APIs with FastAPI · Chapter 18 of 26
Streaming and WebSockets
By the end of this chapter you can send a response a piece at a time, say why its status must be settled before the first piece, stream server-sent events a browser updates itself from, keep a WebSocket open for messages both ways, and choose between the two. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Security and real-world behaviour
- 4 tasks
- FastAPI
- In the all labs plan
The first 2 chapters of APIs with FastAPI are free. This one comes with the all labs plan.
Why you need this
Every response so far was built whole, then sent. Three requests this week do not fit that. Imran's biggest merchant wants every parcel it has ever booked, for its accounts: thousands of rows, growing daily. The tracking page a customer opens should change on its own when the parcel moves, not when they press refresh. And Sunita wants to watch riders move on a map, which means the rider's phone talking to DakiyaGo every few seconds and DakiyaGo passing it on to whoever is watching.
A request and one finished response cannot do any of this well. HTTP can send a response in pieces, keep it open for events, or upgrade the connection to a two-way channel. FastAPI does all three.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
export.py: export a merchant's parcels
Make an app with one route: GET /merchants/{merchant_id}/parcels/export streams that merchant's parcels from /workspace/data/parcels.json, in the file's order, as JSON Lines (one whole parcel object per line, content type application/jsonl), made with a generator. An optional status query parameter keeps only parcels with that status.
A merchant_id not in /workspace/data/merchants.json answers 404. The check tries three merchants, with and without status, and M09.
- Task 2
tracking.py: live tracking
Make an app with one route: GET /parcels/{awb}/events answers a text/event-stream with one server-sent event per tracking event of that parcel in /workspace/data/events.json, in order. Each event has an id (the parcel's events counted from 1), the event name status, and data: JSON with the event's status, at and hub. Then the stream ends.
An AWB with no events answers 404 before the stream starts. The check reads every event of three parcels.
- Task 3
live.py: where is my rider?
Make an app with two WebSocket routes. On /ws/riders/{rider_id} the rider's phone sends messages like {"lat": 26.9124, "lng": 75.7873}. Everyone connected to /ws/watch/{rider_id} for that rider receives each good location as {"rider_id": ..., "lat": ..., "lng": ...}; watchers of other riders receive nothing.
A rider_id not in /workspace/data/riders.json is refused on both routes (closed with code 1008 without accepting). A message that is not a JSON object with numbers lat from -90 to 90 and lng from -180 to 180 gets {"error": "bad location"} back on the rider's connection, goes to no watcher, and the connection stays open. When a watcher leaves, the rider and the other watchers carry on. The check runs your file with uvicorn and connects for real.
- Task 4 · interview question
Interview: resume.py, a stream that survives a tunnel
Make the tracking route of task 2 again (GET /parcels/{awb}/events, the same events, ids and 404), and let a dropped stream carry on: with a Last-Event-ID request header that is a number, send only the events after that id (none if it was the last); with no header, or one that is not a number, start from the beginning. The first event sent carries retry 3000, telling the browser to wait 3 seconds before reconnecting.
The interviewer will ask: for parcel tracking, server-sent events or a WebSocket, and why?
What you will learn
- Streaming responses: a generator as the body, and JSON Lines.
- Status first: why a 404 inside a stream comes too late.
- Server-sent events: the format, ids, and how a browser reconnects.
- WebSockets: the upgrade, a receive loop, disconnects, and many watchers.
- Which one to use, and why.
More in Security and real-world behaviour
Build "Streaming and WebSockets" yourself
DakiyaGo, a Jaipur courier startup, takes bookings on WhatsApp. Merchants want an API, and you build it. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of APIs with FastAPI are free. This one comes with the all labs plan.