Skip to main content
This article demonstrates how to extract Pydantic schemas into their own module, reuse fields via inheritance, and define response schemas so FastAPI returns consistent, documented API shapes. Why separate schemas into their own file?
  • Keeps main.py focused on routing and app wiring.
  • Promotes reuse of schema classes across endpoints (create, update, responses).
  • Simplifies tests, documentation, and OpenAPI generation.

Quick example: inline schema (before extraction)

This works for tiny examples but becomes hard to maintain as your API grows.
Move related schemas into a dedicated schemas.py so you can clearly separate request shapes (what clients send) and response shapes (what your API returns).

Create schemas.py

  • Define base fields once and reuse them with inheritance.
  • Create distinct classes for create/update requests if input requirements differ.
  • Add orm_mode = True on response schemas to allow Pydantic to read SQLAlchemy ORM objects.
Example schemas.py:
Table: Schema classes and common use cases

Using the schemas in main.py

Import the schemas module and reference specific classes in endpoint signatures. Using response_model enforces the output shape and adds it to the generated OpenAPI docs. App setup (assumes models.py and database.py exist):
GET all posts (returns a list of PostOut):
GET a single post by id:
Create a post (request uses PostCreate; response uses PostOut):
Update a post:
Delete a post:
When you use response_model with SQLAlchemy ORM objects, set orm_mode = True on the response Pydantic model (as shown in PostOut). This tells Pydantic to read attributes from ORM instances instead of expecting plain dicts.

When to create multiple request schemas

Create separate request schemas when permissions or allowed fields differ between operations:
  • POST: full creation input (e.g., PostCreate).
  • PUT/PATCH: partial updates or restricted updates (e.g., PostUpdate with optional fields).
  • Separate schemas also make validation rules explicit and reduce accidental field overwrite.
Diagram: Schema models overview Schemas/Pydantic models define both request and response shapes, enforce required fields, and help maintain a stable API contract between clients and your FastAPI backend.
A presentation slide titled "Schema Models" explaining that Schema/Pydantic models define the structure of requests and responses and enforce required fields like "title" and "content." A diagram shows a browser (Chrome logo) sending a request through a schema/pydantic model to a FastAPI server and receiving a response back through a schema model.
Use these practices to keep your code modular, validation explicit, and responses predictable — improving developer experience and API reliability.

Watch Video