Python Lesson 24: Web Requests with Python
Now put it all together: use the requests library to call real APIs from Python. This is one of the most useful skills in Python programming.
Install the requests Library
# Run this in Terminal or Command Prompt:
# pip install requests
# Then import it in your Python file:
import requests
Making Your First API Call
import requests
# Call a free API - get a random cat fact
response = requests.get("https://catfact.ninja/fact")
# Check if it worked
print(response.status_code) # 200 = success
# Get the JSON data
data = response.json() # auto-parses JSON!
print(data["fact"]) # prints the cat fact
Working with Responses
import requests
url = "https://api.agify.io"
params = {"name": "Alice"} # query parameters
response = requests.get(url, params=params)
# Response attributes
print(response.status_code) # 200
print(response.url) # full URL with params
print(response.text) # raw text response
data = response.json()
print(data) # {"name":"Alice","age":30,...}
Error Handling for API Calls
import requests
def fetch_joke():
try:
url = "https://official-joke-api.appspot.com/random_joke"
response = requests.get(url, timeout=5) # 5 second timeout
response.raise_for_status() # raises error for 4xx/5xx
joke = response.json()
print(f"Setup: {joke['setup']}")
print(f"Punchline: {joke['punchline']}")
except requests.exceptions.ConnectionError:
print("No internet connection!")
except requests.exceptions.Timeout:
print("Request timed out!")
except requests.exceptions.HTTPError as e:
print(f"HTTP Error: {e}")
fetch_joke()
Real Project: Weather App
import requests
def get_weather(city):
# wttr.in is a free weather API - no key needed!
url = f"https://wttr.in/{city}?format=j1"
try:
response = requests.get(url, timeout=5)
data = response.json()
current = data["current_condition"][0]
temp_c = current["temp_C"]
feels_like = current["FeelsLikeC"]
description = current["weatherDesc"][0]["value"]
print(f"Weather in {city}:")
print(f"Temperature: {temp_c}C (feels like {feels_like}C)")
print(f"Conditions: {description}")
except Exception as e:
print(f"Could not get weather: {e}")
city = input("Enter a city: ")
get_weather(city)
🏋️ Practice Task
Build a Dog Image Fetcher. Use the free API: https://dog.ceo/api/breeds/image/random to get a random dog image URL. Print the URL. Then let the user choose a breed from a list you display (use https://dog.ceo/api/breeds/list/all to get all breeds).
💡 Hint: response.json()[“message”] gives the image URL. Parse the breeds response and print the keys.