Skip to content
Visual explainer 3h 30m to learn 5 steps

Stream AI responses from FastAPI to a browser

Stream delta, citation, completion and error events from FastAPI to a browser over SSE with fetch.

By Invicly Tech, , in FastAPI with Python for AI Backends. About 10 minutes to read.

Topic 17 of 29

In short

Server-sent events (SSE) let a server push a stream of small text events over one HTTP response. FastAPI can produce them with a StreamingResponse of media type text/event-stream, and the browser reads them with fetch so it can send a POST with a JSON body. Typed events such as delta, citation, done and error let the UI show text as it is generated.

Think of it like this: Instead of waiting for a whole letter, you get a run of postcards, each saying what kind of news it carries.

Explained simply

AI models produce answers a few words at a time. If the server waits for the whole answer, the user stares at a spinner for several seconds. Streaming sends each new piece as soon as it exists, so text appears as it is written.

Server-sent events, or SSE, is a simple way to stream. The server keeps one HTTP response open and writes short text messages into it. Each message can have a type, such as delta for new text or done for the end, and data, usually a small piece of JSON.

FastAPI sends a stream with StreamingResponse. You give it a generator, a function that yields one piece at a time, and it sends each piece straight away. The content type text/event-stream tells the browser it is getting events.

Browsers have a built-in EventSource object for SSE, but it can only send GET requests without custom headers. A chat question needs a POST with a JSON body, so most AI apps use fetch and read the response body piece by piece instead.

Press Play on a diagram to walk through it one step at a time.

SequenceOne chat answer as a stream of events
Browser
FastAPI
Model
  1. 1POST /chat/stream (JSON body)
    Browser to FastAPI: POST /chat/stream (JSON body)
  2. 2200, text/event-stream headers
    FastAPI to Browser: 200, text/event-stream headers
  3. 3Start streaming completion
    FastAPI to Model: Start streaming completion
  4. 4Token chunks
    Model to FastAPI: Token chunks
  5. 5event: delta (repeated)
    FastAPI to Browser: event: delta (repeated)
  6. 6event: citation
    FastAPI to Browser: event: citation
  7. 7event: done with usage
    FastAPI to Browser: event: done with usage
MapEvent types in a chat stream
Chat stream
  • delta
    • New text to append
    • Sent many times
  • citation
    • Number, document, page
    • Sent once per source
  • done
    • Finish reason
    • Token usage
    • Ends the stream
  • error
    • Safe error code
    • Retryable flag
    • Ends the stream

In depth

The SSE wire format

An SSE stream is UTF-8 text. Each event is one or more lines of the form field: value, followed by an empty line. The fields are event (the type name), data (the payload), id (a position the client can resume from) and retry (a reconnect delay in milliseconds, used by EventSource). A line starting with a colon is a comment and is ignored, which makes it useful for heartbeats.

If a data value contains a newline, it must be split into several data lines, which the client joins back with newlines. Encoding the payload as JSON avoids this, because json.dumps writes newlines as the two characters backslash and n. Lines can end with LF, CR or CRLF, so a robust parser handles all three.

LayersAnatomy of one event
  1. 1
    event: citation

    Type the client switches on

  2. 2
    id: 7

    Optional position in the stream

  3. 3
    data: {"doc":"handbook","page":12}

    JSON payload on one line

  4. 4
    (empty line)

    Ends the event; now it is dispatched

Producing events with StreamingResponse

StreamingResponse takes an async generator and sends each yielded string as soon as it is produced. Inside the generator, start the model stream, yield a delta event for every token, then a citation event for each source and a done event with the finish reason and token usage. Add the header Cache-Control: no-cache so caches do not hold the response.

Do slow checks before the first yield, not inside the stream. Authentication, validation and retrieval should run in the route itself, where a failure can still return a proper 401, 404 or 422. Once the generator yields its first event, the status is fixed at 200.

  • delta: {"text": "..."}
  • citation: {"n": 1, "document_id": "...", "page": 12}
  • done: {"finish_reason": "stop", "usage": {...}}
  • error: {"code": "provider_unavailable", "retryable": true}

Reading the stream in the browser with fetch

Call fetch with method POST and a JSON body. If response.ok is false, read the error as normal JSON. Otherwise get a reader from response.body, decode bytes with a TextDecoder in streaming mode, and append them to a buffer. Network chunks do not line up with events: one chunk can hold half an event or three events. Split the buffer on the blank line, keep the last unfinished part for the next read, and parse each complete event.

Update the UI per event type: append delta text, collect citations, and on done stop the typing indicator. Libraries such as @microsoft/fetch-event-source wrap this loop if you prefer not to write the parser yourself.

When WebSockets fit better

SSE is one-way: the server talks, the client listens. That matches a chat answer exactly, works over plain HTTP, passes through most proxies and is easy to test with curl. A new question is simply a new POST.

WebSockets give a two-way channel on one long-lived connection. They make sense when the client must send messages during the stream, such as live audio, collaborative editing or interrupting a voice agent mid-sentence. The cost is a separate protocol with its own authentication, reconnect logic, message framing and load balancer settings. FastAPI supports both, with @app.websocket for WebSockets.

ComparePolling, SSE and WebSockets
Polling
  • Client asks every few seconds
  • Simple and cache friendly
  • Delay equals the interval
  • Good for job status
SSE
  • Server pushes over one response
  • Plain HTTP, text only
  • One direction
  • Good for streamed answers
WebSockets
  • Two-way messages
  • Own protocol after upgrade
  • More moving parts
  • Good for voice and live collaboration

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Frame events in SSE format~40m
  2. 2
    Return a StreamingResponse~40m
  3. 3
    Read the stream with fetch~40m
  4. 4
    Send delta, citation and done events~40m
  5. 5
    Know when WebSockets fit better~40m

Key points

  • Each SSE event is lines of field: value (event, data, id, retry) ending with a blank line.
  • Return StreamingResponse(generator, media_type='text/event-stream') from FastAPI.
  • EventSource only sends GET without custom headers, so read POST streams with fetch and a reader.
  • Put JSON in the data field and use the event field to say what kind of message it is.
  • Use WebSockets only when the client must also send messages during the stream.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
def sse(event: str, data: dict) -> str:
    return f'event: {event}\ndata: {json.dumps(data)}\n\n'

@app.post('/chat/stream')
async def chat_stream(req: ChatRequest, user: User = Depends(current_user)):
    async def events():
        async for token in model.stream(req.question):
            yield sse('delta', {'text': token})
        yield sse('done', {'finish_reason': 'stop'})
    return StreamingResponse(events(), media_type='text/event-stream',
                             headers={'Cache-Control': 'no-cache'})

json.dumps escapes newlines, so each data field stays on one line.

Watching a stream with curl

The -N flag turns off curl's output buffering so events print as they arrive. You should see several delta events within the first second, then citation events, then done. If everything appears at once at the end, something between curl and your generator is buffering. This works against a local fake model, so it costs nothing.

bash
curl -N -X POST http://localhost:8000/chat/stream \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer <demo-token>' \
  -d '{"question": "How many leave days do I get?"}'

# event: delta
# data: {"text": "Staff get "}
#
# event: citation
# data: {"n": 1, "document_id": "7f3c...", "page": 12}

A small SSE reader for fetch

This function reads the body, buffers partial events and calls onEvent with the type and parsed data. It splits on blank lines and keeps any unfinished tail in the buffer for the next chunk. For brevity it assumes LF line endings and one data line per event.

typescript
async function readSse(res: Response, onEvent: (type: string, data: any) => void) {
  const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader();
  let buf = '';
  for (let r = await reader.read(); !r.done; r = await reader.read()) {
    buf += r.value;
    const parts = buf.split('\n\n');
    buf = parts.pop() ?? '';
    for (const part of parts) {
      const type = part.match(/^event: (.*)$/m)?.[1] ?? 'message';
      const data = part.match(/^data: (.*)$/m)?.[1];
      if (data) onEvent(type, JSON.parse(data));
    }
  }
}

Quick reference

  • Event = field lines (event, data, id, retry) + one empty line.
  • Comment line = starts with a colon; clients ignore it.
  • StreamingResponse(gen(), media_type='text/event-stream')
  • Set Cache-Control: no-cache on streaming responses.
  • EventSource = GET only; use fetch + response.body reader for POST.
  • Buffer bytes and split on blank lines; chunks do not match events.
  • curl -N shows events live and reveals buffering.
  • Need two-way messages during the stream? Use WebSockets.

Common mistakes

  • Forgetting the blank line after each event, so the client never sees an event end.
  • Splitting incoming bytes on newlines without buffering, which breaks events split across chunks.
  • Putting raw multi-line text in one data line; encode it as JSON or use several data lines.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What ends a single SSE event?

Question 2

2Why do most AI chat frontends read SSE with fetch rather than EventSource?

Question 3

3Where should authentication fail for a streaming route?

Question 4

4Your reader parses each network chunk as one event and sometimes gets JSON errors. Why?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write by hand the exact text of a stream that sends two deltas, one citation and a done event.

  2. Exercise 2medium

    Build POST /chat/stream with a fake model that yields words with a 100 ms delay, and confirm with curl -N that words arrive one by one.

  3. Exercise 3hard

    Render the stream in a React component: append deltas, show citations as numbered links under the answer, and show an error banner on an error event.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is SSE supported in all browsers?
EventSource and streaming fetch bodies are supported in all current major browsers. Very old browsers may lack response.body streaming.
Can SSE send binary data?
No, SSE is UTF-8 text only. Send JSON, or base64-encode small binary pieces, or use a separate download URL.
Does HTTP/2 change anything for SSE?
It helps: over HTTP/1.1 browsers allow about six connections per host, and each open stream uses one. HTTP/2 multiplexes many streams over one connection.
Do I need a library to send SSE from FastAPI?
No. StreamingResponse plus a small function that formats event and data lines is enough. Helper packages exist if you want extras such as automatic pings.

Go deeper

ShareXLinkedInWhatsApp