How to fetch data from the Anilist API (GraphQL) using Axios
Now I will not be going too much into what GraphQL is exactly but what you should know is that it is a query language for your APIs that is fundamentally different from the good ol’ RESTful APIs. In GQL, we make a post request to our API rather than making different requests for different endpoints.
For fetching different data, we can just make a post request to a single endpoint for the API specifying what data we need in the query that we pass in.
https://graphql.anilist.co
Since this is a going to be a very simple tutorial, I will be just fetching a small amount of data from the API, but you can add on to this and scale it up if you want to in your project.
Let’s first install axios and instantiate it in our code.
const axios = require("axios");
Now let’s start building our query where we specify what and how much data we want.
Now let’s break this down. query
is the beginning of our query in which we have to initialize the variables that we want to use. By default, the API returns a single result object so if we want multiple results, we have to wrap our media
query inside a Page
query. The Page query also provides the pageInfo
field which provides information about the current page and total results count.
The media
query is where the magic happens. Here we can just pass in the variable we passed in our parent query
to get corresponding results filtered by that search string. In my example, I am just fetching the id, title, type and the genres of top 3 anime based on users rating and the search query (at the time of writing) but you can fetch different kinds of data and apply multiple types of sorting. This is the type of flexibility that GraphQL offers making it much easier to make API calls. You can check out the Anilist GraphQL Reference guide here
We can now pass in the values of the variables that we initialized in our query in a separate variables
object. Here, I am just getting a single page of result with only 3 items.
The main part of our code is done. Now we can combine all these blocks of code with our axios api call inside an async function and we will be DONE.
This is how the result data will look like if I searched for “shingeki”.
That’s… pretty much it. Now you know how to get data of your favorite anime with just a few lines of code. I also use this in my own project: AniKo.
If you liked this tutorial you can give clap and share this post or even buy me a coffee! Appreciated ;)