C.W.K.
Stream
Lesson 01 of 08 · published

First WebSocket Endpoint

~12 min · fastapi, server, accept

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

The seven-line server

FastAPI exposes WebSocket through the @app.websocket decorator. The handler is a coroutine that takes a single WebSocket argument. Three things must happen, in order: await websocket.accept() to complete the handshake, then await websocket.receive_*() in a loop, then await websocket.send_*() to reply.

accept() is not optional

Until you call accept(), the handshake is not complete and any send will throw. You can choose to not accept — that is how you reject a connection during auth checks. After accept, the connection is fully open and frames flow.

Running and testing

Spin up the server with uvicorn; test from the command line with websocat or wscat. cwkPippa runs Uvicorn without --reload on purpose (Pippa's adapter is the live brain stem; reload kills sessions). For learning, use --reload.

Code

Echo server in seven lines·python
from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket('/ws')
async def echo(websocket: WebSocket):
    await websocket.accept()
    while True:
        text = await websocket.receive_text()
        await websocket.send_text(f'echo: {text}')
Run + test·shell
pip install 'fastapi[standard]' uvicorn

# Run
uvicorn main:app --reload --host 0.0.0.0 --port 8000

# Test from a second terminal
brew install websocat   # or: cargo install websocat
websocat ws://localhost:8000/ws
> hello
echo: hello

External links

Exercise

Build the echo server. From a browser tab, open new WebSocket('ws://localhost:8000/ws'), send three messages, observe the echoes. Then comment out await websocket.accept() and watch what happens — record the exact error message your server logs.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.