9. httpx for API calls
Python · 52 pages source format
Sync httpx for scripts; async httpx pairs with Playwright later. Status codes, JSON bodies, timeouts, basic auth headers.
What you'll learn
- httpx.Client
- GET/POST
- Status codes
- Timeouts and errors
GET request
httpx.get(url) or with Client() for connection reuse. response.raise_for_status() on errors.
import httpx
resp = httpx.get("https://jsonplaceholder.typicode.com/users", timeout=10.0)
resp.raise_for_status()
users = resp.json()
assert len(users) == 10Do this now
Fetch jsonplaceholder users. Assert 200 and len(users) == 10.
POST and headers
client.post(url, json={...}) sends JSON body. headers={"Authorization": "Bearer ..."} when needed.
Do this now
POST a new todo to jsonplaceholder. Print returned id.
Test API helpers
Extract fetch_users(client) → list. Unit test with httpx mock or fixture JSON — not live network.
Do this now
Write fetch_users using httpx. Test parsing with fixture file.
Pro tip. Playwright path uses httpx for API-only tests — this chapter prepares you for that.