0
0
FastapiHow-ToBeginner · 3 min read

How to Return Streaming Response in FastAPI Quickly

In FastAPI, you can return a streaming response by using StreamingResponse from starlette.responses. This lets you send data chunks as they are generated, which is useful for large files or real-time data streams.
📐

Syntax

The StreamingResponse class is used to send a streaming response. You provide it with an iterable or async iterable that yields bytes, and optionally specify the media_type (like application/json or text/plain).

Key parts:

  • content: An iterable or async iterable yielding bytes.
  • media_type: The MIME type of the response.
python
from fastapi import FastAPI
from starlette.responses import StreamingResponse

app = FastAPI()

def generate():
    yield b"Hello "
    yield b"World!"

@app.get("/stream")
def stream():
    return StreamingResponse(generate(), media_type="text/plain")
💻

Example

This example shows a FastAPI app that streams a simple text message in parts. The generate function yields byte chunks, and StreamingResponse sends them as a streamed response.

python
from fastapi import FastAPI
from starlette.responses import StreamingResponse
import time

app = FastAPI()

def slow_numbers():
    for i in range(1, 6):
        yield f"Number: {i}\n".encode("utf-8")
        time.sleep(1)  # simulate delay

@app.get("/numbers")
def stream_numbers():
    return StreamingResponse(slow_numbers(), media_type="text/plain")
Output
When you visit /numbers, the server sends "Number: 1", then after 1 second "Number: 2", and so on up to 5, streaming each line separately.
⚠️

Common Pitfalls

  • Not yielding bytes: The generator must yield bytes, not strings. Use .encode() to convert strings to bytes.
  • Forgetting media_type: Without it, the client may not interpret the response correctly.
  • Using blocking code inside generator: Avoid long blocking calls; use async generators or run blocking code in threads.
python
from fastapi import FastAPI
from starlette.responses import StreamingResponse

app = FastAPI()

# Wrong: yields strings instead of bytes

def wrong_generator():
    yield "Hello"
    yield "World"

@app.get("/wrong")
def wrong_stream():
    return StreamingResponse(wrong_generator(), media_type="text/plain")

# Right: yields bytes

def right_generator():
    yield b"Hello"
    yield b"World"

@app.get("/right")
def right_stream():
    return StreamingResponse(right_generator(), media_type="text/plain")
📊

Quick Reference

Tips for using StreamingResponse in FastAPI:

  • Always yield bytes, not strings.
  • Set media_type to match your content.
  • Use generators or async generators for streaming data.
  • Good for large files, real-time logs, or slow data sources.

Key Takeaways

Use StreamingResponse with a generator yielding bytes to stream data in FastAPI.
Always specify the media_type to inform the client about the content type.
Generators must yield bytes, not strings, to avoid errors.
StreamingResponse is ideal for large or slow data delivery scenarios.
Avoid blocking operations inside the generator to keep streaming smooth.