Skip to content

What is GraphQL?

GraphQL is a strongly typed API query language. It allows clients to define the structure of data required and the server will respond with data in the same structure. This helps avoid the problems of both over and under-fetching data, while also allowing for a more powerful and flexible API.

Prerequisite Knowledge

Before continuing, it is highly recommended that you familiarize yourself with GraphQL. The official GraphQL documentation is a good place to start.

Making a GraphQL API request

AniList requires all GraphQL requests be made as POST requests to https://graphql.anilist.co.

When making a request, you will need to include 2 objects in your payload: query and variables.

  • query: This is your query or mutation string. It defines the data and shape of data that you would like.
  • variables: Contains the values for the variables used within your query.

The variables object is optional if you are not using any, however, it is recommended that you use variables wherever it makes sense.

Example Query

Let's create a simple query to get an anime by it's unique ID.

Apollo Studio

js
// Here we define our query as a multi-line string
// Storing it in a separate .graphql/.gql file is also possible
var query = `
query ($id: Int) { # Define which variables will be used in the query (id)
  Media (id: $id, type: ANIME) { # Insert our variables into the query arguments (id) (type: ANIME is hard-coded in the query)
    id
    title {
      romaji
      english
      native
    }
  }
}
`;

// Define our query variables and values that will be used in the query request
var variables = {
    id: 15125
};

// Define the config we'll need for our Api request
var url = 'https://graphql.anilist.co',
    options = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        },
        body: JSON.stringify({
            query: query,
            variables: variables
        })
    };

// Make the HTTP Api request
fetch(url, options).then(handleResponse)
    .then(handleData)
    .catch(handleError);

function handleResponse(response) {
    return response.json().then(function (json) {
        return response.ok ? json : Promise.reject(json);
    });
}

function handleData(data) {
    console.log(data);
}

function handleError(error) {
    alert('Error, check console');
    console.error(error);
}
php
// Here we define our query as a multi-line string
$query = '
query ($id: Int) { # Define which variables will be used in the query (id)
  Media (id: $id, type: ANIME) { # Insert our variables into the query arguments (id) (type: ANIME is hard-coded in the query)
    id
    title {
      romaji
      english
      native
    }
  }
}
';

// Define our query variables and values that will be used in the query request
$variables = [
    "id" => 15125
];

// Make the HTTP Api request
$http = new GuzzleHttp\Client;
$response = $http->post('https://graphql.anilist.co', [
    'json' => [
        'query' => $query,
        'variables' => $variables,
    ]
]);
py
# Here we define our query as a multi-line string
query = '''
query ($id: Int) { # Define which variables will be used in the query (id)
  Media (id: $id, type: ANIME) { # Insert our variables into the query arguments (id) (type: ANIME is hard-coded in the query)
    id
    title {
      romaji
      english
      native
    }
  }
}
'''

# Define our query variables and values that will be used in the query request
variables = {
    'id': 15125
}

url = 'https://graphql.anilist.co'

# Make the HTTP Api request
response = requests.post(url, json={'query': query, 'variables': variables})
rs
// This example uses the following crates:
// serde_json = "1.0"
// reqwest = "0.11.8"
// tokio = { version = "1.0", features = ["macros", "rt-multi-thread"] }

use serde_json::json;
use reqwest::Client;

// Query to use in request
const QUERY: &str = "
query ($id: Int) { # Define which variables will be used in the query (id)
  Media (id: $id, type: ANIME) { # Insert our variables into the query arguments (id) (type: ANIME is hard-coded in the query)
    id
    title {
      romaji
      english
      native
    }
  }
}
";

#[tokio::main]
async fn main() {
    let client = Client::new();
    // Define query and variables
    let json = json!({"query": QUERY, "variables": {"id": 15125}});
    // Make HTTP post request
    let resp = client.post("https://graphql.anilist.co/")
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .body(json.to_string())
                .send()
                .await
                .unwrap()
                .text()
                .await;
    // Get json
    let result: serde_json::Value = serde_json::from_str(&resp.unwrap()).unwrap();
    println!("{:#}", result);
}

The request in the above example will return the following JSON response:

json
{
  "data": {
    "Media": {
      "id": 15125,
      "title": {
        "romaji": "Teekyuu",
        "english": "Teekyuu",
        "native": "てーきゅう"
      }
    }
  }
}

Tooling

GraphQL has been used in major projects throughout the industry for over a decade, including Airbnb, Intuit, Microsoft, and more. It is battle tested and has many powerful tools for you to use.

These are some recommended tools for working with AniList:

  • Apollo Studio

    Apollo Studio is a powerful tool for exploring and testing your GraphQL queries. It is a great way to get started with GraphQL and AniList.

  • GraphQL Codegen

    Skip service-specific API clients and generate always up-to-date typings for your language of choice.