Sub topic 2
The endpoint and request model
This chapter builds the entry point of the streaming feature: a POST endpoint that accepts a prompt and rejects bad input before any model call happens. It assumes you know basic Python and async/await, how HTTP requests and responses work, and what an LLM chat API does. It also assumes you have seen a FastAPI route and a Pydantic model before. The examples use Pydantic v2 and FastAPI 0.100 or later.
The endpoint returns a plain JSON object for now. Later chapters replace that return value with a stream. The request side stays the same.
Why the request model matters more for streaming
A streaming endpoint sends the status line and headers first, usually 200 OK, and then the body arrives in pieces. After that point you can no longer change the status code. A request you should have rejected can't be turned into a 400 or 422.
All input checking therefore has to happen before the first byte of the response. FastAPI helps here. It parses and validates the request body before it calls your function. If validation fails, your function never runs, no model call is made, and the client gets a clean 422 Unprocessable Entity.
The request model is where you decide what a legal request looks like. Everything past it can assume the input is sane.
flowchart TDThe diagram below shows the order of events.
A minimal endpoint
Start with the smallest version that does something useful. Save it as main.py.
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) -> dict:
return {"received_chars": len(body.prompt)}Run it with uvicorn main:app --reload, then call it:
curl -s -X POST http://localhost:8000/chat \
-H "Content-Type: application/json" \
-d '{"prompt": "Say hello"}'The response is {"received_chars":9}.
Three things in this code carry the design:
@app.post("/chat")registers the function for the POST method on the path/chat.- The parameter
body: ChatRequesthas a Pydantic model as its type. FastAPI sees that and reads the JSON request body into that model. You do not parse JSON yourself. Field(min_length=1, max_length=4000)attaches constraints to thepromptfield. They are checked during validation.
Why POST and a JSON body
Chat prompts can be long and can contain private data. A GET request would put the prompt in the URL, where it ends up in access logs, browser history, and proxy logs. URLs also have practical length limits. A POST body avoids both problems.
There is one trade-off to know about. The browser's built-in EventSource API, which is made for Server-Sent Events, can only send GET requests and cannot set a body. A browser client for a POST endpoint has to use fetch and read the response body as a stream. Python clients, covered later in this tutorial, have no such restriction.
Field constraints you will use
Pydantic's Field accepts constraints for each type. These are the ones that matter for an LLM endpoint.
| Constraint | Applies to | Example use |
|---|---|---|
| `min_length` | strings, lists | Reject an empty prompt |
| `max_length` | strings, lists | Cap prompt size and cost |
| `ge`, `le` | numbers | Keep `temperature` between 0 and 2 |
| `pattern` | strings | Restrict a `model` name to known characters |
| `default` | any | Make a field optional with a fallback value |
max_length=4000 counts characters, not tokens. A character limit is a cheap upper bound on cost and a guard against abuse. It does not guarantee the prompt fits in the model's context window. If that matters, count tokens in the handler or in a separate check.
What a validation failure looks like
Send an empty prompt:
curl -s -X POST http://localhost:8000/chat \
-H "Content-Type: application/json" \
-d '{"prompt": ""}'FastAPI answers with status 422 and a body like this:
{
"detail": [
{
"type": "string_too_short",
"loc": ["body", "prompt"],
"msg": "String should have at least 1 character",
"input": "",
"ctx": {"min_length": 1}
}
]
}The loc list says where the problem is: in the body, in the field prompt. The client can use this to point at the right input. You get this behavior without writing any error-handling code.
A request fails the same way in each of these cases:
- The body is not valid JSON.
- The
promptfield is missing. promptis not a string, for example{"prompt": 42}. Pydantic's default mode does not coerce an integer to a string.promptis longer than 4000 characters.
A missing Content-Type: application/json header also matters. FastAPI may fail to read the body as JSON without it.
Tightening the model
The minimal model has two weaknesses. A prompt of only spaces passes min_length=1. Misspelled fields, such as {"promt": "hi"}, are ignored by default. In that second case the client would see a 422 for the missing prompt and nothing about the typo, which is confusing when other fields are optional.
Pydantic's model_config fixes both:
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict, Field
app = FastAPI()
class ChatRequest(BaseModel):
model_config = ConfigDict(str_strip_whitespace=True, extra="forbid")
prompt: str = Field(min_length=1, max_length=4000)
temperature: float = Field(default=0.7, ge=0.0, le=2.0)
@app.post("/chat")
async def chat(body: ChatRequest) -> dict:
return {"prompt": body.prompt, "temperature": body.temperature}str_strip_whitespace=Trueremoves leading and trailing whitespace from strings before the length checks run." "becomes""and failsmin_length.extra="forbid"turns unknown fields into validation errors instead of silently dropping them.temperatureis optional. If the client omits it, the default0.7is used. If the client sends a value outside 0 to 2, the request fails.
Exposing temperature to clients is a product decision, not a requirement. Every field you accept is a field you must validate, document, and support. The rest of this tutorial uses the single-field ChatRequest with only prompt, because it keeps the streaming code easy to read.
Why the handler is `async def`
Calling an LLM is network I/O. The handler will spend almost all its time waiting for the model provider to send data. An async def handler runs on the event loop, so while it waits, the server can handle other requests.
If you declare the handler with plain def, FastAPI runs it in a thread pool. That works for blocking code but is the wrong fit for an async LLM client, which needs an event loop. The opposite mistake is also common: calling blocking code, such as time.sleep or a synchronous HTTP library, inside an async def handler. That freezes the event loop and stalls every other request on the worker.
The next chapters build on this. The handler will return an async generator wrapped in a response object, and the event loop will drive it.
Testing the validation
You can check the validation rules without starting a server. FastAPI's TestClient calls the app directly. It needs the httpx package installed.
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_valid_prompt_is_accepted():
resp = client.post("/chat", json={"prompt": "Say hello"})
assert resp.status_code == 200
def test_empty_prompt_is_rejected():
resp = client.post("/chat", json={"prompt": ""})
assert resp.status_code == 422
assert resp.json()["detail"][0]["loc"] == ["body", "prompt"]
def test_whitespace_prompt_is_rejected():
resp = client.post("/chat", json={"prompt": " "})
assert resp.status_code == 422
def test_unknown_field_is_rejected():
resp = client.post("/chat", json={"prompt": "hi", "promt": "typo"})
assert resp.status_code == 422Run these against the tightened model from the previous section. The whitespace and unknown-field tests fail against the minimal model, which is a good way to see what each setting does.
Common mistakes
- Using a plain
dictorRequestas the body. You lose validation and the generated API documentation. Use a Pydantic model. - Checking input inside the generator. Once the stream has started, a failure can only be reported as an event in the body. Check inputs in the model, before the response begins.
- Assuming the limit protects the server from large bodies.
max_lengthis checked after the body has been read and parsed. Limits on the raw request size belong in the server or the reverse proxy. The last chapter returns to this. - Putting secrets or API keys in the request model. The client should not send provider credentials. The server holds them, as the dependency chapter shows.
What comes next
You now have a validated entry point. The next chapter looks at async generators, the Python feature that will produce the stream. After that, StreamingResponse connects a generator to this endpoint.
Exercise
A client sends POST /chat with the body {"prompt": ""} to the endpoint in this chapter. What status code does it get back, does your handler function run, and where in the error response can the client find which field failed?
Show answer
The client gets status 422. The handler does not run, because FastAPI validates the body against ChatRequest before calling it, and the empty string fails min_length=1. The failing field is identified in the "loc" entry of the first item in the "detail" list, which is ["body", "prompt"].
Exercise
Why is it better to reject an over-long prompt in the request model than inside the async generator that streams the answer?
Show answer
Validation in the model runs before the response starts, so the server can still return a 422 status. Once streaming has begun, the 200 status and headers are already sent, so a failure inside the generator can only be reported as part of the stream body. Rejecting early also avoids starting any model call for a request that was never valid.