0
0
FastAPIframework~5 mins

Streaming responses in FastAPI

Choose your learning style9 modes available
Introduction

Streaming responses let your app send data little by little instead of all at once. This helps when sending big files or live data.

Sending large files like videos or logs without loading all in memory
Delivering live updates or real-time data to users
Providing data as it is generated, like progress reports
Reducing wait time by starting to send data immediately
Handling slow clients without blocking the server
Syntax
FastAPI
from fastapi import FastAPI
from fastapi.responses import StreamingResponse

app = FastAPI()

@app.get("/stream")
async def stream():
    def generator():
        yield "Hello "
        yield "World!"
    return StreamingResponse(generator(), media_type="text/plain")

The function returns a StreamingResponse with a generator that yields data chunks.

Set media_type to tell the browser what kind of data is sent.

Examples
This generator yields numbers one by one as strings with newlines.
FastAPI
def number_stream():
    for i in range(1, 6):
        yield f"Number {i}\n"
This endpoint streams numbers to the client as plain text.
FastAPI
@app.get("/numbers")
async def stream_numbers():
    return StreamingResponse(number_stream(), media_type="text/plain")
This generator reads a file in small chunks and yields each chunk for streaming.
FastAPI
def file_stream(file_path):
    with open(file_path, "rb") as f:
        while chunk := f.read(1024):
            yield chunk
Sample Program

This FastAPI app has one endpoint /stream that streams a greeting in parts. The client receives the message piece by piece.

FastAPI
from fastapi import FastAPI
from fastapi.responses import StreamingResponse

app = FastAPI()

def simple_stream():
    yield "Hello "
    yield "from "
    yield "FastAPI!"

@app.get("/stream")
async def stream():
    return StreamingResponse(simple_stream(), media_type="text/plain")
OutputSuccess
Important Notes

StreamingResponse works well with generators or async generators.

Use streaming to save memory and improve user experience for big or slow data.

Remember to set the correct media_type for your data.

Summary

Streaming responses send data in small parts instead of all at once.

Use generators to create the data chunks to stream.

FastAPI's StreamingResponse makes streaming easy and efficient.