GET, query parameters and raise_for_status
The fake server is the handler function. Add another path to it and call it from the client.
A web API is a program on another computer that answers HTTP requests, usually with JSON. With httpx or requests you send a request (a method, a URL, headers, maybe a body) and read back a response (a status code, headers, a body); you must always set a timeout and check the status.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Using a MockTransport handler that returns {"id": 1, "name": "Asha"} for /users/1, write a function get_user(client, user_id) that returns the dictionary, and raises on any error status.
Write a function search(client, term, limit=5) that calls /search with query parameters and returns the list in the results key of the reply.
Write a handler that raises httpx.ConnectError for the path /down, and show how to catch it without catching 404s.
Explain it without notes
What are the parts of an HTTP request and an HTTP response?
What do the status code families 2xx, 4xx and 5xx mean, and why does the difference matter for client code?
Why must a client always set a timeout, and what does raise_for_status() do?
Why use an httpx.Client instead of calling httpx.get every time?
Which HTTP methods are safe and which are idempotent, and why does a client care?
How do the default timeouts and redirect behaviour of httpx differ from requests?
Expected output
status: 200 OK
content-type: application/json
json: {'id': 7, 'name': 'Asha', 'plan': 'free'}
url: https://api.example.com/users/7
url: https://api.example.com/search?q=python+apis&limit=5
json: {'query': 'python apis', 'hits': 2}
status: 404 ok? False
error: Client error '404 Not Found' for url 'https://api.example.com/users/99'
For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404