Yesterday, we learned that Python can request information from an API.
Today, we will learn how to pull specific pieces of information out of the API response.
Instead of printing the entire JSON response, we will display only the information we want the user to see.
By the end of today, you should be able to:
- Make a request to an API using Python
- Convert the response into JSON
- Access specific values from a dictionary
- Use user input to search for a Pokémon
- Display clean, readable output
- Handle a Pokémon that is not found
On Day 1, we used code like this:
import requests
url = "https://pokeapi.co/api/v2/pokemon/pikachu"
response = requests.get(url)
print(response.status_code)
print(response.json())This worked, but it printed a lot of information.
Today, we want to make the output easier to read.
Instead of printing everything, we will choose specific pieces of data.
Create a new Python file named:
api_day_2.py
At the top of the file, import the requests library:
import requestsThe requests library lets Python get information from websites and APIs.
Instead of always searching for Pikachu, we want the user to choose a Pokémon.
Add this code:
pokemon_name = input("Enter a Pokémon name: ").lower()This does two things:
- It asks the user to type a Pokémon name.
- It converts the name to lowercase.
Example:
Enter a Pokémon name: Charizard
Python stores it as:
charizard
This helps because the API expects lowercase names.
Now we need to create the API URL using the Pokémon name the user typed.
Add this code:
url = f"https://pokeapi.co/api/v2/pokemon/{pokemon_name}"This is called an f-string.
An f-string lets us place a variable inside a string.
If the user types:
pikachu
The URL becomes:
https://pokeapi.co/api/v2/pokemon/pikachu
If the user types:
charizard
The URL becomes:
https://pokeapi.co/api/v2/pokemon/charizard
Now we need Python to request information from the API.
Add this code:
response = requests.get(url)This sends a request to the PokéAPI.
The API will send back a response.
Before we use the data, we should check if the request worked.
Add this code:
if response.status_code == 200:
print("Pokémon found!")
else:
print("Pokémon not found.")A status code tells us what happened with the request.
| Status Code | Meaning |
|---|---|
| 200 | The request worked |
| 404 | The Pokémon was not found |
| 500 | Something went wrong on the server |
A status code of 200 means the API found the Pokémon.
A status code of 404 means the API could not find what we searched for.
If the request worked, we need to convert the response into JSON data.
Update your if statement like this:
if response.status_code == 200:
data = response.json()
print("Pokémon found!")
else:
print("Pokémon not found.")This line is important:
data = response.json()It takes the response from the API and converts it into data Python can work with.
Most API data works like dictionaries and lists.
Now we can pull out one specific piece of information.
Add this inside the if statement:
print("Name:", data["name"])Your code should now look like this:
import requests
pokemon_name = input("Enter a Pokémon name: ").lower()
url = f"https://pokeapi.co/api/v2/pokemon/{pokemon_name}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print("Name:", data["name"])
else:
print("Pokémon not found.")Run your program and test it with:
pikachu
You should see:
Name: pikachu
The API gives us the Pokémon name in lowercase.
We can use .title() to make it look better.
Change this:
print("Name:", data["name"])To this:
print("Name:", data["name"].title())Now the output should look like this:
Name: Pikachu
Now add more values from the API data.
Inside the if statement, add:
print("ID:", data["id"])
print("Height:", data["height"])
print("Weight:", data["weight"])Your code should now look like this:
import requests
pokemon_name = input("Enter a Pokémon name: ").lower()
url = f"https://pokeapi.co/api/v2/pokemon/{pokemon_name}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print("Name:", data["name"].title())
print("ID:", data["id"])
print("Height:", data["height"])
print("Weight:", data["weight"])
else:
print("Pokémon not found.")Right now the output works, but we can make it easier to read.
Update the print statements like this:
print("\n--- Pokémon Info ---")
print("Name:", data["name"].title())
print("ID:", data["id"])
print("Height:", data["height"])
print("Weight:", data["weight"])The \n adds a blank line before the heading.
Example output:
Enter a Pokémon name: charizard
--- Pokémon Info ---
Name: Charizard
ID: 6
Height: 17
Weight: 905
Test your program with at least 3 real Pokémon.
Try these:
pikachu
charizard
bulbasaur
squirtle
eevee
snorlax
lucario
gengar
dragonite
mewtwo
Make sure your program works for each one.
Now test your program with a fake Pokémon name.
Example:
notapokemon
Your program should not crash.
It should display:
Pokémon not found.
This is called error handling.
Good programs should handle mistakes without crashing.
By the end of today, your code should look similar to this:
import requests
pokemon_name = input("Enter a Pokémon name: ").lower()
url = f"https://pokeapi.co/api/v2/pokemon/{pokemon_name}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print("\n--- Pokémon Info ---")
print("Name:", data["name"].title())
print("ID:", data["id"])
print("Height:", data["height"])
print("Weight:", data["weight"])
else:
print("Pokémon not found.")Today you learned how to:
- Ask the user for input
- Use the input inside an API URL
- Send an API request with Python
- Check if the request worked
- Convert the response into JSON
- Use dictionary keys to access specific data
- Display clean output for the user
- Handle invalid searches
pokemon_name = input("Enter a Pokémon name: ").lower()This asks the user for a Pokémon name.
url = f"https://pokeapi.co/api/v2/pokemon/{pokemon_name}"This uses the user’s Pokémon name inside the API URL.
response = requests.get(url)This asks the API for data.
if response.status_code == 200:This checks if the Pokémon was found.
data = response.json()This turns the API response into data Python can use.
data["name"]
data["id"]
data["height"]
data["weight"]These pull specific values out of the API data.
Incorrect:
print(data[name])Correct:
print(data["name"])Dictionary keys that are words need quotation marks.
Incorrect:
print(response["name"])Correct:
data = response.json()
print(data["name"])The response is the package from the API.
The JSON data is what we get after opening the package.
Incorrect:
if response.status_code == 200:
data = response.json()
print(data["name"])Correct:
if response.status_code == 200:
data = response.json()
print(data["name"])Python uses indentation to know what belongs inside the if statement.
Some Pokémon names may not work if they have spaces or special characters.
For today, use simple names like:
pikachu
charizard
eevee
snorlax
mewtwo
Before you turn in your work, make sure you completed all of these:
- Created a file named
api_day_2.py - Imported
requests - Asked the user for a Pokémon name
- Used an f-string to build the API URL
- Sent a request using
requests.get() - Checked if the status code was
200 - Converted the response to JSON
- Displayed the Pokémon’s name
- Displayed the Pokémon’s ID
- Displayed the Pokémon’s height
- Displayed the Pokémon’s weight
- Tested with at least 3 real Pokémon
- Tested with 1 fake Pokémon
- Made sure the program does not crash
Answer these questions in a comment at the bottom of your Python file.
# Reflection Questions:
# 1. What does response.json() do?
# 2. What does data["name"] mean?
# 3. Why do we check response.status_code before using the data?
# 4. What is the difference between printing the entire JSON response and printing specific values?
# 5. What other Pokémon information would you like to display later?Add one more value from the API response.
Inside your if statement, add:
print("Base Experience:", data["base_experience"])Example output:
Base Experience: 112
Add lines or spacing to make your output cleaner.
Example:
print("====================")
print(" Pokémon Info")
print("====================")Example output:
====================
Pokémon Info
====================
Name: Pikachu
ID: 25
Height: 4
Weight: 60
Try adding a while loop so the user can search more than once.
Example idea:
while True:
pokemon_name = input("Enter a Pokémon name or type quit: ").lower()
if pokemon_name == "quit":
print("Goodbye!")
breakThis is more advanced, but it will make your program feel more like a real app.
Try creating a function to display the Pokémon information.
Example:
def display_pokemon(data):
print("\n--- Pokémon Info ---")
print("Name:", data["name"].title())
print("ID:", data["id"])
print("Height:", data["height"])
print("Weight:", data["weight"])Then you can call the function like this:
display_pokemon(data)Functions help keep your code organized.
Before you finish, answer these three questions:
1. What is one key you used from the JSON data?
2. Why should we check the status code before using the data?
3. What is one thing you want your final Pokédex app to display?
By the end of today, your program should no longer print the entire JSON response.
Instead, it should ask the user for a Pokémon and display clean information like this:
--- Pokémon Info ---
Name: Pikachu
ID: 25
Height: 4
Weight: 60
Tomorrow, we will learn how to work with more complicated API data, including lists inside dictionaries.