Sub topic 2
The endpoint and request model
This chapter builds the part of the endpoint that exists before any streaming happens: the route and the Pydantic model that validates the request. I assume you can write a basic FastAPI route and know what a Pydantic model is. Later chapters replace the return value with a stream and leave this request handling unchanged.
Why validation comes first
A streaming response commits to a status code the moment the first byte is sent. After that, you can no longer return a clean 4xx error for a bad request. Reject invalid input before the stream starts. FastAPI does this for you when the route declares a Pydantic model as a parameter.
An LLM endpoint has two more reasons to validate strictly:
- Every character of the prompt costs money and latency, so an unbounded prompt is a cost and abuse risk.
- An empty prompt reaches the model provider and fails there, after you have already done work.
Defining the request model
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class ChatRequest(BaseModel):
prompt: str = Field(min_length=1, max_length=4000)
@app.post("/chat")
async def chat(body: ChatRequest):
return {"received_chars": len(body.prompt)}This version returns plain JSON so you can check the request handling in isolation. Save it as main.py and run it with uvicorn main:app --reload.
Three choices here are worth explaining.
- POST, not GET. Prompts are long and may contain sensitive text. A POST body keeps them out of URLs, server logs, and browser history. A browser's built-in
EventSourceonly sends GET, so browser clients later usefetchto read the stream. Fieldconstraints.min_length=1rejects an empty string.max_length=4000caps the input. Pick a limit that matches your model's context budget and your cost tolerance.async def. The handler will await network calls to the model provider. An async route lets one worker serve many concurrent streams without a thread per client.
What happens to a bad request
FastAPI parses the JSON body, validates it against ChatRequest, and only then calls chat. If validation fails, your function never runs.
Try it with curl:
curl -s -X POST http://localhost:8000/chat \
-H "Content-Type: application/json" \
-d '{"prompt": ""}'The response has status 422 (Unprocessable Entity). Its detail list names the failing field in loc (["body", "prompt"]) and the rule in type (string_too_short). A request with a valid prompt returns {"received_chars": N}.
Common errors
| Symptom | Likely cause |
|---|---|
| 422 with `missing` in `loc` | The client sent no `prompt` key, or sent form data instead of JSON |
| 422 with `json_invalid` | The body is not valid JSON, often from shell quoting |
| 422 with `string_type` | `prompt` was a number or object, not a string |
| 415 or an empty body | The `Content-Type: application/json` header is missing |
Keeping the model small
Resist adding fields you do not use yet. Model name, temperature, and conversation history are all plausible additions. Each one becomes part of your public contract and needs its own limits. If you let clients choose the model, validate the choice against an allow-list, because an arbitrary model name lets callers pick the most expensive one. This tutorial reads the model name from an environment variable on the server instead.
Exercise
A client sends POST /chat with the body {"prompt": ""} to the endpoint above. What status code does it get, and does the chat function run?
Show answer
It gets 422. FastAPI validates the body against ChatRequest before calling the function, and min_length=1 rejects the empty string, so chat never runs.
Exercise
Why is it important to reject a bad request during validation instead of inside the streaming generator?
Show answer
Once a streaming response starts, the 200 status and headers are already sent. An error found later can only be reported inside the stream, not as a proper 4xx status. Validating first lets you return a clean 422.