Skip to Content
Course content

274: Making HTTP Requests with the requests Library

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Up until now, our Python scripts have lived in a bubble, processing data we've already provided. But the real power of the language comes when you start talking to the rest of the internet. For that, you want the requests library. I've tried using the built-in urllib a few times in my career, and frankly, it's a headache. requests is the industry standard because it's intuitive and handles the messy parts of HTTP for you.

Let's build a quick tool that grabs data from the PokéAPI—a free, public API—to find out a specific Pokémon's weight and abilities. It's a simple example, but it covers the exact workflow you'll use for almost every API integration you ever write.

Grabbing data from the wild

First, we need to make a GET request. I'll start by importing the library and targeting a specific endpoint for Pikachu. Notice how I'm storing the result in a variable called response; this object contains everything the server sent back, not just the data we want.

import requests

pokemon_name = "pikachu"
url = f"https://pokeapi.co/api/v2/pokemon/{pokemon_name}"

response = requests.get(url)
print(response)

If you run this, you'll see <Response [200]>. That 200 is the HTTP status code for "OK." It's always a good habit to check this before you try to process the data, otherwise, your script will crash blindly if the API is down or the Pokémon doesn't exist.

The "Gotcha" with response objects

Here is where I usually trip up when I'm rushing. I'll try to access the data as if the response object itself is a dictionary. Let's see what happens:

# This is the mistake I often make
print(response["weight"]) 

This will throw a TypeError. Why? Because response is a complex object containing headers, status codes, and encoding info. The actual data we want is sitting in the body of the response as a JSON string. To use it as a Python dictionary, we have to call the .json() method.

# The correction
data = response.json()
print(data["weight"])

Cleaning up the output

Now that we have the data in a dictionary, we can dig into it. The PokéAPI nests its data quite a bit, so to get a list of abilities, we have to iterate through a list of dictionaries. I'll wrap this in a simple function to make it reusable for any Pokémon.

import requests

def get_pokemon_info(name):
    url = f"https://pokeapi.co/api/v2/pokemon/{name.lower()}"
    response = requests.get(url)
    
    if response.status_code == 200:
        data = response.json()
        weight = data["weight"]
        # Using a list comprehension to pull out just the ability names
        abilities = [a["ability"]["name"] for a in data["abilities"]]
        
        print(f"Name: {name.capitalize()}")
        print(f"Weight: {weight}")
        print(f"Abilities: {', '.join(abilities)}")
    else:
        print(f"Couldn't find {name}. Check your spelling!")

get_pokemon_info("charizard")

That's the core loop: request the URL, verify the status code, parse the JSON, and extract the specific keys you need. It's a pattern you'll repeat a thousand times.




📋 Practical Task

Extracting Post Titles from JSONPlaceholder

Your task is to write a script that interacts with the JSONPlaceholder API (a fake API used for testing). Specifically, you need to fetch a list of posts and print only the titles of the first 5 posts.

  • Use the endpoint: https://jsonplaceholder.typicode.com/posts
  • Make a GET request using the requests library.
  • Verify that the request was successful (status code 200).
  • Parse the response as JSON (which will be a list of dictionaries in this case).
  • Use a loop or slicing to print the title value of the first 5 items.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.