Python for AI Engineers · Part B · Lesson 12 of 26
FastAPI tutorial: routes, validation, dependencies and streaming for LLM apps
FastAPI for Java and JavaScript developers: routes, path and query parameters, Pydantic bodies and automatic 422 errors, response models, HTTPException, Depends, async endpoints, lifespan with one shared HTTP client, SSE streaming, background tasks, CORS, /docs and TestClient.
⏱ 45 min3 exercises that check your codeRuns in your browser
By the end you can
- Build a FastAPI app with routes, path and query parameters, and run it with uvicorn
--reload - Validate JSON bodies with Pydantic models, read the automatic 422 errors, and shape replies with
response_model, status codes andHTTPException - Share settings and one HTTP client with
Dependsand a lifespan, and choose betweendefandasync defendpoints - Stream LLM tokens with
StreamingResponseand Server-Sent Events, run background tasks, and enable CORS - Test endpoints without a model using
TestClientanddependency_overrides
1Your first FastAPI app
Every AI feature you build ends up behind an HTTP endpoint: a chat box calls POST /chat, another service calls POST /summarize. FastAPI is the Python web framework most AI teams use for this. It plays the role of Spring Web (@RestController) or Express, and it gets three things from your type hints: request parsing, validation, and API documentation.
FastAPI only describes your app. A separate program, uvicorn, is the web server that listens on a port and hands requests to it, the job Tomcat or Netty does for Spring Boot. Create a project from lesson 1 and add both, plus httpx, the HTTP client from the previous lesson that we use later to call a model:
uv init ask-api --python 3.12
cd ask-api
uv add fastapi uvicorn httpx + fastapi==0.165.0 + httpx==0.29.0 + pydantic==2.14.4 + starlette==1.10.0 + uvicorn==0.55.0 (and about 12 helper packages)
from fastapi import FastAPI
app = FastAPI(title="Ask API")
@app.get("/health")
def health():
return {"status": "ok"} - The application object, like the
SpringApplicationcontext orconst app = express(). uvicorn finds it by its variable name.titleappears on the docs page.line 3 - A decorator (lesson 4) that registers the function below for
GET /health. Same idea as@GetMapping("/health"). There are also@app.post,@app.put,@app.patchand@app.delete.line 6 - The function name does not matter for the URL. It becomes the operation name in the docs.line 7
- Return a dict (or a list, a string, a Pydantic model) and FastAPI turns it into JSON with
content-type: application/json. NoResponseEntityorres.json()needed.line 8
@RestController
public class HealthController {
@GetMapping("/health")
public Map<String, String> health() {
return Map.of("status", "ok");
}
} const app = express();
app.get("/health", (req, res) => {
res.json({ status: "ok" });
});
app.listen(8000); Replace the main.py that uv init created with the code above, then start the server. main:app means "the variable app in the file main.py". --reload watches your files and restarts the server every time you save, which is what you want while developing (never in production):
uv run uvicorn main:app --reload
INFO: Will watch for changes in these directories: ['/Users/you/ask-api']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [4012] using StatReload
INFO: Started server process [4018]
INFO: Waiting for application startup.
INFO: Application startup complete.
Leave it running and, in a second terminal, call it with curl (or open the URL in a browser):
curl http://localhost:8000/health
{"status":"ok"}
Now open http://localhost:8000/docs. FastAPI generates an interactive page (Swagger UI) from your code: every route, its parameters and its JSON shapes, with a Try it out button. The raw OpenAPI description is at /openapi.json, the same thing springdoc gives a Spring app, but here it is built in. Press Ctrl+C in the first terminal to stop the server.
Tip If you see Error loading ASGI app. Could not import module "main", you started uvicorn from a different folder. Run it from the folder that contains main.py. If port 8000 is taken, add --port 8001.
2Path and query parameters
A path parameter is a piece of the URL, written {name} in the route. A query parameter is anything after ?. In FastAPI both are just function parameters: a name in the route's braces is a path parameter, every other simple parameter (int, str, bool and so on) is read from the query string.
The type hint is not decoration here, it is the contract. article_id: int means FastAPI converts "2" from the URL into the integer 2, and rejects "abc" with an error before your function runs. A parameter with a default is optional; without one it is required.
Annotated[int, Query(ge=1, le=50)] is how you attach extra rules to a parameter. Annotated (from the standard typing module) is a type hint with extra information stuck to it: Python sees a plain int, and FastAPI reads the Query(...) part, here "at least 1, at most 50". It is the same rule system as Pydantic's Field from lesson 6.
from typing import Annotated
from fastapi import FastAPI, Query
app = FastAPI(title="Ask API")
ARTICLES = {
1: {"id": 1, "title": "Reset your password", "topic": "account"},
2: {"id": 2, "title": "Change your plan", "topic": "billing"},
3: {"id": 3, "title": "Download invoices", "topic": "billing"},
}
@app.get("/articles/{article_id}")
def get_article(article_id: int):
return ARTICLES[article_id]
@app.get("/articles")
def list_articles(
topic: str | None = None,
limit: Annotated[int, Query(ge=1, le=50)] = 10,
):
found = [a for a in ARTICLES.values() if topic is None or a["topic"] == topic]
return found[:limit] - A dict standing in for a database or a document store, so the example needs nothing else. Imagine the help articles a support bot searches.line 7
{article_id}in the path matches the parameter of the same name below. Like@GetMapping("/articles/{id}")with@PathVariable, orreq.params.idin Express, but already converted to anint.line 14- A missing id raises
KeyError, which FastAPI turns into a plain500 Internal Server Error. The section after next fixes that with a proper 404.line 16 - Not in the path, so it is a query parameter:
?topic=billing.str | None = Nonemakes it optional. Like@RequestParam(required = false).line 21 - An optional query parameter with a default of 10 and a range rule.
?limit=500is rejected for you.line 22 - A list comprehension (lesson 3): keep the articles whose topic matches, or all of them when no topic was given.line 24
Save the file (uvicorn reloads by itself) and try a few URLs. The quotes around the second URL stop your shell from treating & as a command separator:
curl http://localhost:8000/articles/2
curl "http://localhost:8000/articles?topic=billing&limit=1"
curl http://localhost:8000/articles/abc
{"id":2,"title":"Change your plan","topic":"billing"}
[{"id":2,"title":"Change your plan","topic":"billing"}]
{"detail":[{"type":"int_parsing","loc":["path","article_id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"abc"}]}
The last call never reached get_article. FastAPI answered with status 422 Unprocessable Content and a detail list: loc says where the problem is (path, then the parameter name), msg says what is wrong. That is the same error format as Pydantic's ValidationError from lesson 6, because FastAPI uses Pydantic underneath.
Watch out Routes are tried in the order you declare them. If @app.get("/articles/{article_id}") comes before @app.get("/articles/latest"), a request for /articles/latest matches the first route and fails with a 422 ("latest" is not an int). Declare fixed paths before paths with parameters.
3Request bodies and automatic 422 errors
For POST and PUT you send JSON in the request body. In FastAPI you describe that JSON with a Pydantic model and use the model as the parameter type. FastAPI reads the body, validates it against the model, and calls your function with a ready-made object. It is @RequestBody @Valid AskRequest req in Spring, or express.json() plus a validator such as zod in Express, in one step.
Here is the endpoint. Save it as main.py:
from typing import Literal
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI(title="Ask API")
class AskRequest(BaseModel):
question: str = Field(min_length=1, max_length=2000)
temperature: float = Field(default=0.2, ge=0, le=2)
style: Literal["short", "detailed"] = "short"
@app.post("/ask")
def ask(req: AskRequest):
return {"answer": f"You asked: {req.question}", "style": req.style, "temperature": req.temperature}
Because the parameter req has a Pydantic model as its type, FastAPI reads it from the body (a plain int or str would be a query parameter). question is required, temperature must be between 0 and 2, and style must be one of two words. Send one good and one bad request. -X POST sets the method, -H adds the header that says the body is JSON, and -d is the body:
curl -X POST http://localhost:8000/ask -H "Content-Type: application/json" -d '{"question": "What is RAG?"}'
curl -X POST http://localhost:8000/ask -H "Content-Type: application/json" -d '{"temperature": 5, "style": "funny"}'
{"answer":"You asked: What is RAG?","style":"short","temperature":0.2}
{"detail":[
{"type":"missing","loc":["body","question"],"msg":"Field required",
"input":{"temperature":5,"style":"funny"}},
{"type":"less_than_equal","loc":["body","temperature"],"msg":"Input should be less than or equal to 2",
"input":5,"ctx":{"le":2.0}},
{"type":"literal_error","loc":["body","style"],"msg":"Input should be 'short' or 'detailed'",
"input":"funny","ctx":{"expected":"'short' or 'detailed'"}}
]}
curl prints each reply on one line; the second one is split over several lines above so you can read it. The bad request got a 422 listing all three problems at once, each with its loc (body, then the field), the rule that failed (type), a readable msg, the input it got, and the rule's settings in ctx. You wrote no validation code at all. FastAPI cannot run in this page, but Pydantic can, so the box below does by hand what FastAPI does for you. Run it, then change the bodies at the bottom.
from typing import Literal
from pydantic import BaseModel, Field, ValidationError
class AskRequest(BaseModel):
question: str = Field(min_length=1, max_length=2000)
temperature: float = Field(default=0.2, ge=0, le=2)
style: Literal["short", "detailed"] = "short"
def handle(body: dict) -> tuple[int, dict]:
"""Roughly what FastAPI does with a JSON body before your endpoint runs."""
try:
req = AskRequest.model_validate(body)
except ValidationError as e:
detail = [
{"type": err["type"], "loc": ["body", *err["loc"]], "msg": err["msg"]}
for err in e.errors()
]
return 422, {"detail": detail}
return 200, {"answer": f"You asked: {req.question}", "temperature": req.temperature}
for body in [
{"question": "What is RAG?"},
{"question": "hi", "temperature": "0.7"},
{"temperature": 5, "style": "funny"},
]:
status, payload = handle(body)
if status == 200:
print(status, payload)
else:
print(status, len(payload["detail"]), "errors")
for item in payload["detail"]:
print(" ", item)
Expected output
200 {'answer': 'You asked: What is RAG?', 'temperature': 0.2}
200 {'answer': 'You asked: hi', 'temperature': 0.7}
422 3 errors
{'type': 'missing', 'loc': ['body', 'question'], 'msg': 'Field required'}
{'type': 'less_than_equal', 'loc': ['body', 'temperature'], 'msg': 'Input should be less than or equal to 2'}
{'type': 'literal_error', 'loc': ['body', 'style'], 'msg': "Input should be 'short' or 'detailed'"}model_validate(body) checks a dict against the model and returns an AskRequest, or raises ValidationError. e.errors() is the list of problems; each loc is a tuple such as ('question',), and ["body", *err["loc"]] puts "body" in front of it, exactly like FastAPI's loc. Note the second body: the string "0.7" became the float 0.7, because Pydantic converts values when it is safe (lesson 6). The same 422 protects your model bill: a request with a 50,000-character question is rejected by max_length before a single token is sent to the LLM.
Tip Put limits on everything a user controls: text length, list sizes, max_tokens, temperature. A Field rule costs one line and stops a prompt-stuffing request at the door.
4Response models, status codes and HTTPException
The previous section validated what comes in. response_model does the same for what goes out: FastAPI passes your return value through that model, so the client receives only the fields the model declares. Anything else in your dict (an internal system prompt, a cost field, a user's email) is dropped. It also documents the reply shape on /docs.
status_code= sets the success status, for example 201 Created for a POST that creates something. For errors you raise HTTPException(status_code, detail): FastAPI stops your function and replies with that status and {"detail": ...}. It is like throwing a ResponseStatusException in Spring, or res.status(404).json(...) in Express.
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, Field
app = FastAPI(title="Ask API")
class ChatIn(BaseModel):
title: str = Field(min_length=1, max_length=100)
class ChatOut(BaseModel):
id: int
title: str
CHATS: dict[int, dict] = {}
@app.post("/chats", response_model=ChatOut, status_code=status.HTTP_201_CREATED)
def create_chat(chat: ChatIn):
chat_id = len(CHATS) + 1
CHATS[chat_id] = {"id": chat_id, "title": chat.title, "system_prompt": "You are a support bot."}
return CHATS[chat_id]
@app.get("/chats/{chat_id}", response_model=ChatOut)
def get_chat(chat_id: int):
if chat_id not in CHATS:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Chat {chat_id} not found")
return CHATS[chat_id] - Two models for one thing is normal:
ChatInis what a client may send,ChatOutis what a client may see. Like a request DTO and a response DTO in Java.line 7 - An in-memory store, emptied every time uvicorn reloads. A real app would use a database.line 16
statusis a module of named constants (HTTP_201_CREATEDis just201). Use whichever you find easier to read.line 19- The stored chat has a
system_promptthe client must never see.line 22 - We return the whole dict, including
system_prompt.response_model=ChatOutfilters it down toidandtitleon the way out.line 23 raise, notreturn: the function stops here and FastAPI sends a 404 with{"detail": "Chat 42 not found"}.line 29
Try it. -i makes curl print the status line and headers too:
curl -i -X POST http://localhost:8000/chats -H "Content-Type: application/json" -d '{"title": "Refund question"}'
curl -i http://localhost:8000/chats/42
HTTP/1.1 201 Created
content-type: application/json
...
{"id":1,"title":"Refund question"}
HTTP/1.1 404 Not Found
content-type: application/json
...
{"detail":"Chat 42 not found"}
No system_prompt in the reply. You can also write the return type as a hint, def get_chat(chat_id: int) -> ChatOut:, and FastAPI uses it the same way. response_model= is the clearer choice when the function really returns a dict with extra fields, as here, because type checkers such as mypy would complain about a dict returned from a function that promises a ChatOut.
Watch out Returning a database row or a full dict from an endpoint without a response model sends every field to the client. That is how internal prompts, API keys and other users' data leak. Declare what goes out.
5Dependency injection with Depends
Most endpoints need the same things: the settings, a client for the model, the current user. FastAPI's answer is Depends(some_function): before calling your endpoint, FastAPI calls some_function and passes its result in. A dependency can have its own parameters (headers, query parameters, other dependencies), and FastAPI resolves the whole tree for each request.
For a Spring developer: it does the job of constructor injection with @Autowired beans, but per function and with no container or annotations scanning. A dependency is just a function. For an Express developer: it is like a middleware that runs only for the routes that ask for it, and hands its result to the handler instead of attaching it to req.
Annotated[Settings, Depends(get_settings)] says "a Settings object, which you get by calling get_settings". Give it a name once (SettingsDep below) and reuse it on every endpoint.
import os
from dataclasses import dataclass
from functools import lru_cache
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException
app = FastAPI(title="Ask API")
@dataclass(frozen=True)
class Settings:
model: str
api_key: str
@lru_cache
def get_settings() -> Settings:
print("reading settings")
return Settings(
model=os.environ.get("LLM_MODEL", "llama3.2:3b"),
api_key=os.environ.get("APP_API_KEY", "dev-key"),
)
SettingsDep = Annotated[Settings, Depends(get_settings)]
def check_api_key(settings: SettingsDep, x_api_key: Annotated[str | None, Header()] = None) -> None:
if x_api_key != settings.api_key:
raise HTTPException(status_code=401, detail="Missing or wrong X-API-Key header")
@app.get("/config", dependencies=[Depends(check_api_key)])
def show_config(settings: SettingsDep):
return {"model": settings.model} - The settings object from lesson 10 and lab 1: a frozen dataclass filled from environment variables.line 11
@lru_cache(from the standard library) remembers the result of the first call and returns the same object afterwards. So the settings are built once per process, a singleton bean in Spring terms.line 17- Only here to prove the caching: the uvicorn terminal prints this line once, on the first request, however many requests follow.line 19
- A type alias. Every parameter written
settings: SettingsDepgets the result ofget_settings().line 26 - A dependency that uses another dependency.
Header()reads the request header; FastAPI turns the underscores into dashes, sox_api_keyreads theX-API-Keyheader (header names ignore case).line 29 - A dependency can stop the request by raising. The endpoint never runs.line 31
dependencies=[...]runs a dependency whose result you do not need, only its check. Like a Spring Security filter on one route.line 34
Call it without and with the key:
curl http://localhost:8000/config
curl http://localhost:8000/config -H "X-API-Key: dev-key"
{"detail":"Missing or wrong X-API-Key header"}
{"model":"llama3.2:3b"}
The first reply has status 401. The big win comes in testing: because the endpoint asks for its settings instead of reading os.environ itself, a test can swap get_settings for a fake in one line (app.dependency_overrides), as the last section shows. The same goes for the model client, which is what the next section builds.
Tip In a real service, compare secrets with secrets.compare_digest(a.encode(), b.encode()) instead of !=, so the time the check takes does not reveal how many characters were right. Better still, put the API behind your normal authentication.
6async endpoints and lifespan: one shared HTTP client
FastAPI accepts both kinds of endpoint, and runs them differently:
async defendpoints run on the event loop (lesson 9). Use them when the work is awaiting I/O with an async library:httpx.AsyncClient,AsyncOpenAI, an async database driver. One process can then wait on hundreds of model calls at once. This is the WebFlux style in Spring, and the normal style in Node.- Plain
defendpoints run in a thread pool (40 threads by default), so blocking code such as the syncOpenAIclient orrequestsis fine there. This is the classic Spring MVC thread-per-request style.
For LLM apps, most endpoints wait on a model, so async def with an async client is the usual choice. The one rule: never block inside async def. A time.sleep or a sync HTTP call there freezes the whole server, every request, exactly like the blocked event loop in lesson 9.
The client itself should be created once, not per request, so connections to the model server are reused. That is the job of the lifespan: an async context manager (lesson 7) whose code before yield runs when the server starts, and whose code after yield runs when it stops. It is Spring's @PostConstruct and @PreDestroy in one function. Start a model server first (Ollama from lab 1, with llama3.2:3b pulled), then save this:
import os
from contextlib import asynccontextmanager
from typing import Annotated
import httpx
from fastapi import Depends, FastAPI, HTTPException, Request
from pydantic import BaseModel, Field
BASE_URL = os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1")
MODEL = os.environ.get("LLM_MODEL", "llama3.2:3b")
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.llm = httpx.AsyncClient(base_url=BASE_URL, timeout=60)
print("startup: HTTP client ready")
yield
await app.state.llm.aclose()
print("shutdown: HTTP client closed")
app = FastAPI(title="Ask API", lifespan=lifespan)
def get_llm(request: Request) -> httpx.AsyncClient:
return request.app.state.llm
class AskRequest(BaseModel):
question: str = Field(min_length=1, max_length=2000)
@app.post("/ask")
async def ask(req: AskRequest, llm: Annotated[httpx.AsyncClient, Depends(get_llm)]):
payload = {"model": MODEL, "messages": [{"role": "user", "content": req.question}]}
try:
r = await llm.post("/chat/completions", json=payload)
r.raise_for_status()
except httpx.HTTPError as e:
raise HTTPException(status_code=502, detail=f"Model server error: {type(e).__name__}")
return {"answer": r.json()["choices"][0]["message"]["content"]} - Ollama's OpenAI-compatible API. Point
LLM_BASE_URLat any other OpenAI-compatible server without touching the code.line 9 - Turns the generator function below into an async context manager, the async version of
@contextmanagerfrom lesson 7.line 13 - One client for the whole process.
app.stateis a place to keep app-wide objects.timeout=60because a local model can take a while to answer.line 15 - Everything before
yieldruns once at startup, everything after it once at shutdown. The server handles requests while the function is paused here.line 17 - Closes the pooled connections cleanly when you press
Ctrl+C.line 18 - Passing
lifespan=is how FastAPI learns about it. (Old tutorials use@app.on_event("startup"), which is deprecated.)line 22 - A dependency that hands out the shared client.
Requestis the current HTTP request;request.appis our app. Tests replace this one function.line 25 async def, because the body awaits the network. While this request waits on the model, the same process serves other requests.line 34- The base URL ends in
/v1, and httpx appends this path to it: the request goes tohttp://localhost:11434/v1/chat/completions, the same endpoint as in lab 1.line 37 - Turns a 4xx or 5xx reply from the model server into an
httpx.HTTPStatusError.line 38 httpx.HTTPErroris the parent of both connection errors and status errors. We answer 502 Bad Gateway: the problem is upstream, not in the client's request.line 39
Ask a question:
curl -X POST http://localhost:8000/ask -H "Content-Type: application/json" -d '{"question": "What is RAG in one sentence?"}'
{"answer":"RAG (Retrieval-Augmented Generation) is a technique where a model first retrieves relevant documents and then uses them to generate a more accurate answer."}
The model writes the answer, so your words will differ. Stop Ollama and ask again: you get {"detail":"Model server error: ConnectError"} with status 502 instead of a crash. When you stop uvicorn with Ctrl+C, its terminal shows shutdown: HTTP client closed right after Waiting for application shutdown..
Watch out Calling the sync OpenAI client, requests.get or time.sleep inside an async def endpoint blocks the event loop, so every request waits, not just this one. Either use the async client and await it, or make the endpoint a plain def so FastAPI runs it in the thread pool.
7Streaming tokens with StreamingResponse and SSE
Waiting ten seconds for a complete answer feels broken. Chat apps show the answer as it is written, token by token. The browser keeps one HTTP response open and the server writes small events into it. The simplest standard for that is Server-Sent Events (SSE): the content type text/event-stream, and each event is a line starting with data: followed by a blank line.
StreamingResponse takes a generator (lesson 8) or an async generator and sends every piece it yields to the client immediately. To keep this example independent of a model, fake_tokens yields a fixed reply with a short pause per token. The streaming chat lab plugs in a real model.
import asyncio
import json
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
app = FastAPI(title="Ask API")
class AskRequest(BaseModel):
question: str
async def fake_tokens(question: str):
for token in ["Paris", " is", " the", " capital", " of", " France", "."]:
await asyncio.sleep(0.1)
yield token
def sse(data: dict) -> str:
return f"data: {json.dumps(data)}\n\n"
@app.post("/ask/stream")
async def ask_stream(req: AskRequest):
async def events():
async for token in fake_tokens(req.question):
yield sse({"type": "token", "text": token})
yield sse({"type": "done"})
return StreamingResponse(events(), media_type="text/event-stream", headers={"Cache-Control": "no-cache"}) - An async generator, like a model streaming tokens. Note the tokens are word pieces with leading spaces.line 15
asyncio.sleep, nevertime.sleep: the server keeps serving other requests between tokens.line 17- One SSE event:
data:, the JSON on one line, and a blank line (\n\n) that ends the event.json.dumpsnever writes a raw newline, so the event cannot break.line 22 - An inner async generator that can use
req. Nothing in it runs until FastAPI starts sending the response.line 27 - A final event tells the client the answer is complete, so it can stop showing a spinner.line 30
text/event-streamtells the client this is SSE.no-cachestops proxies from storing the stream.line 32
Watch it arrive. -N turns off curl's output buffer so you see each event the moment it comes:
curl -N -X POST http://localhost:8000/ask/stream -H "Content-Type: application/json" -d '{"question": "Capital of France?"}'
data: {"type": "token", "text": "Paris"}
data: {"type": "token", "text": " is"}
data: {"type": "token", "text": " the"}
data: {"type": "token", "text": " capital"}
data: {"type": "token", "text": " of"}
data: {"type": "token", "text": " France"}
data: {"type": "token", "text": "."}
data: {"type": "done"}
The lines appear one every tenth of a second. Recent FastAPI versions (0.165 included) can also format the events for you: declare the route with response_class=EventSourceResponse (from fastapi.sse) and yield plain dicts from the endpoint itself. The wire format is the same data: {...} lines, and it also sets the anti-buffering headers. Writing sse() yourself first shows you exactly what goes over the wire.
from fastapi.sse import EventSourceResponse
@app.post("/ask/events", response_class=EventSourceResponse)
async def ask_events(req: AskRequest):
async for token in fake_tokens(req.question):
yield {"type": "token", "text": token} # sent as: data: {"type": "token", ...}
yield {"type": "done"}
Tip SSE is plain HTTP, so it passes through proxies, load balancers and your authentication like any other request. WebSockets are for two-way traffic (live collaboration, games); a chat answer flows one way, so SSE is the usual choice, and it is what the OpenAI API itself uses to stream.
8Background tasks and CORS
Background tasks run after the response has been sent. Ask for a BackgroundTasks parameter and call add_task(function, args...). The user gets the answer immediately, and the slow bookkeeping happens afterwards: saving token usage, writing a log line, sending a notification.
CORS is the browser rule that blocks a page from one origin (say your React app on http://localhost:5173) from reading responses from another origin (your API on http://localhost:8000) unless the API allows it. curl and other servers are not affected, only browsers. CORSMiddleware adds the Access-Control-Allow-* headers for the origins you list, like @CrossOrigin or a CorsConfigurationSource in Spring, or the cors package in Express.
import json
import time
from fastapi import BackgroundTasks, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
app = FastAPI(title="Ask API")
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173"],
allow_methods=["GET", "POST"],
allow_headers=["Content-Type", "X-API-Key"],
)
class AskRequest(BaseModel):
question: str
def log_usage(question: str, tokens: int) -> None:
time.sleep(1)
with open("usage.jsonl", "a", encoding="utf-8") as f:
f.write(json.dumps({"question": question, "tokens": tokens}) + "\n")
print("usage saved")
@app.post("/ask")
def ask(req: AskRequest, background: BackgroundTasks):
answer = f"You asked: {req.question}"
background.add_task(log_usage, req.question, tokens=42)
print("answer sent")
return {"answer": answer} - Middleware wraps every request, like a servlet filter or
app.use(cors(...)).line 10 - The exact origins (scheme, host and port) of the web pages allowed to call this API from a browser. Your real front-end URL goes here in production.line 12
- Headers the page may send.
X-API-Keymust be listed or the browser refuses to send it.line 14 - A plain
defbackground task runs in the thread pool, so a blockingtime.sleephere does not hurt other requests. It stands in for slow work.line 22 - Appends one JSON object per line (the JSON Lines format from lesson 10), a simple usage log you can later load with pandas.line 24
- FastAPI provides this object because of the
BackgroundTaskstype hint. NoDependsneeded.line 30 - Schedules
log_usage(req.question, tokens=42)for after the response. It does not run yet.line 32
Call /ask. The answer comes back at once, not after the one-second sleep, and one second later the uvicorn terminal prints usage saved and usage.jsonl has a new line:
answer sent
INFO: 127.0.0.1:51532 - "POST /ask HTTP/1.1" 200 OK
usage saved
To see CORS at work without a browser, send the preflight request a browser sends before a cross-origin POST, with -i to show headers:
curl -i -X OPTIONS http://localhost:8000/ask -H "Origin: http://localhost:5173" -H "Access-Control-Request-Method: POST"
HTTP/1.1 200 OK
...
access-control-allow-methods: GET, POST
access-control-allow-origin: http://localhost:5173
...
With -H "Origin: http://evil.example" instead, the reply is 400 Bad Request with the body Disallowed CORS origin and no access-control-allow-origin header, so a browser would block the page.
Watch out Background tasks live inside the server process. If it restarts or crashes, unfinished tasks are lost, and long tasks hold a worker thread. For work that must not be lost or takes minutes (indexing a big PDF into a vector store, a batch of 1,000 embeddings), use a real job queue (Celery, RQ, arq, or a cloud queue).
9Testing endpoints with TestClient
TestClient calls your app in memory: no uvicorn, no port, no network. It has the same methods as an HTTP client (client.get, client.post(..., json=...)), and returns responses with .status_code and .json(). It is the equivalent of Spring's MockMvc or supertest in Express.
The trick for LLM apps is app.dependency_overrides: a dict from a dependency to a replacement. Here the tests replace get_llm from section 6 with an httpx.AsyncClient whose MockTransport answers every request with a Python function instead of a real server. So the tests need no model and run in a fraction of a second. Save this next to the section 6 main.py, and add the test tools as dev dependencies:
uv add --dev pytest httpx2 + httpx2==2.16.2 + pytest==9.2.0 (plus a few helper packages)
import json
import httpx
from fastapi.testclient import TestClient
from main import app, get_llm
def fake_model(request: httpx.Request) -> httpx.Response:
body = json.loads(request.content)
question = body["messages"][-1]["content"]
return httpx.Response(200, json={"choices": [{"message": {"content": f"echo: {question}"}}]})
def model_down(request: httpx.Request) -> httpx.Response:
raise httpx.ConnectError("connection refused")
def use(handler):
async def fake_llm():
async with httpx.AsyncClient(transport=httpx.MockTransport(handler), base_url="http://fake") as client:
yield client
app.dependency_overrides[get_llm] = fake_llm
def teardown_function():
app.dependency_overrides.clear()
def test_ask_returns_the_model_answer():
use(fake_model)
with TestClient(app) as client:
r = client.post("/ask", json={"question": "What is RAG?"})
assert r.status_code == 200
assert r.json() == {"answer": "echo: What is RAG?"}
def test_missing_question_is_422():
use(fake_model)
with TestClient(app) as client:
r = client.post("/ask", json={})
assert r.status_code == 422
assert r.json()["detail"][0]["loc"] == ["body", "question"]
def test_model_down_is_502():
use(model_down)
with TestClient(app) as client:
r = client.post("/ask", json={"question": "hi"})
assert r.status_code == 502
assert r.json() == {"detail": "Model server error: ConnectError"} - FastAPI's test client. It needs an HTTP client library installed:
httpx2(the maintained successor of httpx, by the Pydantic team). With onlyhttpxit still works but prints a deprecation warning.line 4 - Import the real app and the dependency we are going to replace.line 6
- A fake model server: a function from request to response. It echoes the question back in the same JSON shape a real
/chat/completionsreply has.line 9 - Simulates "Ollama is not running": the same error httpx raises when nothing listens on the port.line 16
- A dependency can
yieldinstead ofreturn: FastAPI uses the value, and runs the code afteryield(here, closing the client) when the request is done.line 22 - From now on, every request that asks for
get_llmgetsfake_llminstead. The endpoint code does not change at all.line 24 - pytest runs a function with this name after every test. Clearing the overrides stops one test's fake from leaking into the next.line 27
with TestClient(app)also runs the lifespan (startup before the block, shutdown after it). Withoutwith, the lifespan does not run.line 33- Plain
assertstatements: pytest shows both sides of a failing comparison. The next lesson covers pytest properly.line 35
Run the tests from the project folder. The model server does not need to be running:
uv run pytest -q
... [100%]
3 passed in 0.41s
Each dot is a passing test. This is the pattern every Build lab uses: the endpoint asks for its dependencies, and tests hand it fakes. The same dependency_overrides line replaces get_settings from section 5 when a test needs a different model name or API key.
Common mistakes
- Blocking inside
async def: the syncOpenAIclient,requests, ortime.sleepfreeze every request. Await an async client, or make the endpoint a plaindef. - Creating a new HTTP or SDK client inside every request. Create one in the lifespan and hand it out with
Depends, so connections are reused and closed cleanly. - Declaring
/chats/{chat_id}before/chats/latest: routes match in order, so "latest" hits the first one and fails with a 422. - Returning internal dicts without a
response_model, which leaks fields such as system prompts or keys. Declare what goes out. - Using
allow_origins=["*"]in production. Any website could then call your API from a visitor's browser. List your real front-end origins. - Running
uvicorn --reloadin production, or using background tasks for work that must not be lost. Reload is for development; long or critical jobs belong in a queue.
Practice
Write the code, then press Check. Your work is saved in this browser.
1A chat request that rejects bad input
Finish the two Pydantic models a POST /chat endpoint would use as its body. Message.role may only be "user" or "assistant" (clients must not send their own system message), and content is at most 4000 characters. ChatRequest.messages must hold between 1 and 50 messages, and max_tokens defaults to 256 and must be between 1 and 4096. FastAPI would turn every rule you add into a 422 for free.
from pydantic import BaseModel, Field
class Message(BaseModel):
role: str
content: str
class ChatRequest(BaseModel):
messages: list[Message]
max_tokens: int = 256
print(ChatRequest.model_validate({"messages": [{"role": "user", "content": "hi"}]}))
Hint
Use `Literal["user", "assistant"]` (from `typing`) for the role, `Field(max_length=4000)` for content, `Field(min_length=1, max_length=50)` for the list, and `Field(default=256, ge=1, le=4096)` for max_tokens.
2Build the 422 detail
Write to_detail(error, where) that turns a Pydantic ValidationError into the list FastAPI puts under "detail" in a 422 reply: one dict per problem with the keys type, loc and msg, where loc is a list that starts with where (such as "body" or "query") followed by the parts of Pydantic's own loc.
from pydantic import BaseModel, Field, ValidationError
def to_detail(error: ValidationError, where: str) -> list[dict]:
# one dict per item in error.errors(): {"type": ..., "loc": [where, ...], "msg": ...}
return []
class Ask(BaseModel):
question: str
temperature: float = Field(default=0.2, le=2)
try:
Ask.model_validate({"temperature": 9})
except ValidationError as e:
print(to_detail(e, "body"))
Hint
Loop over `error.errors()`. Each item is a dict with `"type"`, `"loc"` (a tuple) and `"msg"`. Build the new loc with `[where, *item["loc"]]`.
3Format a token stream as SSE
Write sse(data) that returns one Server-Sent Event for a dict: "data: ", the dict as JSON (use json.dumps), and two newlines. Then write the generator events(tokens) that yields one event {"type": "token", "text": t} per token and finally {"type": "done"}. This is the body a StreamingResponse would send.
import json
def sse(data: dict) -> str:
return json.dumps(data)
def events(tokens):
return [sse({"type": "token", "text": t}) for t in tokens]
print("".join(events(["Hi", " there"])))
Hint
Return `f"data: {json.dumps(data)}\n\n"`. In `events`, loop over the tokens and `yield sse(...)` for each, then `yield sse({"type": "done"})` after the loop.
Interview questions
Q1How does FastAPI compare with Spring Boot?
Both map routes to functions and turn objects into JSON. FastAPI gets parsing, validation and OpenAPI docs from Python type hints and Pydantic models instead of annotations like @RequestBody @Valid, uses Depends functions instead of a bean container for dependency injection, and runs on an ASGI server (uvicorn) instead of a servlet container. It is async-first, closer to WebFlux than to classic Spring MVC, but also runs plain def endpoints in a thread pool.
Q2What is the difference between a def and an async def endpoint in FastAPI?
An async def endpoint runs on the event loop, so it must only await non-blocking I/O; one blocking call there stalls every request. A plain def endpoint runs in a worker thread pool, so blocking libraries are safe there, at the cost of one thread per concurrent request. For LLM calls, async def with an async client scales best.
Q3Why does FastAPI return 422 and not 400 for bad input?
FastAPI uses 422 Unprocessable Content for a request that is well-formed HTTP but fails validation of the path, query, headers or body. The body lists every problem with its location, type and message, generated from the Pydantic models. You can change the format with a custom exception handler for RequestValidationError if your API contract needs 400.
Q4How do you test a FastAPI endpoint that calls an LLM without calling the LLM?
Make the endpoint get its model client through a dependency (Depends(get_llm)), then in tests set app.dependency_overrides[get_llm] to a function that returns a fake, for example an httpx.AsyncClient with a MockTransport, or a fake streaming function. Call the app in memory with TestClient, and clear the overrides after each test.
Q5How would you stream an LLM answer from FastAPI to a browser?
Return a StreamingResponse (or use EventSourceResponse) with media type text/event-stream, fed by an async generator that awaits tokens from an async model client and yields each one as a Server-Sent Event (data: {...} plus a blank line), with a final done event. Disable caching and proxy buffering, and handle client disconnects so the model call is cancelled.
Q6What is the lifespan in FastAPI used for?
It is an async context manager passed to FastAPI(lifespan=...). Code before yield runs once at startup (create a shared HTTP or SDK client, load a model or an index, open a connection pool) and code after yield runs once at shutdown (close them). It replaces the deprecated on_event("startup") hooks.