Skip to content
Visual explainer 3h to learn 5 steps

Pydantic request and response models in FastAPI

Define validated request and response models with filtering and pagination that keep the API stable.

By Invicly Tech, , in FastAPI with Python for AI Backends. About 12 minutes to read.

Topic 4 of 29

In short

A contract is the promise your API makes about what it accepts and what it returns. In FastAPI you write that promise as typed path, query and body parameters plus Pydantic request and response models, and FastAPI validates input, filters output and publishes it all in OpenAPI. Stable models and predictable pagination let clients build on your API without breaking when you change internals.

Think of it like this: A response model is like a shop window: whatever is in the stockroom, customers only ever see what you chose to put on display.

Explained simply

An API contract is a promise. It says: send me data in this shape and I will answer in that shape. Mobile apps, web pages and other services are written against that promise, so it needs to be clear and it must not change by surprise.

FastAPI lets you write the promise in Python. You describe the data with Pydantic models, which are classes with typed fields like text: str or top_k: int. FastAPI reads the request, checks it against the model and gives your function clean Python objects. Bad input gets an automatic 422 error that names the field.

Input arrives in three places. The path names one thing, like the 42 in /documents/42. The query string adds options, like ?status=ready&limit=20. The body carries the main data, usually JSON, for creating or changing something.

Output deserves the same care. A response model lists exactly which fields the client gets. Even if your database row holds a tenant ID or a secret, only the declared fields are sent. For long lists you return one page at a time, never everything at once.

Press Play on a diagram to walk through it one step at a time.

FlowData through a typed route
  1. 1
    Raw request

    Path, query string and JSON body as text

  2. 2
    Input models

    Pydantic parses types and checks constraints

  3. 3
    Handler

    Works with clean Python objects

  4. 4
    Internal data

    ORM rows or dicts with extra fields

  5. 5
    Response model

    Keeps only declared fields, in a fixed shape

  6. 6
    JSON out

    The same schema clients see in OpenAPI

CompareOffset versus cursor pagination
Offset (limit and offset)
  • Easy to build and to jump to page N
  • Slower on deep pages
  • Duplicates or gaps when data changes
  • Fine for small admin lists
Cursor (keyset)
  • Opaque next_cursor from the last row
  • Uses an index, fast at any depth
  • Stable while rows are added
  • Best for feeds, jobs and documents
MapOne resource, a family of models
Document
  • DocumentCreate (input)
    • title
    • source_url
  • DocumentOut (output)
    • id
    • title
    • status
    • created_at
  • Database row (internal)
    • tenant_id
    • storage_key
    • checksum
    • plus every output field
  • DocumentPage (list)
    • items: list of DocumentOut
    • next_cursor

In depth

Path, query and body: how FastAPI decides

FastAPI sorts parameters by simple rules. A name that appears in the route path, such as {document_id}, is a path parameter. A plain type like str, int or bool that is not in the path becomes a query parameter. A Pydantic model becomes the JSON body. You can be explicit with Annotated and the Path, Query, Header and Body helpers, which also take constraints and descriptions for the docs.

Path parameters should identify a resource and are always required. Query parameters are for optional filters, sorting and paging, and should have sensible defaults. The body is for the data being created or changed. Avoid GET requests with bodies; many proxies and clients drop them. Recent FastAPI versions can also group related query parameters into one Pydantic model, which keeps long filter lists tidy.

  • In the path: identifies one resource
  • Simple type not in the path: query parameter
  • Pydantic model: JSON body
  • Annotated[int, Query(ge=1, le=100)] adds rules and docs

Validating fields with Pydantic v2

Most rules fit in Field: min_length and max_length for strings and lists, ge, gt, le and lt for numbers, pattern for regular expressions. Literal["asc", "desc"] or an Enum restricts a value to a fixed set. When a rule needs code, add a method decorated with @field_validator("name") and @classmethod; it receives the value and returns the cleaned value or raises ValueError. Rules that compare two fields, such as end date after start date, belong in a @model_validator(mode="after").

Model behaviour is set with model_config = ConfigDict(...). str_strip_whitespace=True trims strings; extra="forbid" rejects unknown fields, which catches client typos but means old servers reject new client fields, so use it deliberately. Every failure becomes part of one 422 response listing each bad field with its location, so clients can show precise messages.

CompareThree places to put a validation rule
Field constraints
  • max_length=2000, ge=1, le=20
  • No code to write
  • Shown in OpenAPI
  • First choice for simple limits
field_validator
  • Python code for one field
  • Normalise or check format
  • Raise ValueError to reject
  • Runs after type parsing by default
model_validator
  • Sees the whole model
  • Rules across fields
  • mode="after" gets the built model
  • Use for start before end checks

Filtering output with response models

Give each resource a small family of models. DocumentCreate holds what clients may send. DocumentOut holds what clients may see. Internal data, such as an ORM row with tenant_id, storage_key and checksum, stays out of both. Declare the output with a return type annotation or response_model, and FastAPI validates the return value against it and drops undeclared fields.

To build an output model from an ORM object, set model_config = ConfigDict(from_attributes=True) and call DocumentOut.model_validate(row), or simply return the row and let FastAPI do it. response_model_exclude_unset=True leaves out fields that were never set, which suits partial updates. Keep one output model per resource where you can, so a document looks the same in a list, in a detail view and inside other responses.

  • Create model: what clients send
  • Out model: what clients see
  • Internal fields live only in the database layer
  • from_attributes=True reads ORM objects

Paginating list endpoints

Any list that can grow must be paged, with a default page size and a hard maximum, for example limit defaulting to 20 with le=100. Offset pagination, ?limit=20&offset=40, is simple and lets users jump to page 3, but the database still walks past skipped rows, and items shift when rows are inserted, so users see duplicates or gaps.

Cursor pagination, also called keyset pagination, returns an opaque next_cursor that encodes the last row seen, such as its created_at and id. The next query asks for rows after that point using an index, so it stays fast on deep pages and stable while data changes. Always sort by a unique key, adding id as a tie-breaker. Wrap results in an envelope like {items: [...], next_cursor: "..."} so you can add fields later without breaking clients.

Keeping response schemas stable

Once clients depend on a field, treat it as permanent. Safe changes are additive: a new optional response field, a new optional query parameter, a new endpoint. Breaking changes include renaming or removing a field, changing its type, making an optional input required, narrowing allowed values, or changing a status code.

When you must break something, add a new version, for example /v2/questions, run both for a while, and mark the old route deprecated=True so OpenAPI shows it. A cheap safety net is a contract test: export /openapi.json in CI and compare it with a committed copy, so any change to the schema shows up in review. Clients should be tolerant readers too, ignoring fields they do not know.

  • Additive changes are safe
  • Rename, remove or retype is breaking
  • Version the path for breaking changes
  • Snapshot openapi.json in CI

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Use path, query and body parameters~35m
  2. 2
    Validate fields with constraints~35m
  3. 3
    Filter output with response models~35m
  4. 4
    Paginate list endpoints~35m
  5. 5
    Keep response schemas stable~35m

Key points

  • Path parameters identify a resource, query parameters filter or page it, and the body carries the data to create or change.
  • Field constraints such as min_length, max_length, ge and le turn business rules into automatic 422 errors.
  • Use separate models for create input and for output so internal fields never leak.
  • List endpoints should always be paginated with a hard maximum page size.
  • Adding optional fields is safe; renaming, removing or retyping fields breaks clients.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
from typing import Annotated
from fastapi import FastAPI, Query
from pydantic import BaseModel, Field

app = FastAPI()
class QuestionIn(BaseModel):
    text: str = Field(min_length=3, max_length=2000)
    top_k: int = Field(default=5, ge=1, le=20)

class AnswerOut(BaseModel):
    question_id: str
    answer: str

@app.post("/v1/collections/{collection_id}/questions", status_code=201)
def ask(collection_id: str, body: QuestionIn, lang: Annotated[str, Query(max_length=8)] = "en") -> AnswerOut: ...

collection_id comes from the path, lang from the query string, body from JSON.

Internal fields never leave the server

The handler returns a dict that, like a real database row, holds tenant_id and storage_key. Because the return type is DocumentOut, FastAPI keeps only id, title and status. Call GET /v1/documents/doc_1 and the JSON has exactly those three fields. Add a field to the dict later and it still will not leak; add it to DocumentOut and it appears on purpose.

python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class DocumentOut(BaseModel):
    id: str
    title: str
    status: str

@app.get("/v1/documents/{document_id}")
def get_document(document_id: str) -> DocumentOut:
    row = {"id": document_id, "title": "Refund policy", "status": "ready",
           "tenant_id": "contoso", "storage_key": "s3://bucket/contoso/doc_1"}
    return DocumentOut.model_validate(row)

A cursor-paginated list

The client asks for a page with limit and an optional cursor. The server returns items plus next_cursor, which is null on the last page. Here the cursor is simply the last ID, with rows sorted by ID. DOCS is an in-memory list of dicts and DocumentOut comes from the previous example. In production you would encode created_at and id and query an indexed column. limit is capped at 100 by the Query constraint, so limit=5000 gets a 422.

python
from typing import Annotated
from fastapi import Query
from pydantic import BaseModel

class DocumentPage(BaseModel):
    items: list[DocumentOut]
    next_cursor: str | None

@app.get("/v1/documents")
def list_documents(limit: Annotated[int, Query(ge=1, le=100)] = 20,
                   cursor: str | None = None) -> DocumentPage:
    rows = [r for r in sorted(DOCS, key=lambda r: r["id"]) if cursor is None or r["id"] > cursor]
    page = rows[:limit]
    nxt = page[-1]["id"] if len(rows) > limit else None
    return DocumentPage(items=page, next_cursor=nxt)

Quick reference

  • Path identifies, query filters and pages, body carries the data.
  • Field(min_length=3, max_length=2000), Field(ge=1, le=20) for simple rules.
  • @field_validator for one field, @model_validator(mode="after") for cross-field rules.
  • Return type or response_model filters out undeclared fields.
  • ConfigDict(from_attributes=True) + Model.model_validate(orm_row) builds output from ORM objects.
  • Cap page size: Annotated[int, Query(ge=1, le=100)] = 20.
  • Prefer cursor pagination for growing lists; sort by a unique key.
  • Additive changes are safe; rename, remove or retype needs a new version.

Common mistakes

  • Returning ORM objects with no response model, which can leak fields like owner IDs or hashes.
  • Letting clients ask for limit=100000 because the page size has no upper bound.
  • Reusing one model for input and output, so a field added for output becomes writable by clients.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1In GET /v1/documents/{document_id}?status=ready, where does status come from?

Question 2

2Which change to a response model is normally safe for existing clients?

Question 3

3Your rule is that end_date must be after start_date. Where should it go?

Question 4

4Why is cursor pagination better than offset for a fast-growing job list?

Question 5

5A handler returns an ORM object that has a password_hash attribute. How do you make sure it is never sent?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a QuestionIn model: text is 3 to 2000 characters, top_k is an integer from 1 to 20 with default 5, and language is either en or de with default en.

  2. Exercise 2medium

    Add a field_validator to QuestionIn that trims the text and rejects it if it is only whitespace. Then send {"text": " "} and check the 422 response names the text field.

  3. Exercise 3hard

    Write a CI check that fails when the API schema changes without review: export app.openapi() to JSON and compare it with a committed tests/openapi.snapshot.json.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Why does FastAPI return 422 and not 400 for bad input?
422 means the request was readable but its content failed validation. You can switch to 400 with a custom RequestValidationError handler, but keep one choice across the whole API.
Should I use the same Pydantic model for input and output?
Usually not. Separate models stop clients from setting server-owned fields like id or status and stop internal fields from leaking out.
Should my API reject unknown fields?
extra="forbid" catches typos, but it also rejects newer clients that send fields an older server does not know. Many public APIs ignore unknown input fields and forbid only on sensitive endpoints.
Is offset pagination ever fine?
Yes, for small lists that rarely change, such as an admin table of a few hundred rows. For feeds, logs, jobs and documents, prefer cursors.

Go deeper

ShareXLinkedInWhatsApp