Chapter 4 · Your First Backend
Pydantic Models, Validation and Error Responses
- Page 18 of 22
- 17 min read
An API is a contract: "send me data shaped like this, and I will answer with data shaped like that". On the last page, one tiny Pydantic model (SentimentRequest) was enough to reject a missing field or a wrong type. Real requests need more: a name that must be 3 to 40 characters, a temperature between 0 and 2, at most 5 tags, a valid email, a template that must contain a placeholder. And responses need rules too, so that an internal field (an owner's email, a cost, an API key) never leaks out by accident.
On this page you build a small prompt library API, the kind of internal service AI teams use to store and reuse prompt templates. You will describe its data with Pydantic models, put limits on every field, read validation errors properly, filter responses, and send the right status code for create, read, delete and "not found".
What you will learn
- How to define Pydantic models, create them from data, and turn them back into dicts and JSON.
- How to add constraints with
Field(lengths, ranges, patterns), fixed choices withLiteral, and your own rules withfield_validator. - How to read a 422 validation error:
type,loc,msg,inputandctx. - How response models hide fields, and how to send 201, 204, 404 and 409 with
status_codeandHTTPException. - A sensible first project structure: an
apppackage withmain.pyandschemas.py.
Set up the project
A fresh uv project, as on Your First FastAPI App. This time the code lives in an app package rather than a single main.py; you will see why at the end of the page.
mkdir -p ~/projects
cd ~/projects
uv init -q --no-package bitbyte-prompts
cd bitbyte-prompts
uv add -q "fastapi[standard]"
rm main.py
mkdir app
touch app/__init__.py
ls -A app__init__.pyWith pip instead: python -m venv .venv, source .venv/bin/activate, pip install "fastapi[standard]", then the same mkdir and touch. The empty app/__init__.py marks the folder as a Python package, so you can write from app.schemas import ....
Pydantic models
A Pydantic model is a class that inherits from BaseModel and lists its fields with type hints. Creating one validates the data: values are checked and, where it is safe, converted. Save the schemas, the shapes of your API's data, in their own file:
# file: app/schemas.py
"""The shapes of the data the prompt library accepts and returns."""
from typing import Annotated, Literal
from pydantic import BaseModel, EmailStr, Field, field_validator
class PromptBase(BaseModel):
name: Annotated[str, Field(min_length=3, max_length=40, pattern=r"^[a-z0-9-]+$")]
template: Annotated[str, Field(min_length=10, max_length=2000)]
model: Literal["bitbyte-mini", "bitbyte-pro"] = "bitbyte-mini"
temperature: Annotated[float, Field(ge=0, le=2)] = 0.7
tags: Annotated[list[str], Field(max_length=5)] = []
@field_validator("template")
@classmethod
def must_have_question(cls, value: str) -> str:
if "{question}" not in value:
raise ValueError("template must contain the {question} placeholder")
return value
class PromptCreate(PromptBase):
"""What a client sends to create a prompt."""
owner_email: EmailStr
class PromptPublic(PromptBase):
"""What the API returns: no owner_email."""
id: int
class RenderRequest(BaseModel):
question: Annotated[str, Field(min_length=1, max_length=500)]
class RenderResponse(BaseModel):
prompt_id: int
model: str
temperature: float
text: strTry the models in Python first, without any web server. A valid prompt:
from app.schemas import PromptCreate, PromptPublic
prompt = PromptCreate(
name="course-helper",
template="You are a friendly tutor. Answer briefly: {question}",
temperature="0.2",
owner_email="[email protected]",
)
print(repr(prompt.temperature), prompt.model, prompt.tags)
print(prompt.model_dump())
print(prompt.model_dump_json(exclude={"owner_email"}))0.2 bitbyte-mini []
{'name': 'course-helper', 'template': 'You are a friendly tutor. Answer briefly: {question}', 'model': 'bitbyte-mini', 'temperature': 0.2, 'tags': [], 'owner_email': '[email protected]'}
{"name":"course-helper","template":"You are a friendly tutor. Answer briefly: {question}","model":"bitbyte-mini","temperature":0.2,"tags":[]}What to notice:
"0.2"(a string) became the float0.2. Pydantic converts when the meaning is unambiguous, which is handy for query strings and form data. It will not turn"warm"into a number.- Fields you left out got their defaults:
modelis"bitbyte-mini"andtagsis an empty list (a fresh one for each object, so the shared-default trap of plain Python does not apply). model_dump()gives a dict,model_dump_json()gives a JSON string; both can leave fields out. Pydantic v2 uses these names; the old.dict()and.json()from v1 tutorials are deprecated.
Now a prompt that breaks several rules at once:
from pydantic import ValidationError
try:
PromptCreate(
name="Course Helper!",
template="Answer this.",
model="gpt-x",
temperature=3,
owner_email="nadia-at-example",
)
except ValidationError as exc:
print(exc.error_count(), "errors")
for error in exc.errors():
print(error["loc"], "|", error["type"], "|", error["msg"])5 errors
('name',) | string_pattern_mismatch | String should match pattern '^[a-z0-9-]+$'
('template',) | value_error | Value error, template must contain the {question} placeholder
('model',) | literal_error | Input should be 'bitbyte-mini' or 'bitbyte-pro'
('temperature',) | less_than_equal | Input should be less than or equal to 2
('owner_email',) | value_error | value is not a valid email address: An email address must have an @-sign.Pydantic does not stop at the first problem: it checks every field and reports all errors together, each with a location, a machine-readable type and a human message. That is exactly what FastAPI will send back to clients. Notice the custom rule's message too: your ValueError text appears after Value error,.
Field constraints
Constraints go inside Annotated[type, Field(...)]. The ones you will use most:
| Constraint | Works on | Example in schemas.py | Error type when broken |
|---|---|---|---|
min_length, max_length | strings, lists | name 3 to 40 characters; at most 5 tags | string_too_short, too_long |
ge, gt, le, lt | numbers | temperature from 0 to 2 | less_than_equal |
pattern | strings | name only lowercase letters, digits and - | string_pattern_mismatch |
Literal[...] | any | model must be one of two names | literal_error |
| A special type | strings | EmailStr (also HttpUrl, UUID, datetime) | value_error |
@field_validator | anything | template must contain {question} | value_error |
For AI endpoints these limits are not decoration. A max_length on text caps how many tokens one request can cost you; a range on temperature stops values the provider would reject anyway; a Literal on the model name stops a client from choosing your most expensive model.
The API
Now use the models in endpoints. The data lives in a dict in memory, which is enough to learn with (it is emptied whenever the server restarts; a database comes in the advanced tutorial).
# file: app/main.py
"""BitByte Prompt Library: store prompt templates and fill them in."""
from itertools import count
from typing import Annotated
from fastapi import FastAPI, HTTPException, Path, status
from app.schemas import PromptCreate, PromptPublic, RenderRequest, RenderResponse
app = FastAPI(title="BitByte Prompt Library", version="0.1.0")
PROMPTS: dict[int, dict] = {} # id -> stored record (includes owner_email)
_next_id = count(1)
PromptId = Annotated[int, Path(ge=1, description="The prompt's id")]
def find_prompt(prompt_id: int) -> dict:
record = PROMPTS.get(prompt_id)
if record is None:
raise HTTPException(status_code=404, detail=f"Prompt {prompt_id} not found")
return record
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/prompts", status_code=status.HTTP_201_CREATED)
def create_prompt(prompt: PromptCreate) -> PromptPublic:
if any(p["name"] == prompt.name for p in PROMPTS.values()):
raise HTTPException(status_code=409, detail=f"A prompt named {prompt.name!r} already exists")
record = {"id": next(_next_id), **prompt.model_dump()}
PROMPTS[record["id"]] = record
return record
@app.get("/prompts")
def list_prompts(tag: str | None = None) -> list[PromptPublic]:
return [p for p in PROMPTS.values() if tag is None or tag in p["tags"]]
@app.get("/prompts/{prompt_id}")
def get_prompt(prompt_id: PromptId) -> PromptPublic:
return find_prompt(prompt_id)
@app.delete("/prompts/{prompt_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_prompt(prompt_id: PromptId) -> None:
find_prompt(prompt_id)
del PROMPTS[prompt_id]
@app.post("/prompts/{prompt_id}/render")
def render_prompt(prompt_id: PromptId, body: RenderRequest) -> RenderResponse:
record = find_prompt(prompt_id)
return RenderResponse(
prompt_id=prompt_id,
model=record["model"],
temperature=record["temperature"],
text=record["template"].replace("{question}", body.question),
)Three things are new here. The return type annotation (-> PromptPublic) tells FastAPI to validate and filter what the function returns. status_code= on the decorator sets the success status. And PromptId is a reusable alias for an annotated type, so the same rule is written once. Start the server; note the path is now app/main.py:
uv run fastapi run app/main.py --port 8000 > server.log 2>&1 &
curl -s --retry 20 --retry-connrefused --retry-delay 0 http://localhost:8000/health{"status":"ok"}Create: 201 and a filtered response
Create a prompt. -w prints the status code after the body:
curl -s -w "\nstatus: %{http_code}\n" -X POST http://localhost:8000/prompts \
-H "Content-Type: application/json" \
-d '{"name": "course-helper",
"template": "You are a friendly tutor. Answer briefly: {question}",
"tags": ["tutor", "short"],
"owner_email": "[email protected]"}'{"name":"course-helper","template":"You are a friendly tutor. Answer briefly: {question}","model":"bitbyte-mini","temperature":0.7,"tags":["tutor","short"],"id":1}
status: 201The status is 201 Created, as declared, and the response has an id but no owner_email, even though the stored record has one and the function returned that record. The return type PromptPublic does not have the field, so FastAPI dropped it. This is the safe way to build responses: list what may go out, rather than remembering what must not. (You may also see the older response_model=PromptPublic argument on the decorator; it does the same job.)
Add a second prompt, then list and fetch:
curl -s -X POST http://localhost:8000/prompts -H "Content-Type: application/json" \
-d '{"name": "bangla-summary", "template": "Summarise in simple Bangla: {question}",
"model": "bitbyte-pro", "temperature": 0.3, "tags": ["summary"], "owner_email": "[email protected]"}'
echo
curl -s "http://localhost:8000/prompts?tag=tutor"
echo
curl -s http://localhost:8000/prompts/2{"name":"bangla-summary","template":"Summarise in simple Bangla: {question}","model":"bitbyte-pro","temperature":0.3,"tags":["summary"],"id":2}
[{"name":"course-helper","template":"You are a friendly tutor. Answer briefly: {question}","model":"bitbyte-mini","temperature":0.7,"tags":["tutor","short"],"id":1}]
{"name":"bangla-summary","template":"Summarise in simple Bangla: {question}","model":"bitbyte-pro","temperature":0.3,"tags":["summary"],"id":2}Reading a validation error
Send the same bad data you tried in Python. This time pipe the response through python -m json.tool to make it readable:
curl -s -X POST http://localhost:8000/prompts -H "Content-Type: application/json" \
-d '{"name": "Course Helper!", "template": "Answer this.", "temperature": 3, "owner_email": "[email protected]"}' \
| python -m json.tool{
"detail": [
{
"type": "string_pattern_mismatch",
"loc": [
"body",
"name"
],
"msg": "String should match pattern '^[a-z0-9-]+$'",
"input": "Course Helper!",
"ctx": {
"pattern": "^[a-z0-9-]+$"
}
},
{
"type": "value_error",
"loc": [
"body",
"template"
],
"msg": "Value error, template must contain the {question} placeholder",
"input": "Answer this.",
"ctx": {
"error": {}
}
},
{
"type": "less_than_equal",
"loc": [
"body",
"temperature"
],
"msg": "Input should be less than or equal to 2",
"input": 3,
"ctx": {
"le": 2.0
}
}
]
}The status is 422 and the body has one entry per problem in detail. Each entry has the same keys:
| Key | Meaning | Use it to |
|---|---|---|
type | A stable, machine-readable error code | Branch in client code, translate messages |
loc | Where: body, query, path or header, then the field (and list index if any) | Highlight the right form field |
msg | A message for humans | Show the developer or user |
input | The value that was rejected | Debugging (careful: it echoes what the client sent) |
ctx | The rule's settings, e.g. {"le": 2.0} | Build your own message |
None of your endpoint code ran. Validation is the first wall: by the time create_prompt runs, prompt is guaranteed to be correct. Two more classic client mistakes:
curl -s -X POST http://localhost:8000/prompts -H "Content-Type: application/json" \
-d '{"name": "broken", "template": "Answer: {question}", "owner_email": "[email protected]",' \
| python -m json.tool
curl -s -X POST http://localhost:8000/prompts -H "Content-Type: application/json" \
-d '{"name": "too-many-tags", "template": "Answer: {question}", "owner_email": "[email protected]",
"tags": ["a", "b", "c", "d", "e", "f"]}' \
| python -m json.tool{
"detail": [
{
"type": "json_invalid",
"loc": [
"body",
84
],
"msg": "JSON decode error",
"input": {},
"ctx": {
"error": "Expecting property name enclosed in double quotes"
}
}
]
}
{
"detail": [
{
"type": "too_long",
"loc": [
"body",
"tags"
],
"msg": "List should have at most 5 items after validation, not 6",
"input": [
"a",
"b",
"c",
"d",
"e",
"f"
],
"ctx": {
"field_type": "List",
"max_length": 5,
"actual_length": 6
}
}
]
}Broken JSON is reported as json_invalid with the character position; a list that is too long reports its actual length. In both cases the client knows precisely what to fix.
Status codes and HTTPException
Validation covers "the data is malformed". Everything else, such as "it does not exist" or "it clashes with something", is your code's decision, made with HTTPException:
curl -s -w "\nstatus: %{http_code}\n" http://localhost:8000/prompts/99
curl -s -w "\nstatus: %{http_code}\n" -X POST http://localhost:8000/prompts -H "Content-Type: application/json" \
-d '{"name": "course-helper", "template": "Another: {question}", "owner_email": "[email protected]"}'
curl -s -w "status: %{http_code}\n" -X DELETE http://localhost:8000/prompts/2
curl -s -w "\nstatus: %{http_code}\n" -X DELETE http://localhost:8000/prompts/2{"detail":"Prompt 99 not found"}
status: 404
{"detail":"A prompt named 'course-helper' already exists"}
status: 409
status: 204
{"detail":"Prompt 2 not found"}
status: 404The first DELETE printed nothing before its status: 204 No Content means exactly that, no body. The second one is a 404, because the prompt is already gone. Here is the full set this API uses, and who decides each one:
| Status | When | Who sends it |
|---|---|---|
200 OK | Successful read or render | FastAPI's default for a normal return |
201 Created | A prompt was created | status_code=status.HTTP_201_CREATED on the decorator |
204 No Content | A prompt was deleted | status_code=status.HTTP_204_NO_CONTENT, return nothing |
404 Not Found | Unknown prompt id | raise HTTPException(status_code=404, ...) in find_prompt |
409 Conflict | The name is already taken | raise HTTPException(status_code=409, ...) |
422 Unprocessable Content | The request data breaks the schema | FastAPI and Pydantic, automatically |
status.HTTP_201_CREATED is just the number 201 with a readable name; both forms work. Raising inside a helper such as find_prompt works from anywhere in the call chain: the exception travels up and FastAPI turns it into the response, so every endpoint that needs a prompt gets the same 404 with one line.
Putting it together: rendering a prompt
The last endpoint does something useful for an LLM app: it fills a stored template with the user's question and returns what you would send to the model, along with the model settings. Its input and output are both models:
import requests
BASE = "http://localhost:8000"
r = requests.post(f"{BASE}/prompts/1/render", json={"question": "What is an API?"}, timeout=5)
print(r.status_code, r.json())
r = requests.post(f"{BASE}/prompts/1/render", json={"question": ""}, timeout=5)
print(r.status_code, r.json()["detail"][0]["msg"])200 {'prompt_id': 1, 'model': 'bitbyte-mini', 'temperature': 0.7, 'text': 'You are a friendly tutor. Answer briefly: What is an API?'}
422 String should have at least 1 characterIn a real LLM backend, the next line would send text to the provider with model and temperature. Because the question is validated (1 to 500 characters), an empty question or a 50-page paste never reaches the paid API.
Project structure basics
Here is what the project looks like now, and where things go as it grows:
bitbyte-prompts/
├── app/
│ ├── __init__.py makes "app" a package
│ ├── main.py the FastAPI app and its endpoints
│ └── schemas.py Pydantic models: what goes in and out
├── tests/ tests (next page)
├── .gitignore .venv, __pycache__, .env ...
├── .python-version
├── pyproject.toml dependencies (uv) - or requirements.txt (pip)
├── uv.lock
└── README.mdThe rule behind it: keep the HTTP layer (paths, status codes) separate from the data shapes (schemas), and later from the business logic (services) and data access (a database layer). Each file then has one reason to change, and tests can import the parts they need. The advanced tutorial splits main.py further with routers. Two practical notes: run the app with fastapi dev app/main.py (or fastapi run app/main.py), and always import with the package name, from app.schemas import ..., so the imports work the same in the server, in tests and in scripts.
Where this shows up in real AI work
- Model inputs: a prediction endpoint's Pydantic model lists every feature with its type and range, so a request with
age: -4or a missing column never reaches the model. - LLM request limits:
max_lengthon messages, a cap on the number of messages, and aLiterallist of allowed models keep cost and abuse under control. - Structured LLM output: the same Pydantic models validate JSON that an LLM returns; OpenAI's and Anthropic's SDKs, and many agent frameworks, accept Pydantic models to describe the output they want.
- Safe responses: separate "create" and "public" models keep internal fields (owners, costs, embeddings, keys) out of API responses.
Common mistakes
- Returning the stored record without a response model. Every field in it, including emails or internal notes, goes out. Fix: give every endpoint a return type (
-> PromptPublic) that lists only public fields. - Returning errors with status 200.
return {"error": "not found"}breaks clients and monitoring. Fix:raise HTTPException(status_code=404, detail=...). - Validating by hand inside the endpoint.
if len(body.name) < 3: ...duplicates whatFielddoes, is easy to forget, and does not appear in/docs. Fix: put rules in the model. - Using Pydantic v1 code from old tutorials.
.dict(),.json(),@validatorandclass Configare v1. Fix:model_dump(),model_dump_json(),@field_validatorandmodel_config. - A body on a 204. A 204 response must not have a body. Fix: with
status_code=204, return nothing (-> None).
Try it yourself
- Easy: Write a model
FeedbackInfor rating an AI answer:answer_id(an integer, at least 1),rating(1 to 5) and an optionalcommentof at most 280 characters (defaultNone). Create one valid object and one withrating=6, and print the error'stype. - Medium: Add
PUT /prompts/{prompt_id}, which replaces a prompt with a newPromptCreatebody, keeps the id, and returnsPromptPublic. It must answer 404 for an unknown id. (The answer adds it from a second file and runs on port 8001, as on the last page.) - Hard: Tags are messy: clients send
["Tutor", "tutor ", "short"]. Write a model with afield_validatorthat strips spaces, lowercases and removes duplicates while keeping the first order, so that list becomes["tutor", "short"]. Why is it better to clean tags in the model than in each endpoint?
Answers
from typing import Annotated
from pydantic import BaseModel, Field, ValidationError
class FeedbackIn(BaseModel):
answer_id: Annotated[int, Field(ge=1)]
rating: Annotated[int, Field(ge=1, le=5)]
comment: Annotated[str | None, Field(max_length=280)] = None
print(FeedbackIn(answer_id=7, rating=5, comment="Clear and correct"))
try:
FeedbackIn(answer_id=7, rating=6)
except ValidationError as exc:
print(exc.errors()[0]["type"])answer_id=7 rating=5 comment='Clear and correct'
less_than_equal# file: answers.py
from app.main import PROMPTS, PromptId, app, find_prompt
from app.schemas import PromptCreate, PromptPublic
@app.put("/prompts/{prompt_id}")
def replace_prompt(prompt_id: PromptId, prompt: PromptCreate) -> PromptPublic:
find_prompt(prompt_id)
PROMPTS[prompt_id] = {"id": prompt_id, **prompt.model_dump()}
return PROMPTS[prompt_id]uv run fastapi run answers.py --port 8001 > answers.log 2>&1 &
curl -s --retry 20 --retry-connrefused --retry-delay 0 http://localhost:8001/health > /dev/null
curl -s -X POST http://localhost:8001/prompts -H "Content-Type: application/json" \
-d '{"name": "explain", "template": "Explain simply: {question}", "owner_email": "[email protected]"}'
echo
curl -s -X PUT http://localhost:8001/prompts/1 -H "Content-Type: application/json" \
-d '{"name": "explain", "template": "Explain like I am new to AI: {question}", "temperature": 0.4, "owner_email": "[email protected]"}'
echo
curl -s -X PUT http://localhost:8001/prompts/5 -H "Content-Type: application/json" \
-d '{"name": "ghost", "template": "Nobody: {question}", "owner_email": "[email protected]"}'{"name":"explain","template":"Explain simply: {question}","model":"bitbyte-mini","temperature":0.7,"tags":[],"id":1}
{"name":"explain","template":"Explain like I am new to AI: {question}","model":"bitbyte-mini","temperature":0.4,"tags":[],"id":1}
{"detail":"Prompt 5 not found"}The server on port 8001 is a separate process, so it has its own empty PROMPTS: the new prompt got id 1 there. A full answer would also return 409 if the new name belongs to a different prompt.
from pydantic import field_validator
class TaggedPrompt(BaseModel):
tags: Annotated[list[str], Field(max_length=5)] = []
@field_validator("tags")
@classmethod
def clean_tags(cls, tags: list[str]) -> list[str]:
cleaned = [t.strip().lower() for t in tags if t.strip()]
return list(dict.fromkeys(cleaned)) # remove duplicates, keep order
print(TaggedPrompt(tags=["Tutor", "tutor ", "short", " "]).tags)['tutor', 'short']
Cleaning in the model happens once, for every endpoint and every client, before your code sees the data; filtering by tag and checking for duplicates then simply work. Note the order: the max_length=5 constraint is checked on the list before this validator runs (it is an "after" validator), so six messy tags are still rejected even if they would clean down to five.
Summary
- A Pydantic model is a class with typed fields; creating it validates and converts the data, and
model_dump()/model_dump_json()turn it back into a dict or JSON. - Put rules in the model:
Fieldfor lengths, ranges and patterns,Literalfor fixed choices, special types likeEmailStr, and@field_validatorfor your own checks. - A 422 lists every problem with
type,loc,msgandinput; your endpoint never runs with invalid data. - Return types filter responses: use separate input and public models so internal fields never leak.
- Choose status codes deliberately:
status_code=201for create,204with no body for delete, andHTTPExceptionfor 404 and 409. Keep schemas and endpoints in separate files inside anapppackage.
Next: Testing Your API with pytest. Instead of checking every endpoint by hand with curl, you will write tests that check them all in a second, every time you change the code.

