Fetch Anime poster from AniList API using Python
In this tutorial, we are going to fetch cover pictures of Anime shows using Python by requesting data using AniList API. API can be used to communicate between different software applications, it acts as a median for different applications.
I wrote a program that will take Anime name as user input and show the anime poster along with the name of the anime.
Requirements:
- Matplotlib
- Requests
To get started you need to install these two Python components if not present on your system already. You can install these using PIP which is a package installer for Python programming language. You can install it on your system by opening Command Prompt if you are using Windows or Terminal if you are using Linux/Mac operating system and run the following code.
pip install matplotlib requests
Making a request:
Here we will be using post()
method which will send a POST request to a specific url. We will be using requests.post()
function which takes various kinds of parameters such as url, data, json etc.
Syntax:
response = requests.post(url, json={key: value})
Here to retrieve data from AniList I’ve made an API call to the AniList API and retrieved the information about different Animes. I made a post function to retrieve the Anime title and cover-picture.
Retrive Anime Poster from AniList:
Code:
import requests import matplotlib.pyplot as plt from PIL import Image from io import BytesIO #Defined query as multiline string query = ''' query ($title: String) { Media(search: $title, type: ANIME){ coverImage{ large } title { english } } } ''' url = 'https://graphql.anilist.co' #taking Input input_title = input('Enter Anime Title: ') variables = { 'title': input_title, } #Make API request response = requests.post(url, json={'query': query, 'variables': variables}) data = response.json() image_url = data['data']['Media']['coverImage']['large'] #Open the image and storing it to a new variable image_response = requests.get(image_url) cover_image = Image.open(BytesIO(image_response.content)) #Plotting the Image plt.imshow(cover_image) plt.xlabel(data['data']['Media']['title']['english'], fontweight='bold', fontsize=15) plt.show()
Input:
Enter Anime Title: One Piece
Output:
This is how we can retrieve Anime posters in Python using AniList API.
Leave a Reply