### Python Paginated Media Query
Source: https://docs.anilist.co/guide/graphql/pagination
A Python example demonstrating a paginated media search query using the `requests` library. Ensure `requests` is installed (`pip install requests`).
```python
query = '''\nquery ($id: Int, $page: Int, $perPage: Int, $search: String) {\n Page (page: $page, perPage: $perPage) {\n pageInfo {\n currentPage\n hasNextPage\n perPage\n }\n media (id: $id, search: $search) {\n id\n title {\n romaji\n }\n }\n }\n}\n'''
variables = {
'search': 'Fate/Zero',
'page': 1,
'perPage': 3
}
url = 'https://graphql.anilist.co'
response = requests.post(url, json={'query': query, 'variables': variables})
```
--------------------------------
### Rate Limit Headers Example
Source: https://docs.anilist.co/guide/rate-limiting
Inspect these headers in API responses to monitor your current rate limit status.
```http
HTTP/1.1 200 OK
...
other headers here ...
X-RateLimit-Limit: 90
X-RateLimit-Remaining: 59
```
--------------------------------
### Rust Paginated Media Query
Source: https://docs.anilist.co/guide/graphql/pagination
This Rust example uses `reqwest`, `tokio`, and `serde_json` to perform a paginated media search. Ensure these crates are added to your `Cargo.toml`.
```rust
// This example uses 3 crates serde_json, reqwest, tokio
use serde_json::json;
use reqwest::Client;
// Query to use in request
const QUERY: &str = "\nquery ($id: Int, $page: Int, $perPage: Int, $search: String) {\n Page (page: $page, perPage: $perPage) {\n pageInfo {\n currentPage\n hasNextPage\n perPage\n }\n media (id: $id, search: $search) {\n id\n title {\n romaji\n }\n }\n }\n}
";
#[tokio::main]
async fn main() {
let client = Client::new();
// Define query and variables
let json = json!(
{
"query": QUERY,
"variables": {
"search": "Fate/Zero",
"page": 1,
"perPage": 3
}
}
);
// 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 output
let result: serde_json::Value = serde_json::from_str(&resp.unwrap()).unwrap();
println!("{:#?}", result);
}
```
--------------------------------
### Example GraphQL Response JSON
Source: https://docs.anilist.co/guide/graphql
This is the expected JSON response structure when querying for media details with the provided GraphQL query and variables.
```json
{
"data": {
"Media": {
"id": 15125,
"title": {
"romaji": "Teekyuu",
"english": "Teekyuu",
"native": "てーきゅう"
}
}
}
}
```
--------------------------------
### GraphQL Connection Example
Source: https://docs.anilist.co/guide/graphql/connections
This snippet demonstrates how to query for paginated characters associated with a media object, accessing intermediate data like role and voice actors through edges.
```graphql
{
Media {
characters(page: 1) {
edges { # Array of character edges
role
voiceActors { # Array of voice actors of this character for the anime
id
name {
first
last
}
}
}
}
}
}
```
--------------------------------
### Valid Page Query for Media
Source: https://docs.anilist.co/guide/graphql/pagination
This example demonstrates a valid `Page` query to retrieve a paginated list of media. It includes the `pageInfo` field for pagination and a single data field (`media`).
```graphql
{
Page {
pageInfo {
hasNextPage
}
media {
id
}
}
}
```
--------------------------------
### Get media by ID
Source: https://docs.anilist.co/guide/graphql/queries/media
Fetches a specific media entry using its unique ID. Returns a 404 if the ID does not exist or does not match the requested type.
```APIDOC
## Get media by ID
### Description
This is one of the most barebones queries you can make. It will directly return the media with the specified ID. If the ID does not match up with a media, you will receive a `404` response code.
### Method
GraphQL
### Endpoint
N/A (GraphQL Query)
### Parameters
#### Query Parameters
- **id** (Int!) - Required - The unique identifier for the media entry.
### Request Example
```graphql
query ($id: Int) {
Media (id: $id) {
id
title {
romaji
english
native
}
}
}
```
### Response
#### Success Response (200)
- **id** (Int) - The unique identifier of the media.
- **title** (object) - An object containing different title formats for the media.
- **romaji** (String) - The Romaji title of the media.
- **english** (String) - The English title of the media.
- **native** (String) - The native language title of the media.
```
--------------------------------
### Rust GraphQL API Request
Source: https://docs.anilist.co/guide/graphql
Make a GraphQL query to the AniList API using Rust with the reqwest and serde_json crates. This example demonstrates asynchronous request handling and JSON serialization.
```rust
// 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);
}
```
--------------------------------
### Advanced Media Browse Query
Source: https://docs.anilist.co/guide/graphql/queries/media
This query is a comprehensive example used for browsing media, allowing for extensive filtering and sorting. It demonstrates how to fetch media with various parameters like ID, type, season, format, status, and more.
```graphql
query (
$page: Int = 1
$id: Int
$type: MediaType
$isAdult: Boolean = false
$search: String
$format: [MediaFormat]
$status: MediaStatus
$countryOfOrigin: CountryCode
$source: MediaSource
$season: MediaSeason
$seasonYear: Int
$year: String
$onList: Boolean
$yearLesser: FuzzyDateInt
$yearGreater: FuzzyDateInt
$episodeLesser: Int
$episodeGreater: Int
$durationLesser: Int
$durationGreater: Int
$chapterLesser: Int
$chapterGreater: Int
$volumeLesser: Int
$volumeGreater: Int
$licensedBy: [Int]
$isLicensed: Boolean
$genres: [String]
$excludedGenres: [String]
$tags: [String]
$excludedTags: [String]
$minimumTagRank: Int
$sort: [MediaSort] = [POPULARITY_DESC, SCORE_DESC]
) {
Page(page: $page, perPage: 20) {
pageInfo {
hasNextPage
}
media(
id: $id
type: $type
season: $season
format_in: $format
status: $status
countryOfOrigin: $countryOfOrigin
source: $source
search: $search
onList: $onList
seasonYear: $seasonYear
startDate_like: $year
startDate_lesser: $yearLesser
startDate_greater: $yearGreater
episodes_lesser: $episodeLesser
episodes_greater: $episodeGreater
duration_lesser: $durationLesser
duration_greater: $durationGreater
chapters_lesser: $chapterLesser
chapters_greater: $chapterGreater
volumes_lesser: $volumeLesser
volumes_greater: $volumeGreater
licensedById_in: $licensedBy
isLicensed: $isLicensed
genre_in: $genres
genre_not_in: $excludedGenres
tag_in: $tags
tag_not_in: $excludedTags
minimumTagRank: $minimumTagRank
sort: $sort
isAdult: $isAdult
) {
id
title {
romaji
}
}
}
}
```
--------------------------------
### UserStartYearStatistic
Source: https://docs.anilist.co/reference/object/userstartyearstatistic
The UserStartYearStatistic object contains fields that represent aggregated statistics for users based on the year they started engaging with media. It includes metrics like the count of activities, mean score, minutes watched, chapters read, and lists of media IDs, all associated with a specific start year.
```APIDOC
## UserStartYearStatistic
### Description
Represents aggregated statistics for users based on the year they started engaging with media.
### Fields
- **count** (Int!) - The total count of activities or items related to the start year.
- **meanScore** (Float!) - The average score achieved by users starting in this year.
- **minutesWatched** (Int!) - The total minutes watched by users starting in this year.
- **chaptersRead** (Int!) - The total chapters read by users starting in this year.
- **mediaIds** ([Int]!) - A list of media IDs associated with users starting in this year.
- **startYear** (Int) - The specific year this statistic pertains to.
```
--------------------------------
### Get Media Object with List Entry
Source: https://docs.anilist.co/guide/graphql/queries/media-list
Retrieves a Media object and its associated list entry for the authenticated user. If the request is not authenticated, `mediaListEntry` will be null.
```APIDOC
## Get Media Object with List Entry
### Description
Retrieves a `Media` object and its `mediaListEntry` for the authenticated user. If not authenticated, `mediaListEntry` will be null.
### Method
POST
### Endpoint
/v2/graphql
### Parameters
#### Query Parameters
- **id** (Int!) - Required - The ID of the media.
### Request Example
```json
{
"query": "query ($id: Int!) {\n Media(id: $id) {\n id\n title {\n romaji\n }\n mediaListEntry {\n id\n }\n }\n}",
"variables": {
"id": 123
}
}
```
### Response
#### Success Response (200)
- **id** (Int) - The ID of the media.
- **title** (Object) - The title of the media.
- **romaji** (String) - The Romaji title of the media.
- **mediaListEntry** (Object) - The list entry for the authenticated user, or null if not authenticated.
- **id** (Int) - The ID of the list entry.
#### Response Example
```json
{
"data": {
"Media": {
"id": 123,
"title": {
"romaji": "Example Media Title"
},
"mediaListEntry": {
"id": 789
}
}
}
}
```
```
--------------------------------
### PHP Paginated Media Query
Source: https://docs.anilist.co/guide/graphql/pagination
This PHP snippet shows how to make a paginated search request for media using Guzzle HTTP client. Ensure you have Guzzle installed (`composer require guzzlehttp/guzzle`).
```php
$query = ':\nquery ($id: Int, $page: Int, $perPage: Int, $search: String) {\n Page (page: $page, perPage: $perPage) {\n pageInfo {\n currentPage\n hasNextPage\n perPage\n }\n media (id: $id, search: $search) {\n id\n title {\n romaji\n }\n }\n }\n}\n';
$variables = [
"search" => "Fate/Zero",
"page" => 1,
"perPage" => 3
];
$http = new GuzzleHttp
Client;
$response = $http->post('https://graphql.anilist.co', [
'json' => [
'query' => $query,
'variables' => $variables,
]
]);
```
--------------------------------
### Get Media by ID
Source: https://docs.anilist.co/guide/graphql/queries/media
Fetches a specific media entry using its unique ID. Returns a 404 if the ID is not found. Ensure the ID corresponds to the correct media type (anime or manga).
```graphql
query ($id: Int) {
Media (id: $id) {
id
title {
romaji
english
native
}
}
}
```
--------------------------------
### Make Authenticated Request in JavaScript
Source: https://docs.anilist.co/guide/auth/authenticated-requests
Use this snippet to make an authenticated POST request to the AniList API using Node.js fetch. Ensure you have a valid access token and the 'node-fetch' library installed.
```javascript
const fetch = require('node-fetch');
var query = "
{
Viewer {
id
name
}
}
";
const accessToken = getAccessToken();
const url = 'https://graphql.anilist.co',
opions = {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query: query
})
};
fetch(url, options).then(handleResponse, handleError);
function handleResponse(response) {
console.log(response);
}
```
--------------------------------
### Get Media List Entry
Source: https://docs.anilist.co/guide/graphql/queries/media-list
Retrieves a single media list entry for a user. You can query by the list entry ID, or by media ID paired with a user ID or username. The server ignores extra arguments if not provided.
```APIDOC
## Get Media List Entry
### Description
Retrieves a single media list entry. This can be done by the list entry ID itself, or by the media ID usually paired with the user ID or username.
### Method
POST
### Endpoint
/v2/graphql
### Parameters
#### Query Parameters
- **id** (Int) - Optional - The ID of the list entry.
- **mediaId** (Int) - Optional - The ID of the media.
- **userId** (Int) - Optional - The ID of the user.
### Request Example
```json
{
"query": "query ($id: Int, $mediaId: Int, $userId: Int) {\n MediaList(id: $id, mediaId: $mediaId, userId: $userId) {\n id\n media {\n id\n title {\n romaji\n }\n }\n }\n}",
"variables": {
"id": 123,
"mediaId": 456,
"userId": 789
}
}
```
### Response
#### Success Response (200)
- **id** (Int) - The ID of the media list entry.
- **media** (Object) - The media object associated with the list entry.
- **id** (Int) - The ID of the media.
- **title** (Object) - The title of the media.
- **romaji** (String) - The Romaji title of the media.
#### Response Example
```json
{
"data": {
"MediaList": {
"id": 123,
"media": {
"id": 456,
"title": {
"romaji": "Example Media Title"
}
}
}
}
}
```
```
--------------------------------
### Create Media List Entry with PHP
Source: https://docs.anilist.co/guide/graphql/mutations
Use the `SaveMediaListEntry` mutation to create a new media list entry. Provide `mediaId` and `status` to create the entry. The `id` field in the response is the ID of the newly created entry.
```php
$query = '
mutation ($listEntryId: Int, $mediaId: Int, $status: MediaListStatus) {
SaveMediaListEntry(id: $listEntryId, mediaId: $mediaId, status: $status) {
id
status
}
}
';
$variables = [
"mediaId" => 1,
"status" => "CURRENT"
];
$http = new GuzzleHttp
$response = $http->post('https://graphql.anilist.co', [
'json' => [
'query' => $query,
'variables' => $variables,
]
]);
```
```json
{
"data": {
"SaveMediaListEntry": {
"id": 4,
"status": "CURRENT"
}
}
}
```
--------------------------------
### Get Media Relations
Source: https://docs.anilist.co/guide/graphql/queries/media
Fetch all related media entries for a given media ID, including the type of relation and the related media's title.
```graphql
query ($id: Int!) {
Media (id: $id) {
id
title {
romaji
}
relations {
edges {
relationType
node {
id
title {
romaji
}
}
}
}
}
}
```
--------------------------------
### Get Media Relations
Source: https://docs.anilist.co/guide/graphql/queries/media
Retrieves all related media for a given media entry, such as prequels and sequels. It utilizes the `relations` field and `edges` to understand the connection types.
```APIDOC
## Get Media Relations
### Description
Retrieves all related media for a given media entry, such as prequels and sequels. It utilizes the `relations` field and `edges` to understand the connection types.
### Method
GraphQL Query
### Endpoint
N/A (GraphQL)
### Parameters
#### Query Parameters
- **id** (Int!) - Required - The ID of the media entry.
### Request Example
```graphql
query ($id: Int!) {
Media (id: $id) {
id
title {
romaji
}
relations {
edges {
relationType
node {
id
title {
romaji
}
}
}
}
}
}
```
### Response
#### Success Response
- **Media** (Object) - The media object with its relations.
- **id** (Int) - The ID of the media.
- **title** (Object) - The title of the media.
- **romaji** (String) - The Romaji title.
- **relations** (Object) - The relations of the media.
- **edges** (Array) - An array of relation edges.
- **relationType** (String) - The type of relation.
- **node** (Object) - The related media node.
- **id** (Int) - The ID of the related media.
- **title** (Object) - The title of the related media.
- **romaji** (String) - The Romaji title of the related media.
```
--------------------------------
### Get Authenticated User Details
Source: https://docs.anilist.co/guide/graphql/queries/user
Use the `Viewer` query to fetch the ID and name of the currently authenticated user. This query infers the user from the access token.
```graphql
query {
Viewer {
id
name
}
}
```
--------------------------------
### StaffEdge Object
Source: https://docs.anilist.co/reference/object/staffedge
The StaffEdge object provides information about a staff member's connection to a media production. It includes the staff node, the ID of the connection, the staff member's role, and their favorite order.
```APIDOC
## StaffEdge
### Description
Represents a connection between a staff member and a media production, detailing their role and display order in favorites.
### Fields
- **node** (Staff) - The staff member connected to the media.
- **id** (Int) - The unique identifier for this connection.
- **role** (String) - The specific role the staff member played in the production (e.g., Director, Animator).
- **favouriteOrder** (Int) - The order in which this staff member should appear in a user's list of favorites.
```
--------------------------------
### GraphQL Validation Error Response Example
Source: https://docs.anilist.co/guide/graphql/errors
When mutations fail validation rules, an additional `validation` field is included in the error response. These messages can be safely displayed to users.
```json
{
"data": null,
"errors": [
{
"message": "validation",
"status": 400,
"locations": [
{
"line": 2,
"column": 3
}
],
"validation": {
"id": [
"The selected id is invalid."
],
"score": [
"The score may not be greater than 100."
]
}
}
]
}
```
--------------------------------
### UserOptions
Source: https://docs.anilist.co/reference/object/useroptions
Represents a user's general options and preferences.
```APIDOC
## UserOptions
### Description
A user's general options.
### Fields
- **titleLanguage** (UserTitleLanguage) - The language the user wants to see media titles in.
- **displayAdultContent** (Boolean) - Whether the user has enabled viewing of 18+ content.
- **airingNotifications** (Boolean) - Whether the user receives notifications when a show they are watching airs.
- **profileColor** (String) - Profile highlight color (blue, purple, pink, orange, red, green, gray).
- **notificationOptions** ([NotificationOption]) - Notification options.
- **timezone** (String) - The user's timezone offset (Auth user only).
- **activityMergeTime** (Int) - Minutes between activity for them to be merged together. 0 is Never, Above 2 weeks (20160 mins) is Always.
- **staffNameLanguage** (UserStaffNameLanguage) - The language the user wants to see staff and character names in.
- **restrictMessagesToFollowing** (Boolean) - Whether the user only allows messages from users they follow.
- **disabledListActivity** ([ListActivityOption]) - The list activity types the user has disabled from being created from list updates.
```
--------------------------------
### Redirect User for Authorization (HTML)
Source: https://docs.anilist.co/guide/auth/authorization-code
Use this HTML link to redirect users to the AniList authorization URL. Ensure you replace `{client_id}` and `{redirect_uri}` with your application's specific values.
```html
Login with AniList
```
--------------------------------
### Get Light Novels from 2020
Source: https://docs.anilist.co/guide/graphql/queries/media
Retrieve all light novels published in the year 2020 by filtering manga with the NOVEL format and specifying a date range. Defaults to page 1.
```graphql
query ($page: Int = 1) {
Page(page: $page) {
pageInfo {
hasNextPage
}
media(
type: MANGA
format: NOVEL
startDate_greater: 20200000
startDate_lesser: 20210000
) {
id
title {
romaji
}
}
}
}
```
--------------------------------
### Recommendation Queries
Source: https://docs.anilist.co/reference/query
Query for media recommendations with various filters.
```APIDOC
## Recommendation Queries
### Description
Provides functionality to query for media recommendations based on various criteria.
### Query Fields
- **Recommendation** (Recommendation): Retrieves recommendations.
- **id** (Int): Filter by the recommendation ID.
- **mediaId** (Int): Filter by the ID of the media the recommendation is for.
- **mediaRecommendationId** (Int): Filter by the ID of the recommended media.
- **userId** (Int): Filter by the user who created the recommendation.
- **onList** (Boolean): Filter by whether the recommended media is on the authenticated user's list.
- **rating** (Int): Filter by the total rating of the recommendation.
- **rating_greater** (Int): Filter by recommendations with a total rating greater than the specified value.
- **rating_lesser** (Int): Filter by recommendations with a total rating lesser than the specified value.
- **sort** ([RecommendationSort]): The order in which to return the results.
```
--------------------------------
### HTML Link for Authorization
Source: https://docs.anilist.co/guide/auth/implicit
Use this HTML snippet to create a link that redirects the user to AniList for authorization. Ensure you replace `{client_id}` with your application's client ID.
```html
Login with AniList
```
--------------------------------
### Studio Object Fields
Source: https://docs.anilist.co/reference/object/studio
Provides details about the fields that can be queried for a Studio object. This includes basic information like ID and name, as well as relationships to media and user interaction data.
```APIDOC
## Studio Object
Represents an animation or production company.
### Fields
- **id** (Int!) - The id of the studio.
- **name** (String!) - The name of the studio.
- **isAnimationStudio** (Boolean!) - If the studio is an animation studio or a different kind of company.
- **media** (MediaConnection) - The media the studio has worked on.
- **sort** ([MediaSort]) - The order the results will be returned in.
- **isMain** (Boolean) - If the studio was the primary animation studio of the media.
- **onList** (Boolean) -
- **page** (Int) - The page.
- **perPage** (Int) - The amount of entries per page, max 25.
- **siteUrl** (String) - The url for the studio page on the AniList website.
- **isFavourite** (Boolean!) - If the studio is marked as favourite by the currently authenticated user.
- **favourites** (Int) - The amount of user's who have favourited the studio.
```
--------------------------------
### Get Media Entry from Media Object
Source: https://docs.anilist.co/guide/graphql/queries/media-list
When requesting a Media object, you can use the mediaListEntry field to retrieve the list entry for the authenticated user. This field will return null if the request is not authenticated.
```graphql
query ($id: Int!) {
Media(id: $id) {
id
title {
romaji
}
mediaListEntry {
id
}
}
}
```
--------------------------------
### Making a GraphQL Request in JavaScript
Source: https://docs.anilist.co/guide/graphql
This snippet demonstrates how to construct and send a GraphQL query with variables using the Fetch API in JavaScript. It includes basic response and error handling.
```javascript
var query = "\nquery ($id: Int) { # Define which variables will be used in the query (id) \n Media (id: $id, type: ANIME) { # Insert our variables into the query arguments (id) (type: ANIME is hard-coded in the query) \n id \n title { \n romaji \n english \n native \n } \n } \n}";
var variables = {
id: 15125
};
var url = 'https://graphql.anilist.co',
options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query: query,
variables: variables
})
};
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);
}
```
--------------------------------
### Get a Single Media List Entry by ID
Source: https://docs.anilist.co/guide/graphql/queries/media-list
Use this query to fetch a specific media list entry by its ID. It can also accept mediaId and userId, but these will be ignored if an ID is provided.
```graphql
query ($id: Int, $mediaId: Int, $userId: Int) {
MediaList(id: $id, mediaId: $mediaId, userId: $userId) {
id
media {
id
title {
romaji
}
}
}
}
```
--------------------------------
### SaveRecommendation
Source: https://docs.anilist.co/reference/mutation
Saves a recommendation for a media item, linking a base media with a recommended media and assigning a rating.
```APIDOC
## SaveRecommendation
### Description
Recommendation a media.
### Method
mutation
### Parameters
#### Field Arguments
- **mediaId** (Int) - Required - The id of the base media
- **mediaRecommendationId** (Int) - Required - The id of the media to recommend
- **rating** (RecommendationRating) - Required - The rating to give the recommendation
```
--------------------------------
### Studio Object Filters
Source: https://docs.anilist.co/reference/object/page
Filters available for querying Studio objects.
```APIDOC
## Studio Object Filters
### Description
Filters for querying Studio objects, including ID, search queries, and sorting.
### Parameters
#### Query Parameters
- **id** (Int) - Optional - Filter by the studio id.
- **search** (String) - Optional - Filter by search query.
- **id_not** (Int) - Optional - Filter by the studio id.
- **id_in** ([Int]) - Optional - Filter by the studio id.
- **id_not_in** ([Int]) - Optional - Filter by the studio id.
- **sort** ([StudioSort]) - Optional - The order the results will be returned in.
```
--------------------------------
### Update Media List Entry with PHP
Source: https://docs.anilist.co/guide/graphql/mutations
Update an existing media list entry using the `SaveMediaListEntry` mutation. Provide the `listEntryId` along with the fields you wish to update, such as `status`.
```php
$query = '
mutation ($listEntryId: Int, $mediaId: Int, $status: MediaListStatus) {
SaveMediaListEntry(id: $listEntryId, mediaId: $mediaId, status: $status) {
id
status
}
}
';
$variables = [
"listEntryId" => 4,
"status" => "COMPLETED"
];
$http = new GuzzleHttp
$response = $http->post('https://graphql.anilist.co', [
'json' => [
'query' => $query,
'variables' => $variables,
]
]);
```
--------------------------------
### Example API Unavailable Error
Source: https://docs.anilist.co/guide/considerations
This JSON structure illustrates the error response received when the AniList API is temporarily disabled due to stability issues. It includes an error message and a status code.
```json
{
"errors": [
{
"message": "The AniList API has been temporarily disabled due to severe stability issues. Please check the official AniList Discord for more information.",
"status": 403,
"locations": [
{
"line": 1,
"column": 1
}
]
}
],
"data": null
}
```
--------------------------------
### Making a GraphQL Request in PHP
Source: https://docs.anilist.co/guide/graphql
This snippet shows how to send a GraphQL query with variables using the Guzzle HTTP client in PHP. It sets up the query, variables, and makes a POST request to the AniList API.
```php
$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
}
}
}';
$variables = [
"id" => 15125
];
$http = new GuzzleHttp
$response = $http->post('https://graphql.anilist.co', [
'json' => [
'query' => $query,
'variables' => $variables,
]
]);
```
--------------------------------
### Activity
Source: https://docs.anilist.co/reference/query
Retrieves a feed of user activities. Supports extensive filtering and sorting.
```APIDOC
## GET Activity
### Description
Fetches a feed of user activities, such as status updates, comments, and more. Supports a wide range of filters and sorting options.
### Method
GET
### Endpoint
/api/v1/query/activity
### Parameters
#### Query Parameters
- **id** (Int) - Optional - Filter by the activity's unique identifier.
- **userId** (Int) - Optional - Filter by the ID of the user who performed the activity.
- **messengerId** (Int) - Optional - Filter by the ID of the user who sent a message related to the activity.
- **mediaId** (Int) - Optional - Filter by the ID of the media associated with the activity.
- **type** (ActivityType) - Optional - Filter by the type of activity (e.g., ANIME_LIST_UPDATE, COMMENT).
- **isFollowing** (Boolean) - Optional - If true, filters activity to only include users followed by the authenticated user.
- **hasReplies** (Boolean) - Optional - If true, filters activity to only include those with replies.
- **hasRepliesOrTypeText** (Boolean) - Optional - If true, filters activity to include those with replies or of type text.
- **createdAt** (Int) - Optional - Filter by the timestamp when the activity was created.
- **id_not** (Int) - Optional - Exclude activities with this ID.
- **id_in** ([Int]) - Optional - Filter by a list of activity IDs.
- **id_not_in** ([Int]) - Optional - Exclude activities with IDs in this list.
- **userId_not** (Int) - Optional - Exclude activities by this user ID.
- **userId_in** ([Int]) - Optional - Filter by a list of user IDs.
- **userId_not_in** ([Int]) - Optional - Exclude activities by user IDs in this list.
- **messengerId_not** (Int) - Optional - Exclude activities by this messenger ID.
- **messengerId_in** ([Int]) - Optional - Filter by a list of messenger IDs.
- **messengerId_not_in** ([Int]) - Optional - Exclude activities by messenger IDs in this list.
- **mediaId_not** (Int) - Optional - Exclude activities associated with this media ID.
- **mediaId_in** ([Int]) - Optional - Filter by a list of media IDs.
- **mediaId_not_in** ([Int]) - Optional - Exclude activities associated with media IDs in this list.
- **type_not** (ActivityType) - Optional - Exclude activities of this type.
- **type_in** ([ActivityType]) - Optional - Filter by a list of activity types.
- **type_not_in** ([ActivityType]) - Optional - Exclude activities of types in this list.
- **createdAt_greater** (Int) - Optional - Filter by activities created after this timestamp.
- **createdAt_lesser** (Int) - Optional - Filter by activities created before this timestamp.
- **sort** ([ActivitySort]) - Optional - The order in which to sort the results.
### Response
#### Success Response (200)
- **ActivityUnion** (Object) - An object representing the activity feed.
### Response Example
{
"data": {
"Activity": {
"id": 2001,
"type": "ANIME_LIST_UPDATE",
"user": {
"name": "UserA"
},
"createdAt": 1678886400
}
}
}
```
--------------------------------
### GraphQL Error Response Example
Source: https://docs.anilist.co/guide/graphql/errors
This is a typical error response from the GraphQL API, indicating a query issue such as requesting a non-existent field. Always check the `errors` field, even with a 200 status code.
```json
{
"data": null,
"errors": [
{
"message": "Cannot query field \"nonexistentField\" on type \"MediaList\".",
"status": 400,
"locations": [
{
"line": 4,
"column": 5
}
]
}
]
}
```
--------------------------------
### Get Light Novels from 2020
Source: https://docs.anilist.co/guide/graphql/queries/media
Fetches all light novels published in the year 2020. This query filters by media type `MANGA` with format `NOVEL` and uses date range arguments for precise filtering.
```APIDOC
## Get Light Novels from 2020
### Description
Fetches all light novels published in the year 2020. This query filters by media type `MANGA` with format `NOVEL` and uses date range arguments for precise filtering.
### Method
GraphQL Query
### Endpoint
N/A (GraphQL)
### Parameters
#### Query Parameters
- **page** (Int = 1) - Optional - The page number for pagination. Defaults to 1.
### Request Example
```graphql
query ($page: Int = 1) {
Page(page: $page) {
pageInfo {
hasNextPage
}
media(
type: MANGA
format: NOVEL
startDate_greater: 20200000
startDate_lesser: 20210000
) {
id
title {
romaji
}
}
}
}
```
### Response
#### Success Response
- **Page** (Object) - The page object containing media results.
- **pageInfo** (Object) - Information about the pagination.
- **hasNextPage** (Boolean) - Indicates if there is a next page.
- **media** (Array) - An array of media objects.
- **id** (Int) - The ID of the media.
- **title** (Object) - The title of the media.
- **romaji** (String) - The Romaji title.
```
--------------------------------
### Studio
Source: https://docs.anilist.co/reference/query
Retrieves information about a studio. Can filter by ID or search by name.
```APIDOC
## GET Studio
### Description
Fetches details about a specific animation or manga studio.
### Method
GET
### Endpoint
/api/v1/query/studio
### Parameters
#### Query Parameters
- **id** (Int) - Optional - Filter by the studio's unique identifier.
- **search** (String) - Optional - Filter by a search query against studio names.
- **id_not** (Int) - Optional - Exclude studios with this ID.
- **id_in** ([Int]) - Optional - Filter by a list of studio IDs.
- **id_not_in** ([Int]) - Optional - Exclude studios with IDs in this list.
- **sort** ([StudioSort]) - Optional - The order in which to sort the results.
### Response
#### Success Response (200)
- **Studio** (Object) - An object containing the studio's details.
### Response Example
{
"data": {
"Studio": {
"id": 1,
"name": "Kyoto Animation",
"isAnimationStudio": true
}
}
}
```
--------------------------------
### RecommendationConnection
Source: https://docs.anilist.co/reference/object/recommendationconnection
Represents a connection to a list of recommendations, enabling pagination.
```APIDOC
## RecommendationConnection
### Description
Represents a connection to a list of recommendations, enabling pagination. This object is part of the AniList API's data fetching capabilities.
### Fields
- **edges** ([RecommendationEdge]): A list of edges, where each edge contains a node and cursor for pagination.
- **nodes** ([Recommendation]): A list of the actual recommendation objects.
- **pageInfo** (PageInfo): The pagination information, including details about the current page, next page, and whether there are more pages.
```
--------------------------------
### StudioConnection
Source: https://docs.anilist.co/reference/object/studioconnection
Represents a connection to a list of studios, enabling paginated access to studio data. It includes edges for detailed connection information, nodes for the actual studio objects, and pageInfo for pagination controls.
```APIDOC
## StudioConnection
### Description
Represents a connection to a list of studios, enabling paginated access to studio data. It includes edges for detailed connection information, nodes for the actual studio objects, and pageInfo for pagination controls.
### Fields
- **edges** ([StudioEdge]) - A list of StudioEdge objects, representing the connection between studios.
- **nodes** ([Studio]) - A list of Studio objects, representing the actual studio data.
- **pageInfo** (PageInfo) - The pagination information, including details about the current page, next page, and total count.
```
--------------------------------
### Invalid Page Query with Multiple Data Fields
Source: https://docs.anilist.co/guide/graphql/pagination
This example shows an invalid `Page` query because it attempts to fetch paginated data for multiple types (`media` and `characters`) in a single query. Only one data field is permitted per `Page` query.
```graphql
{
Page {
pageInfo {
hasNextPage
}
media {
id
}
characters {
id
}
}
}
```
--------------------------------
### FormatStats
Source: https://docs.anilist.co/reference/object/formatstats
Retrieves the user's statistics for different media formats.
```APIDOC
## FormatStats
### Description
Retrieves the user's statistics for different media formats, including the format type and the amount associated with it.
### Endpoint
/formatstats
### Parameters
#### Query Parameters
- **format** (MediaFormat) - Optional - The media format to filter by.
- **amount** (Int) - Optional - The amount of media in a specific format.
### Response
#### Success Response (200)
- **format** (MediaFormat) - The type of media format.
- **amount** (Int) - The number of media items in that format.
```
--------------------------------
### Get Full Media List Collection
Source: https://docs.anilist.co/guide/graphql/queries/media-list
Retrieves a user's full media list, split by status and custom lists. The `type` argument is required, and either `userId` or `userName` must be provided. Note: This query is limited to the 11,000 most recently updated unique entries.
```APIDOC
## Get Full Media List Collection
### Description
Retrieves a user's complete media list, automatically split by status and custom lists. Requires `type` and either `userId` or `userName`. Limited to 11,000 most recently updated entries.
### Method
POST
### Endpoint
/v2/graphql
### Parameters
#### Query Parameters
- **type** (MediaType!) - Required - The type of media to retrieve (e.g., ANIME, MANGA).
- **userId** (Int) - Optional - The ID of the user.
- **userName** (String) - Optional - The username of the user.
### Request Example
```json
{
"query": "query ($type: MediaType!, $userId: Int!) {\n MediaListCollection(type: $type, userId: $userId) {\n lists {\n name\n entries {\n id\n media {\n id\n title {\n romaji\n }\n }\n }\n }\n }\n}",
"variables": {
"type": "ANIME",
"userId": 789
}
}
```
### Response
#### Success Response (200)
- **lists** (Array) - An array of lists, each containing entries.
- **name** (String) - The name of the list (e.g., 'Watching', 'Completed', custom list name).
- **entries** (Array) - An array of media list entries within this list.
- **id** (Int) - The ID of the media list entry.
- **media** (Object) - The media object associated with the list entry.
- **id** (Int) - The ID of the media.
- **title** (Object) - The title of the media.
- **romaji** (String) - The Romaji title of the media.
#### Response Example
```json
{
"data": {
"MediaListCollection": {
"lists": [
{
"name": "Watching",
"entries": [
{
"id": 101,
"media": {
"id": 201,
"title": {
"romaji": "Anime Title 1"
}
}
},
{
"id": 102,
"media": {
"id": 202,
"title": {
"romaji": "Anime Title 2"
}
}
}
]
},
{
"name": "Custom List Name",
"entries": [
{
"id": 103,
"media": {
"id": 203,
"title": {
"romaji": "Anime Title 3"
}
}
}
]
}
]
}
}
}
```
```
--------------------------------
### ListActivityOption
Source: https://docs.anilist.co/reference/object/listactivityoption
Represents the options available for configuring list activity settings. It allows specifying whether the activity is disabled and its associated media list status type.
```APIDOC
## ListActivityOption
### Description
Represents the options available for configuring list activity settings. It allows specifying whether the activity is disabled and its associated media list status type.
### Fields
- **disabled** (Boolean) - Indicates if the activity is disabled.
- **type** (MediaListStatus) - Specifies the type of the media list status for the activity.
```
--------------------------------
### Get Full Media List Collection
Source: https://docs.anilist.co/guide/graphql/queries/media-list
Use the MediaListCollection query to retrieve a user's entire media list, split by status and custom lists. The type argument is required, and either userId or userName must be provided. Note the current limit of 11,000 unique entries.
```graphql
query ($type: MediaType!, $userId: Int!) {
MediaListCollection(type: $type, userId: $userId) {
lists {
name
entries {
id
media {
id
title {
romaji
}
}
}
}
}
}
```