Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
274: Making HTTP Requests with the requests Library
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
requestslibrary. - 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
titlevalue of the first 5 items.
There are no comments for now.