Python API Client Examples
Short, runnable programs that show python api example: build an api client in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python API Example: Build an API Client lesson.
1Filter on the server with query parameters
params={"userId": 2} asks the server for one user's todos only. response.url shows the full URL that requests built. (Live request: the exact output depends on the API.)
import requests
url = "https://jsonplaceholder.typicode.com/todos"
response = requests.get(url, params={"userId": 2}, timeout=10)
response.raise_for_status()
print(response.url)
todos = response.json()
still_open = [todo["title"] for todo in todos if not todo["completed"]]
print(len(todos), "todos,", len(still_open), "still open")
print("First open:", still_open[0])Expected outputhttps://jsonplaceholder.typicode.com/todos?userId=2
20 todos, 12 still open
First open: suscipit repellat esse quibusdam voluptatem incidunt
2Handle a missing resource without crashing
Asking for something that does not exist returns status 404. Catching HTTPError inside a helper lets the caller simply check for None. (Live request.)
import requests
def get_post(post_id):
url = f"https://jsonplaceholder.typicode.com/posts/{post_id}"
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
except requests.HTTPError:
return None
return response.json()
for post_id in [1, 9999]:
post = get_post(post_id)
if post is None:
print(f"Post {post_id}: not found")
else:
print(f"Post {post_id}: {post['title'][:30]}...")Expected outputPost 1: sunt aut facere repellat provi...
Post 9999: not found
3Test the report offline with sample data
The processing code only needs lists and dictionaries shaped like the API's responses. Hand-made sample data makes it quick to test, and the output never changes.
posts = [
{"userId": 1, "id": 1, "title": "Planning a trip"},
{"userId": 1, "id": 2, "title": "Packing light"},
{"userId": 2, "id": 3, "title": "Ten quick dinners"},
{"userId": 3, "id": 4, "title": "Learning Python in the browser"},
{"userId": 2, "id": 5, "title": "Bread at home"},
]
users = [{"id": 1, "name": "Asha"}, {"id": 2, "name": "Ben"}, {"id": 3, "name": "Chen"}]
names = {user["id"]: user["name"] for user in users}
per_user = {}
for post in posts:
per_user[post["userId"]] = per_user.get(post["userId"], 0) + 1
for user_id, count in per_user.items():
print(f"{names[user_id]}: {count} post(s)")
titles = [post["title"] for post in posts]
print("Longest title:", max(titles, key=len))Expected outputAsha: 2 post(s)
Ben: 2 post(s)
Chen: 1 post(s)
Longest title: Learning Python in the browser
4Send data with POST
json= turns a dictionary into a JSON request body. JSONPlaceholder pretends to save it and answers with status 201 (Created) and a new id — nothing is really stored. (Live request.)
import requests
new_todo = {"userId": 1, "title": "Write my first API client", "completed": False}
response = requests.post(
"https://jsonplaceholder.typicode.com/todos", json=new_todo, timeout=10
)
response.raise_for_status()
created = response.json()
print("Status:", response.status_code)
print("Server gave it id", created["id"])
print(created["title"])Expected outputStatus: 201
Server gave it id 201
Write my first API client
Practise next
Python API Example: Build an API Client exercises → Back to the lesson
Python Dictionaries examplesWorking with JSON in Python examplesPython requests: Call Web APIs examplesPandas Basics examples