Building a Pokémon Selector Web App with Flask and API Integration: A Step-by-Step Tutorial in Python

Welcome to our comprehensive tutorial on creating a Pokémon Selector web application using Flask, a powerful Python web framework, and seamlessly integrating it with the Pokémon API. In this step-by-step guide, we’ll walk you through the process of setting up the development environment, understanding the code structure, and creating interactive web pages to select and explore details about different Pokémon.

Whether you’re a beginner looking to dive into web development or an experienced developer eager to explore API integration with Flask, this tutorial is tailored to provide insights into both aspects. By the end, you’ll have a functional web app that allows users to choose a Pokémon from a dropdown list and view detailed information about their favorite creatures.

Let’s embark on this coding journey, combining Flask’s simplicity with the richness of Pokémon data from the API. Get ready to catch ’em all – not just Pokémon but also valuable insights into Flask web development! 🚀 #Flask #APIIntegration #WebDevelopment #PokémonSelector

See also:JSON and Fetch in JavaScript: A Practical Guide with Pokémon API Examples

Unleash the Power of Flask and API Integration for Pokémon Fun!

In a Flask application, when you use templates, it’s a common practice to save your HTML files in a folder named “templates.” This folder should be in the same directory as your main Python application file (app.py in this case).

So, the structure would look like this:

project_folder/
|-- app.py
|-- templates/
|   |-- index.html
|   |-- pokemon_details.html

By saving your HTML files in the “templates” folder, Flask can automatically locate and render these templates when you use the render_template function in your Python code (as seen in app.py). This follows Flask’s convention for organizing templates.

Make sure that the HTML files are directly inside the “templates” folder, and their filenames match what you specified in your render_template calls (index.html and pokemon_details.html in this case).

  1. Setting Up:
    • Make sure you have Python installed on your system.
    • Install Flask and requests by running pip install Flask requests in your terminal.
  2. Code Structure:
    • The Python code is structured as a Flask web application (app.py).
    • It has two routes:
      • /: Displays a web page with a dropdown list of Pokémon names.
      • /pokemon: Displays detailed information about the selected Pokémon.
  3. Running the Application:
    • Save the Python code in a file (e.g., app.py).
    • Open a terminal and navigate to the directory where app.py is located.
    • Run the application by executing python app.py in the terminal.
  4. Accessing the Web Application:
    • After running the application, you’ll see output indicating that the Flask development server is running.
    • Open a web browser and go to http://localhost:5000/ to access the home page.
    • On the home page, you’ll find a dropdown list of Pokémon names. Select a Pokémon and click the “Submit” button.
  5. Viewing Pokémon Details:
    • After submitting the form, you’ll be redirected to a page displaying detailed information about the selected Pokémon.
    • The details include the Pokémon’s name (capitalized), ID, image, types, abilities, stats, and weight.
  6. Navigation:
    • To go back to the home page, click the “Go Back” link at the bottom of the Pokémon details page.
  7. Understanding the Code:
    • The code uses the Flask framework to create a web server.
    • The requests library is used to make HTTP requests to the Pokémon API (https://pokeapi.co/) to fetch Pokémon data.
    • HTML templates (index.html and pokemon_details.html) are used to structure and present the information on the web pages.
  8. Modifying and Extending:
    • You can modify the code to add more features, improve styling, or integrate additional functionalities.
    • Explore the Flask documentation for more details on building Flask applications.

Remember to stop the Flask development server when you’re done testing or exploring by pressing Ctrl + C in the terminal.

Python Code (app.py)

#pip install Flask requests
from flask import Flask, render_template, request
import requests

app = Flask(__name__)

@app.route('/')
def index():
    # Scrapes the list of Pokémon from the API
    pokemon_list_url = 'https://pokeapi.co/api/v2/pokemon/'
    response = requests.get(pokemon_list_url)
    data = response.json()
    # Creates a list of tuples containing Pokémon names and their respective URLs
    pokemon_list = [(pokemon['name'].capitalize(), pokemon['url']) for pokemon in data['results']]

    return render_template('index.html', pokemon_list=pokemon_list)

@app.route('/pokemon')
def pokemon_details():
    # Gets the URL of the selected Pokémon from the form
    selected_pokemon_url = request.args.get('pokemon_selector')

    # Scrapes details of the selected Pokémon from the API
    response = requests.get(selected_pokemon_url)
    data = response.json()

    return render_template('pokemon_details.html', data=data)

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

HTML Template (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pokémon Selector</title>
</head>
<body>
<h2>Select a Pokémon:</h2>
<!-- Form to select a Pokémon and submit the request to /pokemon route -->
<form action="/pokemon" method="get">
<select name="pokemon_selector">
{% for pokemon_name, pokemon_url in pokemon_list %}
<option value="{{ pokemon_url }}">{{ pokemon_name }}</option>
{% endfor %}
</select>
<button type="submit">Submit</button>
</form>
</body>
</html>

HTML Template (pokemon_details.html)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pokémon Details</title>
</head>
<body>
<!-- Display details of the selected Pokémon -->
<h2>{{ data['name'].capitalize() }} (ID: {{ data['id'] }})</h2>
<img src="{{ data['sprites']['front_default'] }}" alt="{{ data['name'] }}">
<h3>Type(s): {% for type in data['types'] %}{{ type['type']['name'] }}, {% endfor %}</h3>
<h3>Abilities: {% for ability in data['abilities'] %}{{ ability['ability']['name'] }}, {% endfor %}</h3>
{% for stat in data['stats'] %}
<p><strong>{{ stat['stat']['name'] }}:</strong> {{ stat['base_stat'] }}</p>
{% endfor %}
<p><strong>Weight:</strong> {{ data['weight'] / 10 }} kg</p>
<!-- Link to go back to the index page -->
<a href="/">Go Back</a>
</body>
</html>

This code sets up a Flask web application that allows users to select a Pokémon from a dropdown list, and upon submission, it displays detailed information about the selected Pokémon. The data is retrieved from the Pokemon API using the requests library, and the information is rendered using Flask templates. The HTML templates use Jinja2 templating to dynamically generate content based on the data received from the API.

Conclusion

Congratulations! You’ve successfully navigated through the creation of a Pokémon Selector web application using Flask and API integration. Throughout this tutorial, you’ve gained hands-on experience with Flask’s fundamentals, API requests, and HTML templating, equipping you with valuable skills for your web development journey.

As you reflect on your accomplishment, consider exploring further enhancements to your project. You might want to add styling with CSS, incorporate more interactive features using JavaScript, or even expand your knowledge by integrating additional APIs.

Remember, the skills you’ve acquired here can serve as a solid foundation for building various web applications. The combination of Flask’s simplicity and the dynamic data from the Pokémon API opens doors to endless possibilities. Keep experimenting, coding, and evolving your projects – the world of web development awaits your creative touch.

Thank you for joining us on this tutorial adventure. If you have any questions or want to share your creations, feel free to reach out. Happy coding, and may your web development endeavors continue to flourish! 🌐🚀 #Flask #WebDevelopment #APIIntegration #PokémonApp #HappyCoding