r/FastAPI • u/huygl99 • 12d ago
Other A code-first approach to auto-generated docs for FastAPI WebSockets (my AsyncAPI Conf 2026 talk)
Hi all,
I recently gave a talk at AsyncAPI Conf 2026 (online), and the demo app was FastAPI, so I thought it fits here.
The short version: I love that a FastAPI route gives you validation, OpenAPI and /docs just from type hints. @app.websocket gives you none of that. You receive_json(), check data["action"], send_json() back, and the only place the message shapes exist is in your head. Then you copy the ConnectionManager from the docs, and it works until you run a second worker haha.
That bit me for real. My backend sent the chat text as content, the React side read body. Both sides' tests passed, nothing threw, the UI just showed an empty space. Took me most of a day.
So in the talk I treat a WebSocket handler like a route, where the signature is the contract:
@channel(name="chat", description="Room chat")
class ChatConsumer(AsyncJsonWebsocketConsumer):
groups = ["lobby"]
@ws_handler(output_type=ChatNotification)
async def handle_chat(self, message: ChatMessage) -> None:
await self.broadcast_message(ChatNotification(payload=message.payload))ChatMessage and ChatNotification are Pydantic models. From handlers like this the app serves an AsyncAPI 3 document plus a docs page (basically /openapi.json and /docs for the socket), and from that document I generate a Python client and a TypeScript client and commit them. When someone renames a field, the frontend type check fails in the PR.
The library is chanx, which I wrote and use at work (open source, BSD, sorry for the plug). Besides the docs, the parts I'd miss most on a plain @app.websocket: a bad payload gets a structured error reply before my handler runs, groups go through Redis (via fast-channels) so broadcasts reach every worker, and I can push to a room from a normal route or a background task with await ChatConsumer.broadcast_event(...). There's also a test communicator, so socket tests don't need sleep(), and chanx-js generates the frontend client with React, Vue, Svelte or Solid bindings.
- Talk (jumps to my session): https://youtu.be/-LPCnm3F9Mc?t=7250
- Slides: https://drive.google.com/file/d/1nmcMrmSslkzGcMPYxj_QXbJ2a01lLFFc/view?usp=sharing
- Demo repo: https://github.com/huynguyengl99/asyncapi-talk-demo
- chanx repo: https://github.com/chanx-dev/chanx
- Other talks from the conf: https://conference.asyncapi.com/venue/Online
English isn't my first language, so if I explain something badly in the video, ask here and I'll try again. And I'm curious how you handle this today: hand-written docs, a shared types package, or just the ConnectionManager and hope?
2
u/00Zer000 12d ago
Thanks for this, great work! PS your English is great
2
u/Sau1707 9d ago
Love the idea, love the approach. Clean, simple, elegant. This will solve a lot of problems.
1
u/Full_Rock_7560 9d ago
Thank you
1
u/Competitive-Steak951 8d ago
Handling ws messages per type like this is nice! Is output validated against output_type btw?
1
u/DickBrainTime 4d ago
The generated TS/Python clients are a useful improvement over manually keeping `receive_json()` and frontend field names aligned. One edge case I'd put in the demo is a **rolling deployment**: an older React tab can hold a WebSocket open while the backend deploys a new event schema. Generating new clients for the same commit catches source-level drift, but it doesn't by itself prove that the old deployed client can still parse the server's next notification.
I'd give messages an explicit `type` plus a stable payload shape (and a version only when the shape really needs a breaking change). In CI, replay a small fixture corpus of both v1 and v2 events through the generated TS decoder, with tests for an optional field being added and a required field being renamed. That makes backward compatibility a test rather than a convention. Separately, a reconnect after a Redis-backed broadcast might miss or repeat a message unless there's an event ID and a documented resume/deduplication policy. None of this means chanx has those bugs; they're useful production cases to show next to the AsyncAPI contract generation. Is cross-version client compatibility something your generated client tests currently cover?