Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
FastAPI
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Models and Validation

FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose

Stop sending your database rows to clients. A BookRequest model decides what may come in, a BookResponse model decides what goes out, and an internal shelf_code stays in the database.

Chaand Sheikh

·27 November 2026Models and Validation

What you will learn

  • Write a Pydantic request model that limits what a client may send
  • Write a response model with from_attributes=True that reads a SQLAlchemy row
  • Use response_model in a FastAPI route to keep internal columns out of the JSON
  • Explain why one model for both directions causes problems

Before you start

  • Python classes
  • FastAPI routes
  • SQLAlchemy ORM models

When a client asks your API for a book, should it see everything you store about that book? Usually not. The database row is for you. The JSON on the wire is for the client, and you should design it on purpose.

In FastAPI you do that with models: small Python classes built on Pydantic's BaseModel, made only for the wire. One model decides what may come in. Another decides what goes out.

We'll use a small Book API: FastAPI, SQLAlchemy and an in-memory SQLite database that prints every SQL statement.

The problem: the row leaks its insides

Our Book table has a column the client should never see. shelf_code says where the book stands in the library. It's for the staff only.

from sqlalchemy.orm import Mapped, mapped_column

from library.database import Base


class Book(Base):
    __tablename__ = "book"

    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str]
    author: Mapped[str]
    pages: Mapped[int]
    shelf_code: Mapped[str] = mapped_column(default="NEW-ARRIVALS")  # internal: where the book stands

Before models were added in the lecture, GET /api/books/2 answered with the whole row, column by column:

{"id":2,"title":"Dune","author":"Frank Herbert","pages":412,"shelf_code":"NEW-ARRIVALS"}

There's the shelf code, in front of every client. And the other direction raises the same question. When a client adds a book, what may it send? A title, an author, pages, sure. But an id? A shelf code?

Two doors: one model in, one model out

JSON text becomes a BookRequest with title, author and pages, then a Book row that adds id and shelf_code, then a BookResponse with id, title, author and pages, then JSON text again. Pydantic works at the first and last doors. JSON in "title" "author" "pages" BookRequest title author pages Book row id title author pages shelf_code BookResponse id title author pages JSON out "id" "title" "author" "pages" Pydantic reads the text Pydantic writes the text id and shelf_code belong to us A model for what comes in, a model for what goes out.
The request model and the response model are the two doors. The Book row stays in the middle.

BookRequest: only three fields come in

Both models live in schemas.py:

from pydantic import BaseModel, ConfigDict


class BookRequest(BaseModel):
    """What a client may send: no id, no shelf code."""

    title: str
    author: str
    pages: int


class BookResponse(BaseModel):
    """What a client gets back: the shelf code stays inside."""

    model_config = ConfigDict(from_attributes=True)

    id: int
    title: str
    author: str
    pages: int

BookRequest builds on BaseModel, and that's how Pydantic knows it's a model. Pydantic reads the incoming JSON and fills the three fields by name: "title" goes to title, "author" to author, "pages" to pages.

There is no id field and no shelf_code field. The model simply has no place to put them, so they never make it into a BookRequest.

BookResponse: you choose every field that leaves

BookResponse has four fields and one line of config: from_attributes=True. That line lets Pydantic read the values straight off a Book row object, attribute by attribute.

The row has five fields. The four we listed (id, title, author, pages) travel into the response. shelf_code has no place in the response, so it stays behind in the row. You write each outgoing field on purpose.

The route only names the models

Here's the route that adds a book, from routers/books.py:

from fastapi import APIRouter, Depends, HTTPException, Response
from sqlalchemy.orm import Session

from library import models
from library.database import get_db
from library.repositories.book_repository import BookRepository
from library.schemas import BookRequest, BookResponse
from library.services.book_service import BookService

router = APIRouter(prefix="/api/books", tags=["Books"])


def get_service(db: Session = Depends(get_db)) -> BookService:
    return BookService(BookRepository(db))


@router.post("", response_model=BookResponse, status_code=201, summary="Add a book", operation_id="create")
def add_book(book: BookRequest, response: Response, service: BookService = Depends(get_service)):
    saved = service.create(models.Book(**book.model_dump()))
    response.headers["Location"] = f"/api/books/{saved.id}"
    return saved
  • The parameter book: BookRequest: the request body arrives as a BookRequest. book.model_dump() turns it into a dict, and models.Book(**...) makes a Book row for the service.
  • The decorator response_model=BookResponse: the function returns the whole saved Book row, and FastAPI cuts it down to a BookResponse on the way out. The status stays 201.

The read routes work the same way. GET /api/books/{book_id} uses response_model=BookResponse, and the list route uses response_model=list[BookResponse].

Following one book through both doors

Let's add Matilda by Roald Dahl. The client sends this text:

{"title": "Matilda", "author": "Roald Dahl", "pages": 240}

From the lecture's run, this is what each step looks like:

BookRequest(title='Matilda', author='Roald Dahl', pages=240)
BookResponse(id=4, title='Matilda', author='Roald Dahl', pages=240)
{"id":4,"title":"Matilda","author":"Roald Dahl","pages":240}

Pydantic reads the text and builds a BookRequest. Our function saves the book and returns it. FastAPI keeps the four fields of a BookResponse, and now there is an id: the database gave it 4. On the way out, Pydantic writes that model as JSON again. It all works because the names match, the same names in the JSON and in the model.

The HTTP exchange, as shown in the lecture:

POST /api/books HTTP/1.1
{"title": "Matilda", "author": "Roald Dahl", "pages": 240}

HTTP/1.1 201
Location: /api/books/4
Content-Type: application/json
{"id":4,"title":"Matilda","author":"Roald Dahl","pages":240}

Hidden from the client, still kept inside

Is the shelf code lost? No. The engine prints every SQL statement, and the insert shows it going into the database with its default value:

INSERT INTO book (title, author, pages, shelf_code) VALUES (?, ?, ?, ?)
('Matilda', 'Roald Dahl', 240, 'NEW-ARRIVALS')

The column is filled. The client just never sees it.

Same request, a cleaner answer

Put the two answers to GET /api/books/2 next to each other:

BodyContent-Length
Before: the whole Book row{"id":2,"title":"Dune","author":"Frank Herbert","pages":412,"shelf_code":"NEW-ARRIVALS"}88 bytes
Now: BookResponse{"id":2,"title":"Dune","author":"Frank Herbert","pages":412}60 bytes

The shelf code is gone from what the client sees, and the answer is smaller too.

Run it

The project pins these versions in requirements.txt (Python 3.11 or newer):

fastapi==0.162.0
uvicorn==0.54.0
sqlalchemy==2.1.6
python -m venv .venv
.venv\Scripts\activate          # macOS / Linux: source .venv/bin/activate
pip install -r requirements.txt
uvicorn library.main:app --reload --port 8080

Then send the requests from requests.http (PyCharm, or the REST Client extension in VS Code), or try them in Swagger UI at http://localhost:8080/docs. The database is in memory, so the books are gone when you stop the app.

Common mistakes

  • Returning the ORM row with no response_model. Every column goes out, including internal ones like shelf_code.
  • Using one model for both directions. The response needs id, the request must not accept it. Two models keep the two doors separate.
  • Forgetting from_attributes=True. The response model is filled from a SQLAlchemy object's attributes, not from a dict, and this config is what lets Pydantic read them.
  • Mismatched names. Pydantic matches JSON keys to field names. A field called page_count won't pick up "pages".

Quick recap

PieceJobIn the Book API
Model (BaseModel)a class made for the wireschemas.py
Request modeldecides what may come inBookRequest: title, author, pages
Response modeldecides what goes outBookResponse: id, title, author, pages
response_model=FastAPI cuts the return value down to the modelshelf_code stays in the database
from_attributes=Trueread values off an objectBookResponse from a Book row

Try it yourself

Run GET /api/books and check that none of the three seeded books shows a shelf code. Then add a year column to the Book table and decide on purpose: should it go in the request model, the response model, both or neither?

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Full Stack Python & React: Django, FastAPI, Flask + AI

Python, Django, FastAPI, Flask, React, Docker, AWS, local LLMs and AI vibe coding.View on Udemy ↗: Full Stack Python & React: Django, FastAPI, Flask + AI (opens in a new tab)
On this page
  • The problem: the row leaks its insides
  • Two doors: one model in, one model out
  • BookRequest: only three fields come in
  • BookResponse: you choose every field that leaves
  • The route only names the models
  • Following one book through both doors
  • Hidden from the client, still kept inside
  • Same request, a cleaner answer
  • Run it
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Full Stack Python & React: Django, FastAPI, Flask + AI

Python, Django, FastAPI, Flask, React, Docker, AWS, local LLMs and AI vibe coding.View on Udemy ↗: Full Stack Python & React: Django, FastAPI, Flask + AI (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.