Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 15.1 — Calling Web APIs: HTTP with httpx and requests
Python · Example 2 of 2

POST JSON, auth header and a timeout

The API key here is made up. Real keys come from the environment (Topic 15.3), never from the source code.

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.

01

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.

02

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.

03

Write a handler that raises httpx.ConnectError for the path /down, and show how to catch it without catching 404s.

Explain it without notes

01

What are the parts of an HTTP request and an HTTP response?

02

What do the status code families 2xx, 4xx and 5xx mean, and why does the difference matter for client code?

03

Why must a client always set a timeout, and what does raise_for_status() do?

04

Why use an httpx.Client instead of calling httpx.get every time?

05

Which HTTP methods are safe and which are idempotent, and why does a client care?

06

How do the default timeouts and redirect behaviour of httpx differ from requests?

POST JSON, auth header and a timeout
Sign in to run this example in your browser.

Expected output

201 {'id': 1, 'title': 'learn httpx', 'done': False}
method: POST
sent content-type: application/json
sent body: {"title":"learn httpx"}
timeout setting: Timeout(connect=2.0, read=5.0, write=5.0, pool=5.0)
timeout caught: ReadTimeout - server took too long
without key: 401