Fetch data from anilist API using Java

Program to fetch data from anilist API using Java

To fetch data from the AniList API using Java, you typically need to perform the following steps:

  1. Set up the HTTP Request: Use an HTTP client to send a request to the AniList API. Java provides several libraries for this, such as HttpURLConnection, Apache HttpClient, or the more modern java.net.http.HttpClient in Java 11+.
  2. Authentication: Some endpoints of the AniList API require authentication. You can obtain an access token by registering an application on AniList and using OAuth2. The token should be included in the request header for secure API access.
  3. Parsing the Response: The response from the AniList API is usually in JSON format. Use a JSON parsing library like Jackson, Gson, or JSON-P to deserialize the JSON response into Java objects.
  4. Handling Data: Process the data as required by your application, such as displaying it or storing it in a database.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class AniListFetcher {
    private static final String ANILIST_API_URL = "https://graphql.anilist.co";
    private static final String QUERY = "{ Media(id: 1) { id title { romaji } } }"; // Example query

    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(ANILIST_API_URL))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString("{\"query\": \"" + QUERY + "\"}"))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(response.body());
        System.out.println(jsonNode.toPrettyString());
    }
}

Key Points

  • GraphQL Endpoint: The AniList API uses GraphQL, so you’ll need to format your query according to GraphQL syntax.
  • Error Handling: Include error handling for HTTP errors and JSON parsing issues.
  • Dependencies: You may need to add dependencies for libraries like Jackson if you’re using a build tool like Maven or Gradle.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top