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

Send & Receive Methods

~11 min · fastapi, send, receive, iter

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

Three pairs of methods

FastAPI's WebSocket object gives you three matched send/receive pairs: send_text/receive_text for strings, send_json/receive_json for auto-serialized JSON dicts, send_bytes/receive_bytes for raw binary. receive_json() parses for you; send_json() stringifies for you. For 95% of applications you only ever use the JSON pair.

iter_text and iter_json

Instead of a manual while True loop, FastAPI exposes async iterators: async for msg in websocket.iter_json():. Cleaner code; same behavior; the iterator stops on disconnect (no WebSocketDisconnect handling needed for the iter form).

send_json is not opinionated about format

send_json(obj) sends whatever json.dumps(obj) would produce. It does not impose a type/data envelope. That is your job — Track 5 covers protocol design.

Code

All six methods on one endpoint·python
from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket('/ws')
async def demo(websocket: WebSocket):
    await websocket.accept()

    # Receiving
    text  = await websocket.receive_text()       # str
    obj   = await websocket.receive_json()       # dict / list
    raw   = await websocket.receive_bytes()      # bytes

    # Sending
    await websocket.send_text('hi')
    await websocket.send_json({'type': 'hello', 'data': {'ok': True}})
    await websocket.send_bytes(b'\x00\x01\x02')

    # Closing
    await websocket.close(code=1000, reason='done')
iter_json — clean async iteration·python
@app.websocket('/ws')
async def chat(websocket: WebSocket):
    await websocket.accept()
    async for msg in websocket.iter_json():
        # msg is already a dict
        if msg.get('type') == 'ping':
            await websocket.send_json({'type': 'pong'})
        else:
            await websocket.send_json({'type': 'echo', 'data': msg})

External links

Exercise

Convert the echo server from t3l1 to use iter_json(). Have it route on msg['type']: ping returns pong, anything else echoes back as {type: 'echo', data: msg}. Test with websocat sending JSON.

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.