Skip to main content

The Other Side of the API

Python programs are not only servers — they call APIs too: fetching data, talking to services, integrating third parties. The standard library's urllib.request is three habits:

1. make the request (urlopen for a simple GET, a Request object for full control over method, headers and body),
2. open the response in a with block so it is always closed,
3. remember that a 4xx or 5xx answer raises HTTPError — catch it where a bad status is a case you handle.

The demos below call a local test server, so the outputs are stable — the client code is exactly what you would point at a real URL. (The ecosystem's popular requests package wraps these same ideas in a friendlier API; everything here stays standard library.)


GET and Decode

The everyday task: GET a URL and decode the JSON body. json.loads(resp.read()) gives plain Python data, and a dataclass turns each dict into a typed record with User(**item).

Fetch a list into records

The response body parses into a list of User records, and from there it is ordinary Python data — looped and printed field by field.

Prompt
Write a Python program that GETs a JSON array of users from a server (a local demo server in the same file), parses the body with json.loads, builds a list of User dataclasses from it, and prints each user's id and name.
Output: complete Python program

POST with a JSON Body

Sending data is the mirror image: dump the record to JSON bytes, POST them with the right content type — then parse the server's answer, which here carries the id the server assigned.

Send a record, read the answer

The record goes out as JSON and the created User(id=7, name='Cleo') comes back — the complete write-path of an API client in one small program.

Prompt
Write a Python program that dumps a new User dataclass to JSON, POSTs it with the application/json content type to a server that assigns an id and answers 201 (a local demo server in the same file), then parses the response and prints the status and the created user with its new id.
Output: complete Python program