07 · Pydantic at the HTTP Boundary
The previous lesson introduced dependencies:
Browser→ session middleware→ router→ authentication dependency→ authorization dependency→ route→ responseToday we add Pydantic validation to a POST request:
Browser sends untrusted JSON→ middleware reconstructs the session→ router selects the endpoint→ dependencies authenticate the user→ Pydantic validates the request body→ route receives structurally validated Python objects→ response returns to the browserThe important phrase is “validates the request body.”
The browser does not send a DocumentCreate object. It sends bytes containing JSON. FastAPI and Pydantic collaborate to turn those bytes into a useful Python object.
Today’s scenario
Section titled “Today’s scenario”An authenticated user creates a new document for review.
CurrentUserDep is the dictionary-backed alias established at the end of lesson 6. The user must have a firm membership for this creation example. As we first follow a write request, we are isolating its data boundary; CSRF protection for cookie-authenticated writes is added explicitly in lesson 14.
The browser sends:
{ "title": " September Website Review ", "document_type": "website", "priority": 4}Our application requires:
- A title between 3 and 200 characters
- One recognized document type
- A priority between 1 and 5
- No unexpected fields
After validation, the route receives:
DocumentCreate( title="September Website Review", document_type="website", priority=4,)Notice that the whitespace around the title has been removed.
The schema module
Section titled “The schema module”We’ll add a schema module:
app/├── main.py├── data.py├── dependencies.py├── security.py├── schemas/│ ├── __init__.py│ └── documents.py└── routers/ └── documents.pyHere is app/schemas/documents.py:
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
DocumentType = Literal[ "advertisement", "website", "email",]
class DocumentCreate(BaseModel): model_config = ConfigDict( extra="forbid", str_strip_whitespace=True, )
title: str = Field( min_length=3, max_length=200, )
document_type: DocumentType
priority: int = Field( default=3, ge=1, le=5, )
class DocumentRead(BaseModel): id: int firm_id: int title: str document_type: DocumentType priority: intThese are Pydantic models.
They describe data moving across application boundaries:
DocumentCreate└── Data allowed to enter the application
DocumentRead└── Data allowed to leave the applicationThey are not database tables. We will later create SQLAlchemy models for that responsibility.
BaseModel
Section titled “BaseModel”The declaration begins:
class DocumentCreate(BaseModel):DocumentCreate is a Python class that inherits from Pydantic’s BaseModel.
Inheritance gives the class Pydantic’s validation machinery.
Without BaseModel, this would be an ordinary Python class:
class DocumentCreate: ...Python would retain the type annotations, but Python itself would not automatically validate incoming values.
By inheriting from BaseModel, we can construct an object like this:
document = DocumentCreate( title="September Website Review", document_type="website", priority=4,)Pydantic checks the values before allowing the object to exist successfully.
FastAPI recognizes Pydantic models in route signatures and uses them to read and validate JSON request bodies. FastAPI request-body documentation
The model configuration
Section titled “The model configuration”Inside the model, we declare:
model_config = ConfigDict( extra="forbid", str_strip_whitespace=True,)This is configuration for the entire model.
Rejecting unexpected fields
Section titled “Rejecting unexpected fields”The first setting is:
extra="forbid"Suppose a browser sends:
{ "title": "September Website Review", "document_type": "website", "priority": 4, "approved": true}Our model does not define:
approvedWithout a strict extra-field policy, unexpected values may be ignored, depending on the model configuration.
With:
extra="forbid"Pydantic rejects the request.
This matters because clients should not be able to invent sensitive fields such as:
{ "approved": true, "firm_id": 999, "created_by_admin": true}Rejecting unknown fields also catches harmless mistakes:
{ "document_typ": "website"}The misspelled field produces an error instead of silently disappearing.
Stripping whitespace
Section titled “Stripping whitespace”The second setting is:
str_strip_whitespace=TruePydantic removes leading and trailing whitespace from string fields.
The browser sends:
" September Website Review "The validated model contains:
"September Website Review"This normalization happens at the boundary, so later application layers do not each need to remember to call:
title.strip()The document type
Section titled “The document type”We define:
DocumentType = Literal[ "advertisement", "website", "email",]Literal means the value must literally be one of those strings.
These are valid:
"advertisement""website""email"These are invalid:
"Website""web""pdf""social post"This is more precise than:
document_type: strAn ordinary str would accept almost any text.
The alias also avoids repeating the list in multiple models:
document_type: DocumentTypeBoth DocumentCreate and DocumentRead now use the same permitted vocabulary.
For a small, stable set of values, Literal is perfectly reasonable. A larger application might eventually use a Python Enum or a database-backed document-type table.
Field constraints
Section titled “Field constraints”The title is declared as:
title: str = Field( min_length=3, max_length=200,)The base type is:
strThe Field call adds constraints.
After whitespace is removed, the title must contain at least three characters and no more than 200.
These values fail:
"""A""AB"A normal title succeeds:
"September Website Review"The priority field uses numeric constraints:
priority: int = Field( default=3, ge=1, le=5,)Here:
ge = greater than or equal tole = less than or equal toThe allowed range is therefore:
1 ≤ priority ≤ 5These values are valid:
135These are invalid:
06100The field also has:
default=3That means the browser may omit it:
{ "title": "September Website Review", "document_type": "website"}The resulting model will contain:
priority == 3A default value makes the field optional in the request while still guaranteeing that the resulting Python object has a value.
Required, optional, and nullable
Section titled “Required, optional, and nullable”Compare these declarations:
title: strpriority: int = 3notes: str | None = NoneThey express three different ideas.
title: strThe field is required and must be a string.
priority: int = 3The field may be omitted. If omitted, its value becomes 3.
notes: str | None = NoneThe field may be omitted, and its value may explicitly be None.
“Optional” and “nullable” are related but not identical:
Optional→ The client may omit the field.
Nullable→ The field may contain null/None.Our current document schema does not need nullable fields, but the distinction becomes important in update models.
The route
Section titled “The route”Here is the new route in app/routers/documents.py:
from fastapi import APIRouter, status
from ..data import documents_by_idfrom ..dependencies import CurrentUserDepfrom ..schemas.documents import ( DocumentCreate, DocumentRead,)
router = APIRouter( prefix="/documents", tags=["documents"],)
@router.post( "/", response_model=DocumentRead, status_code=status.HTTP_201_CREATED,)async def create_document( payload: DocumentCreate, current_user: CurrentUserDep,): document_id = max( documents_by_id, default=100, ) + 1
document = { "id": document_id, "firm_id": current_user["firm_id"], "title": payload.title, "document_type": payload.document_type, "priority": payload.priority, }
documents_by_id[document_id] = document
return documentThe route has two important inputs:
payload: DocumentCreatecurrent_user: CurrentUserDepFastAPI obtains them differently.
payload└── Comes from the JSON request body
current_user└── Comes from dependency resolutionThe route does not manually parse either one.
What the browser sends
Section titled “What the browser sends”Imagine a small amount of browser JavaScript submitting the document:
const response = await fetch("/documents/", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: " September Website Review ", document_type: "website", priority: 4 })});
const document = await response.json();JSON.stringify() converts the JavaScript object into JSON text.
The HTTP request resembles:
POST /documents/ HTTP/1.1Host: 127.0.0.1:8000Content-Type: application/jsonCookie: app_session=...
{ "title": " September Website Review ", "document_type": "website", "priority": 4}Because this is a same-origin browser request, the browser normally includes the relevant session cookie automatically.
The request body is not yet a Python dictionary or Pydantic model. Across the network, it is encoded data.
How FastAPI recognizes the request body
Section titled “How FastAPI recognizes the request body”The route declares:
payload: DocumentCreateFastAPI examines the type.
DocumentCreate is a Pydantic model, so FastAPI concludes:
This parameter should come from the HTTP request body.
This differs from a simple parameter:
limit: intUnless otherwise marked, a simple value not appearing in the path would generally be interpreted as a query parameter.
FastAPI uses the parameter’s declaration to determine its source:
document_id: intwith /{document_id}→ URL path
limit: int→ Query string
payload: DocumentCreate→ JSON request body
current_user: CurrentUserDep→ DependencyThis is one reason route signatures are so important in FastAPI. They describe how the framework should construct the route’s arguments.
From bytes to a Pydantic object
Section titled “From bytes to a Pydantic object”When the request arrives, several transformations occur.
First, the server receives raw HTTP data.
FastAPI’s underlying request machinery sees:
Content-Type: application/jsonIt parses the JSON body into ordinary data conceptually resembling:
{ "title": " September Website Review ", "document_type": "website", "priority": 4,}Pydantic then validates that data against DocumentCreate.
It checks:
Is title a string?Strip its outer whitespace.Is the cleaned title 3–200 characters?
Is document_type an allowed literal?
Is priority an integer?Is it between 1 and 5?
Are there any unexpected fields?If everything succeeds, Pydantic creates:
DocumentCreate( title="September Website Review", document_type="website", priority=4,)FastAPI then supplies that object to the route:
await create_document( payload=validated_document_create, current_user=authenticated_user,)The actual orchestration is performed by the framework, but this conceptual call shows the resulting values.
The route receives attributes, not raw dictionary keys
Section titled “The route receives attributes, not raw dictionary keys”Inside the route, we use:
payload.titlepayload.document_typepayload.priorityThese are object attributes.
If we had accepted a raw dictionary, we would write:
payload["title"]payload["document_type"]payload["priority"]The Pydantic model gives us several advantages:
- The fields are known in advance.
- Invalid requests have already been rejected.
- Editors can autocomplete the attributes.
- Type-checking tools understand the values.
- Constraints are centralized in one schema.
- OpenAPI documentation is generated automatically.
The route does not need defensive code such as:
if "title" not in payload: ...
if not isinstance(payload["priority"], int): ...
if payload["priority"] > 5: ...That boundary validation has already happened.
Invalid data never reaches the route body
Section titled “Invalid data never reaches the route body”Suppose the browser sends:
{ "title": "A", "document_type": "pdf", "priority": 9}Three rules fail:
title is too shortdocument_type is not permittedpriority is greater than 5FastAPI returns a validation response resembling:
HTTP/1.1 422 Unprocessable ContentContent-Type: application/jsonThe body contains structured details identifying the failed fields.
Most importantly:
create_document() never runsNo document ID is generated.
Nothing is inserted into documents_by_id.
No success response is created.
FastAPI documents this automatic sequence: read the JSON body, convert compatible values, validate the data, and return detailed errors when validation fails. FastAPI request-body validation
Validation may include conversion
Section titled “Validation may include conversion”Pydantic does not always require the incoming representation to match the final Python type exactly.
For example, depending on the model’s strictness settings:
{ "priority": "4"}may be converted from the string "4" into the integer 4.
This is called coercion.
It can be convenient because HTTP input often arrives as text. But it is important to understand what “validated” means:
Pydantic may accept a compatible valueand convert it into the declared type.If an application requires exact types, Pydantic can be configured for strict validation.
For an ordinary browser-facing application, selective coercion is often practical. For security-sensitive or unusually precise fields, strict validation can be appropriate.
The decision should be deliberate rather than assumed.
Validation does not mean authorization
Section titled “Validation does not mean authorization”Pydantic confirms that:
priority is between 1 and 5document_type is recognizedtitle has an acceptable shapeIt does not decide:
May this user create documents?May this user create a document for this firm?Has this firm reached its document limit?Those are authorization or business-rule questions.
Notice that the request schema does not accept:
firm_idThe server obtains the firm from:
current_user["firm_id"]That is deliberate.
An insecure route might accept:
{ "firm_id": 20, "title": "Other Firm Document"}A user from firm 10 could try to create data under firm 20.
Our route instead constructs:
"firm_id": current_user["firm_id"]The authoritative firm comes from the authenticated user, not from untrusted browser input.
Pydantic validates the shape of submitted data. The application still decides which submitted facts it is willing to trust.
Creating the temporary record
Section titled “Creating the temporary record”After validation and authentication succeed, the route generates an ID:
document_id = max( documents_by_id, default=100,) + 1If the existing IDs are:
101202then:
max(documents_by_id)returns:
202The new ID becomes:
203The route then creates a dictionary:
document = { "id": document_id, "firm_id": current_user["firm_id"], "title": payload.title, "document_type": payload.document_type, "priority": payload.priority,}Finally:
documents_by_id[document_id] = documentstores it in memory.
This is only our temporary database stand-in. It is not concurrency-safe or durable. Restarting the application would lose the newly created record.
Later, this exact position in the lifecycle will contain a service call:
document = document_service.create_document( db=db, user=current_user, data=payload,)The service will use SQLAlchemy to write the record to SQLite.
Validating the response
Section titled “Validating the response”The route decorator includes:
response_model=DocumentReadInput validation uses:
payload: DocumentCreateOutput validation and serialization use:
response_model=DocumentReadThe route returns an ordinary dictionary:
return documentBefore sending it to the browser, FastAPI validates and serializes it according to:
class DocumentRead(BaseModel): id: int firm_id: int title: str document_type: DocumentType priority: intThis establishes an outgoing contract.
If the internal dictionary accidentally contained:
{ "id": 203, "firm_id": 10, "title": "September Website Review", "document_type": "website", "priority": 4, "internal_storage_path": "/private/uploads/203.pdf", "reviewer_notes": "Internal notes",}the declared response model limits the public response to its defined fields.
The browser receives:
{ "id": 203, "firm_id": 10, "title": "September Website Review", "document_type": "website", "priority": 4}This is why separate input and output schemas are useful.
The application does not automatically expose every internal field it happens to store.
Pydantic model versus SQLAlchemy model
Section titled “Pydantic model versus SQLAlchemy model”This distinction will become increasingly important:
Pydantic model└── Validates and serializes application data
SQLAlchemy model└── Maps Python objects to database tablesEventually we may have:
class DocumentCreate(BaseModel): ...and:
class Document(Base): ...They represent related information, but they serve different systems.
DocumentCreate answers:
What may the browser submit when creating a document?
The SQLAlchemy Document model will answer:
How is a document stored in the database?
The database model may contain fields the browser is never allowed to submit:
idfirm_idcreated_by_user_idcreated_atstorage_pathprocessing_statusKeeping these responsibilities separate prevents the external HTTP contract from becoming identical to the internal database structure.
The complete execution trace
Section titled “The complete execution trace”For a successful request:
POST /documents/Cookie: app_session=...Content-Type: application/jsonthe lifecycle is:
- The browser converts a JavaScript object into JSON.
- The browser sends the JSON body and session cookie.
- The server receives the HTTP request.
SessionMiddlewareverifies the cookie.- The middleware reconstructs
request.session. - The router matches
POST /documents/. - FastAPI inspects the endpoint’s required inputs.
- FastAPI parses the JSON bytes and resolves the authentication dependency as part of preparing the request.
- Pydantic receives the parsed request-body data.
- Pydantic strips string whitespace.
- Pydantic rejects unknown fields.
- Pydantic validates the title, document type, and priority.
- Pydantic constructs a
DocumentCreateobject. - FastAPI calls the route with the authenticated user and validated payload.
- Python constructs and stores the temporary document dictionary.
- The route returns that dictionary.
- FastAPI validates and filters it through
DocumentRead. - FastAPI serializes the result as JSON.
- The response passes outward through middleware.
- The server sends
201 Created. - The browser parses the JSON response.
The database still performs no work today. Our dictionary occupies its future architectural position.
The central idea
Section titled “The central idea”Pydantic creates a boundary between untrusted external data and application code.
Before the boundary:
JSON supplied by a browserPossibly missing, malformed, unexpected, or misleadingAfter the boundary:
A known Python objectWith declared fields, normalized strings, and validated constraintsThat does not make the data authorized or make every business decision correct. It means the application no longer has to wonder whether priority is missing, whether document_type contains an invented value, or whether the title is an empty string.
The next architectural step is the service layer. We’ll remove document creation from the route and give the route one focused job: translate HTTP input into a service call, then translate the service result into an HTTP response.