Serving an LLM app with FastAPI
Expose a streaming chat or RAG endpoint with auth and input validation.
By Invicly Tech, , in AI Engineering with Python. About 12 minutes to read.
In short
FastAPI turns your Python LLM logic into an HTTP service. Pydantic validates requests, dependencies handle auth, and streaming responses send tokens to clients as they are generated.
Explained simply
A notebook works for you alone. A service lets a website, a mobile app or another program use your AI feature over HTTP. FastAPI is a popular Python framework for this. You write normal Python functions, and FastAPI turns them into web endpoints.
FastAPI leans on type hints. You describe the request body as a Pydantic model, and FastAPI checks every incoming request against it. If the text is missing or too long, the request is rejected with a clear error before your code even runs.
Streaming makes chat feel fast. Instead of waiting ten seconds for the whole answer, the endpoint sends each piece of text as soon as the model produces it, and the user watches the reply appear word by word.
Because every model call costs money, the endpoint must also know who is calling. A token or API key in the Authorization header identifies the caller, so strangers cannot use your service and you can apply per-user limits.
Press Play on a diagram to walk through it one step at a time.
- Client to FastAPI: POST /chat with bearer token1POST /chat with bearer token
- 2Check token, validate bodyFastAPI to FastAPI: Check token, validate body
- FastAPI to LLM API: Streaming request3Streaming request
- LLM API to FastAPI: Token chunks4Token chunks
- FastAPI to Client: StreamingResponse chunks5StreamingResponse chunks
- 1Uvicorn
ASGI server: sockets and HTTP
- 2Middleware
CORS, request ID, access logs
- 3Dependencies
Auth, settings, rate limits
- 4Pydantic validation
Bad body returns 422
- 5Your handler
Calls the model, streams the reply
In depth
One shared client and settings, created at startup
Creating a new HTTP or SDK client on every request wastes time on new connections and TLS handshakes. Create one async client when the app starts and reuse it. FastAPI's lifespan feature is the place for this: an async context manager that runs setup code before the app takes requests and cleanup code when it shuts down.
Load settings the same way. The pydantic-settings package lets you declare a Settings class whose fields are read from environment variables, with types and defaults. If a required value like the API key is missing, the app fails at startup with a clear message, instead of failing on the first user request at 3 a.m.
Keep the model name, prompt version and limits in settings too, so you can change them per environment without changing code.
- FastAPI(lifespan=lifespan) runs setup once and cleanup at shutdown
- pydantic-settings reads typed config from environment variables
- Fail fast at startup when a secret is missing
Streaming: plain text or Server-Sent Events
StreamingResponse takes an async generator and sends each value it yields as soon as it is ready. The simplest format is plain text chunks. It works with curl -N, but the client cannot tell a normal end from an error, and there is no room for extra data such as citations.
Server-Sent Events (SSE) add structure. Each event is one or more lines starting with data:, followed by a blank line, sent with the media type text/event-stream. Encode each chunk as JSON so a newline inside a token cannot break the framing, and send a final done event, or an error event, so the client knows how the stream ended.
The browser's EventSource API only supports GET requests, so chat front ends that POST a message usually read the stream with fetch instead. Reverse proxies like nginx may buffer responses; the X-Accel-Buffering: no header turns that off for nginx.
- 1Validate and auth
Before any model call
- 2Open model stream
Shared async client
- 3Yield SSE events
data: JSON chunk, blank line
- 4Client renders
Appends each chunk
- 5Finish
done event, or error event
Errors and disconnects in the middle of a stream
Once the first chunk is sent, the HTTP status 200 is already on the wire. If the model fails halfway, you cannot change it to 500. So catch errors inside the generator and send an error event that the client can show, then end the stream. Log the failure with the request ID.
Users also close tabs mid-answer. When the client disconnects, keep in mind that the upstream model may keep generating, and you keep paying for those tokens. Use the SDK's stream as an async context manager, so it closes the upstream connection when your generator stops, and check await request.is_disconnected() inside the loop to stop early.
Set timeouts on the upstream call: a connect timeout and a read timeout between chunks. A stream that stalls for a minute should end with an error event, not hang forever.
- After the first chunk, report errors as an error event
- Close the upstream stream when the client leaves
- Use a read timeout between chunks, not only a total timeout
Validation and auth that hold up
Make the Pydantic model strict. Limit message length with Field(max_length=...), limit the number of history messages, and restrict roles with Literal['user', 'assistant'] so a caller cannot inject a fake system message. Set model_config = ConfigDict(extra='forbid') to reject unknown fields with a 422 instead of silently ignoring them.
For service-to-service calls, give each client its own API key, store only a hash of it, and compare with secrets.compare_digest, which takes the same time whether the first or last character differs. For browser apps, accept a token from your identity provider (often a JWT) and verify its signature and expiry. FastAPI's HTTPBearer helper reads the Authorization: Bearer header for you.
Always take the user's identity from the verified token, never from a user_id field in the body. Return 401 when credentials are missing or wrong, and 403 when they are valid but not allowed.
Running and testing the service
In development, fastapi dev main.py (from the fastapi[standard] package) or uvicorn main:app --reload restarts on every code change. In production, run uvicorn without reload, binding to 0.0.0.0, and add --workers to use several CPU cores.
Async endpoints run on one event loop per worker. A single blocking call inside an async def, such as a synchronous SDK client or time.sleep, freezes every request on that worker. Use the async version of your SDK, or declare the endpoint with plain def so FastAPI runs it in a thread pool, or wrap the blocking call with asyncio.to_thread.
Test without spending money. FastAPI's TestClient sends requests to the app in memory, and app.dependency_overrides lets you swap the real model client or auth for fakes, so tests are fast and deterministic.
- uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
- Never call blocking code inside async def
- TestClient plus dependency_overrides for free, fast tests
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Create a FastAPI app~1h
- 2Add a streaming chat endpoint~1h
- 3Validate input with Pydantic~1h
- 4Add API key or token auth~1h
Key points
- Declare request bodies as Pydantic models; FastAPI validates and documents them.
- Return 401 for missing credentials and 422 for invalid input automatically.
- Use async endpoints and async SDK clients to handle many users concurrently.
- Limit input size so a single request cannot blow up cost.
Key terms
Tap a card to flip it. 0/5 known
Examples
import os
from fastapi import FastAPI, Depends, Header, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
app = FastAPI()
class ChatIn(BaseModel):
message: str = Field(min_length=1, max_length=4000)
def auth(authorization: str = Header()):
if authorization != f"Bearer {os.environ['API_TOKEN']}":
raise HTTPException(status_code=401)
@app.post('/chat', dependencies=[Depends(auth)])
async def chat(body: ChatIn):
return StreamingResponse(stream_reply(body.message), media_type='text/plain')Validated input, token auth and a streaming response.
An SSE chat endpoint with clean endings
This endpoint streams a reply as Server-Sent Events. Step 1: an inner async generator reads tokens from your model stream (stream_reply is your own function around the SDK). Step 2: each token is JSON-encoded inside a data: line followed by a blank line. Step 3: if the client disconnected, stop reading so you stop paying. Step 4: a done event marks a normal end; an error event replaces a crash, because the 200 status was already sent. Step 5: headers turn off caching and nginx buffering.
import json
from fastapi import Request
from fastapi.responses import StreamingResponse
@app.post("/chat/stream", dependencies=[Depends(auth)])
async def chat_stream(body: ChatIn, request: Request):
async def events():
try:
async for token in stream_reply(body.message):
if await request.is_disconnected():
break
yield f"data: {json.dumps({'token': token})}\n\n"
yield "event: done\ndata: {}\n\n"
except Exception:
yield f"event: error\ndata: {json.dumps({'error': 'generation failed'})}\n\n"
return StreamingResponse(events(), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})Testing validation without calling a model
You want CI to prove that bad input never reaches the model. Step 1: import the app and its auth dependency. Step 2: override auth with a function that does nothing, so tests do not need a real token. Step 3: send an empty message and expect 422 from Pydantic. Step 4: send an unknown field and expect 422 too; this works because the ChatIn model sets extra='forbid'. Step 5: in a separate test without the override, send no Authorization header and expect a 401 or 403 from the real auth.
from fastapi.testclient import TestClient
from main import app, auth
app.dependency_overrides[auth] = lambda: None # skip auth in these tests
client = TestClient(app)
def test_rejects_empty_message():
assert client.post("/chat", json={"message": ""}).status_code == 422
def test_rejects_unknown_fields():
r = client.post("/chat", json={"message": "hi", "role": "system"})
assert r.status_code == 422Quick reference
- fastapi dev main.py for development; uvicorn main:app --host 0.0.0.0 --workers 4 in production
- Create one async client in the lifespan handler and reuse it for every request
- SSE event format: data: <json> then a blank line; media type text/event-stream
- After streaming starts the status is fixed, so send an error event instead of a 500
- Field(max_length=...) and ConfigDict(extra='forbid') stop oversized and unexpected input
- Compare API keys with secrets.compare_digest; store only their hashes
- Never call blocking code inside async def; use async SDKs or asyncio.to_thread
- app.dependency_overrides swaps the model and auth for fakes in tests
Common mistakes
- Using a blocking SDK client inside async endpoints.
- Accepting unlimited input length and paying for huge prompts.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a ChatIn Pydantic model with a message of 1 to 4,000 characters, a history list of at most 20 items with role limited to user or assistant, and no extra fields allowed.
- Exercise 2medium
Write a FastAPI auth dependency that reads a Bearer token with HTTPBearer, compares its SHA-256 hash to a set of stored key hashes in constant time, and returns the client name.
- Exercise 3hard
Add a lifespan handler that creates one shared httpx.AsyncClient with connect and read timeouts at startup, stores it on app.state, and closes it at shutdown.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How do I stream LLM responses with FastAPI?
- Return a StreamingResponse built from an async generator that yields chunks as your SDK produces them. Use the text/event-stream media type and SSE framing if the client needs structured events.
- Should my FastAPI endpoints be async def or def?
- Use async def with async clients for model calls. If a library only offers blocking calls, use plain def or asyncio.to_thread so the event loop is not blocked.
- Why does FastAPI return 422?
- 422 Unprocessable Content means the request body or parameters failed validation against your Pydantic model or type hints. The response lists which fields were wrong.
- Why does my stream arrive all at once behind nginx?
- The proxy is buffering the response. Disable buffering for that route, for example with the X-Accel-Buffering: no response header or proxy_buffering off in nginx.