Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 25 min · revision 3

Validating Input and Shaping Output with Pydantic

Give the reading list separate create, update and read schemas, constraints and validators that normalise input, and a response model that keeps an internal field out of every response.

Contentsand lesson path

What you will learn

  • Define Pydantic v2 models with field constraints and custom validators, using separate create, update and read schemas so invalid input gets a 422 and internal fields never appear in responses.

Prerequisites: HTTP & APIs

01. The problem: one shape in, a different shape out

The CRUD lab used two models, BookIn and BookOut, and that was enough. Real services soon need more, because what a client may send when creating a record, when editing one, and what a client may read back are three different contracts:

  • creating a book requires the essential fields; an empty title is meaningless;
  • editing a book should allow sending only what changes;
  • the stored record now also carries a private librarian’s note, owner_note, which must never appear in a response.

This worked example rebuilds the models around those three contracts. You met Pydantic models themselves in the schema validation lesson; here they plug into a web API, where a failed check becomes a 422 the client can act on. The previous lab is the starting point — same domain, same routes, same environment.

The code lives in four files. schemas.py holds the input models of steps 1 and 2, models.py the stored record and the public view of step 3, and app.py the application with its routes. The snippets that send requests go in try_it.py, one after another, and you run it with python try_it.py. Here is app.py as it starts: storage is its dictionary of stored records (book 1, The Pragmatic Programmer, is already in it), load(book_id) returns a stored record or raises a 404, POST /books stores a BookRecord and answers with a BookRead, and client is a TestClient that calls the app in process. The routes from steps 2 and 3 go at the end of this file. Because app.py imports models.py, write all of schemas.py, models.py and app.py from steps 1–3 before the first python try_it.py; then add the try_it.py snippets one step at a time and rerun after each.

Python · app.py (the start; the routes of steps 2 and 3 follow)
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient

from models import BookRead, BookRecord
from schemas import BookCreate, BookUpdate

app = FastAPI()
client = TestClient(app)

storage: dict[int, BookRecord] = {
    1: BookRecord(id=1, title="The Pragmatic Programmer", author="Hunt & Thomas",
                  pages=352, owner_note="signed copy, do not lend"),
}


def load(book_id: int) -> BookRecord:
    if book_id not in storage:
        raise HTTPException(status_code=404, detail="book not found")
    return storage[book_id]


@app.post('/books', status_code=201, response_model=BookRead)
def create_book(book: BookCreate):
    record = BookRecord(id=max(storage) + 1, **book.model_dump())
    storage[record.id] = record
    return record
Python · try_it.py (first line; the snippets below follow it)
from app import app, client, storage

02. Step 1: the create schema, with teeth

Constraints on fields reject whole classes of bad input without any handler code. Custom rules that need logic — strip surrounding spaces, reformat an ISBN, reject a blank title — go in field_validator methods, which run as part of validation. A validator that returns a value normalises it; a validator that raises ValueError rejects it, and FastAPI turns either outcome into a documented, type-checked flow before the handler is called.

Python · schemas.py
from pydantic import BaseModel, Field, field_validator


class BookValidatorsMixin:
    @field_validator("title")
    @classmethod
    def title_not_blank(cls, value: str | None) -> str | None:
        if value is None:
            return value
        stripped = value.strip()
        if not stripped:
            raise ValueError("title must not be blank")
        return stripped

    @field_validator("isbn")
    @classmethod
    def compact_isbn(cls, value: str | None) -> str | None:
        if value is None:
            return value
        digits = value.replace("-", "")
        if len(digits) not in (10, 13) or not digits.isdigit():
            raise ValueError("isbn must be 10 or 13 digits")
        return digits


class BookCreate(BookValidatorsMixin, BaseModel):
    title: str = Field(min_length=1, max_length=200)
    author: str = Field(min_length=1, max_length=100)
    pages: int = Field(ge=0)
    isbn: str | None = None
Python · try_it.py: three clients post to /books
r = client.post('/books', json={'title': 'Refactoring',
                               'author': 'Fowler', 'pages': -1})
print(r.status_code, [(e["loc"][-1], e["type"]) for e in r.json()["detail"]])

r = client.post('/books', json={'title': 'Refactoring',
                               'author': 'Fowler', 'pages': 448,
                               'isbn': 'no-digits-here'})
print(r.status_code, r.json()["detail"][0]["msg"])

r = client.post('/books', json={'title': '  Refactoring  ',
                               'author': 'Fowler', 'pages': 448,
                               'isbn': '978-0-13-475759-9'})
print(r.status_code, r.json()["title"], r.json()["isbn"])
Expected output
422 [('pages', 'greater_than_equal')]
422 Value error, isbn must be 10 or 13 digits
201 Refactoring 9780134757599

Three posts, three outcomes, none of them written by you. A negative page count fails the ge=0 constraint. A non-numeric ISBN fails the validator, and the message from the ValueError is carried into the response, so the client sees why. The third post succeeds, and the handler receives the title already stripped and the ISBN already compacted — normalisation inside validation means handlers never trim strings. Notice also what min_length=1 does not catch: a title of three spaces has length 3 and passes the constraint, which is exactly why title_not_blank strips first and then checks.

03. Step 2: the update schema, where absence means “do not touch”

A PATCH request says “change these fields, leave the rest”. That is a different contract from creation, so it gets its own model: every field optional. The subtlety is on the reading side. A plain model_dump() of the update model fills unsent fields with None — so you must ask for only the fields the client actually sent, with exclude_unset=True, and apply just those.

Python · schemas.py (continued)
class BookUpdate(BookValidatorsMixin, BaseModel):
    title: str | None = Field(default=None, min_length=1, max_length=200)
    author: str | None = Field(default=None, min_length=1, max_length=100)
    pages: int | None = Field(default=None, ge=0)
    isbn: str | None = None  # null is a real value here: it clears the ISBN

    @field_validator("title", "author", "pages", mode="before")
    @classmethod
    def omit_but_not_null(cls, value):
        # Absent means "leave alone"; null means "set to null", and these
        # fields are required on the record, so null must be rejected
        if value is None:
            raise ValueError("may be omitted, but not set to null")
        return value
Python · app.py (continued): the PATCH route
@app.patch('/books/{book_id}', response_model=BookRead)
def update_book(book_id: int, changes: BookUpdate):
    stored = load(book_id)  # raises 404 when missing
    for field, value in changes.model_dump(exclude_unset=True).items():
        setattr(stored, field, value)
    return stored  # a BookRecord; response_model filters it
Python · try_it.py: change the page count, then send a null title
r = client.patch('/books/1', json={'pages': 300})
print(r.status_code, r.json()["pages"], r.json()["title"])
print('owner_note' in r.json())

r = client.patch('/books/1', json={'title': None})
print(r.status_code, r.json()["detail"][0]["msg"])
print('stored title:', storage[1].title)
Expected output
200 300 The Pragmatic Programmer
False
422 Value error, may be omitted, but not set to null
stored title: The Pragmatic Programmer

The client sent one field, so one field changed: the title survived untouched. The False line shows the note stayed private: the route returns the stored record, and response_model=BookRead filters it on the way out (step 3 explains how). With a plain model_dump() this loop would also apply title=None, author=None and wipe the record — the single most common PATCH bug, and the reason the optional fields carry their constraints even though they are rarely all sent at once. Validation still applies per sent field: a pages of -1 in a PATCH fails exactly as it did in a POST.

There is a second trap in the same model. str | None makes JSON null a valid value, and exclude_unset=True keeps fields the client sent explicitly, so without the omit_but_not_null validator a body of {"title": null} would pass validation and the loop would write None into a field the record requires. Pydantic does not re-validate on attribute assignment by default, so nothing stops it there; the next read of that book then fails response validation with a 500. The rule to remember: absent means "leave alone", but null is a value, and for a required field it must be rejected. A before validator does that without affecting omitted fields, because validators do not run on defaults. isbn is optional on the record, so null stays allowed there and clears it. (Another safe pattern is to build the updated record with stored.model_copy(update=...) and re-validate it with BookRecord.model_validate(...) before saving.)

04. Step 3: the read schema, a filter on the way out

Now the leak. The stored record keeps the librarian’s note, so the internal model has it and the public model does not. The connection is response_model: FastAPI validates and filters whatever the handler returns through that model before serialising it. A field that is not on the response model cannot leave the server, whatever the handler returns.

Python · models.py (public view and internal record)
from pydantic import BaseModel


class BookRead(BaseModel):      # what a client may see
    id: int
    title: str
    author: str
    pages: int
    isbn: str | None = None


class BookRecord(BaseModel):    # what the server stores
    id: int
    title: str
    author: str
    pages: int
    isbn: str | None = None
    owner_note: str = ""
Python · app.py (continued): the read route
@app.get('/books/{book_id}', response_model=BookRead)
def get_book(book_id: int):
    return load(book_id)   # a BookRecord, note and all
Python · try_it.py: same record, with and without the filter
r = client.get('/books/1')
print(r.status_code, sorted(r.json()))


@app.get('/books/{book_id}/raw')   # no response_model
def get_book_raw(book_id: int):
    return storage[book_id]


r = client.get('/books/1/raw')
print(r.status_code, sorted(r.json()))
Expected output
200 ['author', 'id', 'isbn', 'pages', 'title']
200 ['author', 'id', 'isbn', 'owner_note', 'pages', 'title']

The handler returns the very same object twice. Through BookRead the note is gone; without a response model, whatever the handler hands back is serialised as-is, note included. Filtering on the way out also protects you from your future self: the day someone adds a cost_cents or a password_hash to the record, existing routes still only expose what BookRead declares. The filter works per route, though: every route that returns a stored record needs it, which is why the PATCH route in step 2 declares response_model=BookRead too.

05. Step 4: fields you never declared simply vanish

One more question the three schemas answer for free: what if a client sends a field you never declared? A misbehaving client — or a curious one — might add publisher, or even try to set owner_note itself. Pydantic’s default is to ignore unknown fields: they are dropped during validation, they never reach the stored record, and the response model filters what is left. Run the probe below, which posts the lesson’s BookCreate with two smuggled extra keys:

Python · try_it.py: post two extra keys
r = client.post('/books', json={'title': 'Refactoring', 'author': 'Fowler',
                               'pages': 448, 'publisher': 'Addison-Wesley',
                               'owner_note': 'smuggled'})
print(r.status_code, sorted(r.json()))
print('stored owner_note:', repr(storage[r.json()['id']].owner_note))
Expected output
201 ['author', 'id', 'isbn', 'pages', 'title']
stored owner_note: ''

The request succeeded, and both extra keys are gone — not echoed, and not stored: the record's owner_note keeps its default empty string instead of the smuggled value. This default is what protects a typed API from mass assignment: a client cannot write to a field just by naming it, because only declared fields exist as far as validation is concerned. If you would rather reject unknown fields than ignore them, model_config = ConfigDict(extra="forbid") on the model turns them into a 422; choose that when silent data loss would confuse clients more than an honest error.

06. Mistakes to avoid

07. Check your understanding

Practice check · 3 questions

Schemas in motion

Trace data through the validators and models.

Q1. A client posts {"title": " Designing Data-Intensive Applications ", "author": "Kleppmann", "pages": 616, "isbn": "978-1-4493-7332-0"}. What values does the handler body receive?
Q2. Which title reaches the validator layer but should still be refused, and what stops it?
Q3. A teammate’s PATCH handler loops over changes.model_dump() instead of exclude_unset=True and sets every field. A client sends only {"pages": 300}. What happens to the stored author?
Practice only: not graded, not saved, not evidence.

08. Apply it

Take the lab from the previous lesson and migrate it to these three schemas:

  1. Replace BookIn with BookCreate, add the two validators, and adjust the tests: one that posts a blank title, one that posts a hyphenated ISBN and asserts the stored value is compact.
  2. Add the PATCH /books/{book_id} route with BookUpdate and exclude_unset=True, with a test that patches pages only and asserts the author is unchanged.
  3. Add owner_note to the stored record, a BookRead response model without it, and a test that asserts the key never appears in any response.

This is the exact shape of the skill’s practice task, which the remaining lessons extend with dependencies, routers and settings.

09. Review prompt

Without looking back: why are create, update and read three separate models rather than one? What can a field_validator do that a Field constraint cannot, and in which direction does data flow through response_model? Finally, write from memory the loop that applies a partial update safely, and say what breaks if you drop its argument.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check