Skip to content

07 · Pydantic at the HTTP Boundary

The previous lesson introduced dependencies:

Browser
→ session middleware
→ router
→ authentication dependency
→ authorization dependency
→ route
→ response

Today 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 browser

The 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.


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.


We’ll add a schema module:

app/
├── main.py
├── data.py
├── dependencies.py
├── security.py
├── schemas/
│ ├── __init__.py
│ └── documents.py
└── routers/
└── documents.py

Here 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: int

These are Pydantic models.

They describe data moving across application boundaries:

DocumentCreate
└── Data allowed to enter the application
DocumentRead
└── Data allowed to leave the application

They are not database tables. We will later create SQLAlchemy models for that responsibility.


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


Inside the model, we declare:

model_config = ConfigDict(
extra="forbid",
str_strip_whitespace=True,
)

This is configuration for the entire model.

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:

approved

Without 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.

The second setting is:

str_strip_whitespace=True

Pydantic 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()

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: str

An ordinary str would accept almost any text.

The alias also avoids repeating the list in multiple models:

document_type: DocumentType

Both 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.


The title is declared as:

title: str = Field(
min_length=3,
max_length=200,
)

The base type is:

str

The 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 to
le = less than or equal to

The allowed range is therefore:

1 ≤ priority ≤ 5

These values are valid:

1
3
5

These are invalid:

0
6
100

The field also has:

default=3

That means the browser may omit it:

{
"title": "September Website Review",
"document_type": "website"
}

The resulting model will contain:

priority == 3

A default value makes the field optional in the request while still guaranteeing that the resulting Python object has a value.


Compare these declarations:

title: str
priority: int = 3
notes: str | None = None

They express three different ideas.

title: str

The field is required and must be a string.

priority: int = 3

The field may be omitted. If omitted, its value becomes 3.

notes: str | None = None

The 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.


Here is the new route in app/routers/documents.py:

from fastapi import APIRouter, status
from ..data import documents_by_id
from ..dependencies import CurrentUserDep
from ..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 document

The route has two important inputs:

payload: DocumentCreate
current_user: CurrentUserDep

FastAPI obtains them differently.

payload
└── Comes from the JSON request body
current_user
└── Comes from dependency resolution

The route does not manually parse either one.


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.1
Host: 127.0.0.1:8000
Content-Type: application/json
Cookie: 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.


The route declares:

payload: DocumentCreate

FastAPI 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: int

Unless 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: int
with /{document_id}
→ URL path
limit: int
→ Query string
payload: DocumentCreate
→ JSON request body
current_user: CurrentUserDep
→ Dependency

This is one reason route signatures are so important in FastAPI. They describe how the framework should construct the route’s arguments.


When the request arrives, several transformations occur.

First, the server receives raw HTTP data.

FastAPI’s underlying request machinery sees:

Content-Type: application/json

It 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.title
payload.document_type
payload.priority

These 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.


Suppose the browser sends:

{
"title": "A",
"document_type": "pdf",
"priority": 9
}

Three rules fail:

title is too short
document_type is not permitted
priority is greater than 5

FastAPI returns a validation response resembling:

HTTP/1.1 422 Unprocessable Content
Content-Type: application/json

The body contains structured details identifying the failed fields.

Most importantly:

create_document() never runs

No 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


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 value
and 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.


Pydantic confirms that:

priority is between 1 and 5
document_type is recognized
title has an acceptable shape

It 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_id

The 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.


After validation and authentication succeed, the route generates an ID:

document_id = max(
documents_by_id,
default=100,
) + 1

If the existing IDs are:

101
202

then:

max(documents_by_id)

returns:

202

The new ID becomes:

203

The 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] = document

stores 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.


The route decorator includes:

response_model=DocumentRead

Input validation uses:

payload: DocumentCreate

Output validation and serialization use:

response_model=DocumentRead

The route returns an ordinary dictionary:

return document

Before 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: int

This 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.


This distinction will become increasingly important:

Pydantic model
└── Validates and serializes application data
SQLAlchemy model
└── Maps Python objects to database tables

Eventually 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:

id
firm_id
created_by_user_id
created_at
storage_path
processing_status

Keeping these responsibilities separate prevents the external HTTP contract from becoming identical to the internal database structure.


For a successful request:

POST /documents/
Cookie: app_session=...
Content-Type: application/json

the lifecycle is:

  1. The browser converts a JavaScript object into JSON.
  2. The browser sends the JSON body and session cookie.
  3. The server receives the HTTP request.
  4. SessionMiddleware verifies the cookie.
  5. The middleware reconstructs request.session.
  6. The router matches POST /documents/.
  7. FastAPI inspects the endpoint’s required inputs.
  8. FastAPI parses the JSON bytes and resolves the authentication dependency as part of preparing the request.
  9. Pydantic receives the parsed request-body data.
  10. Pydantic strips string whitespace.
  11. Pydantic rejects unknown fields.
  12. Pydantic validates the title, document type, and priority.
  13. Pydantic constructs a DocumentCreate object.
  14. FastAPI calls the route with the authenticated user and validated payload.
  15. Python constructs and stores the temporary document dictionary.
  16. The route returns that dictionary.
  17. FastAPI validates and filters it through DocumentRead.
  18. FastAPI serializes the result as JSON.
  19. The response passes outward through middleware.
  20. The server sends 201 Created.
  21. The browser parses the JSON response.

The database still performs no work today. Our dictionary occupies its future architectural position.


Pydantic creates a boundary between untrusted external data and application code.

Before the boundary:

JSON supplied by a browser
Possibly missing, malformed, unexpected, or misleading

After the boundary:

A known Python object
With declared fields, normalized strings, and validated constraints

That 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.