← Back to FastAPI, page 2

fastapi-0033 · Medium mid

Why do FastAPI projects use separate schemas for create, update and read, and how do you implement PATCH partial updates?

Create, update and read have different rules: create needs required fields, update usually allows any subset, and read adds server fields like id while hiding secrets. Separate models (StudentCreate, StudentUpdate, StudentRead), often sharing a base class, keep these rules explicit. For PATCH, make every field optional in the update model and apply only fields the client actually sent with model_dump(exclude_unset=True).

Full answer

One model for everything creates bugs: clients can set id or is_admin, responses leak password_hash, and PATCH cannot tell "not sent" from "set to null".

A common layout:

python
class StudentBase(BaseModel):
    name: str = Field(min_length=2)
    email: EmailStr

class StudentCreate(StudentBase):
    password: str = Field(min_length=8)

class StudentUpdate(BaseModel):
    name: str | None = Field(default=None, min_length=2)
    email: EmailStr | None = None
    phone: str | None = None

class StudentRead(StudentBase):
    model_config = ConfigDict(from_attributes=True)
    id: int
    phone: str | None

PATCH semantics: the client sends only the fields to change.

python
changes = data.model_dump(exclude_unset=True)
for field, value in changes.items():
    setattr(student, field, value)

exclude_unset=True includes only fields present in the request body. So {"phone": null} clears the phone, while omitting phone leaves it unchanged. That difference is the whole point; exclude_none=True would wrongly ignore an intentional null.

Pydantic also offers model.model_copy(update=changes) to build an updated copy of a Pydantic object.

PUT vs PATCH: PUT replaces the whole resource, so it should use a model with required fields (often the create model without the password). PATCH changes part of it.

Guard fields that may be updated: the update model simply does not contain id, role or created_at, so clients cannot change them. If some fields need validation rules on update but can be null (clearing), express that explicitly. Optional fields with constraints still validate when present.

Naming conventions vary (StudentIn/StudentOut, StudentCreate/StudentPublic); consistency inside a project matters more than the exact names.

python
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict, Field


class StudentBase(BaseModel):
    name: str = Field(min_length=2)
    email: str


class StudentCreate(StudentBase):
    password: str = Field(min_length=8)


class StudentUpdate(BaseModel):
    name: str | None = Field(default=None, min_length=2)
    email: str | None = None
    phone: str | None = None


class StudentRead(StudentBase):
    model_config = ConfigDict(from_attributes=True)
    id: int
    phone: str | None = None


DB: dict[int, dict] = {}
app = FastAPI()


@app.post("/students", response_model=StudentRead, status_code=201)
def create(data: StudentCreate):
    sid = len(DB) + 1
    DB[sid] = {"id": sid, **data.model_dump(exclude={"password"}), "phone": None,
               "password_hash": "hashed:" + data.password[::-1]}
    return DB[sid]


@app.patch("/students/{sid}", response_model=StudentRead)
def update(sid: int, data: StudentUpdate):
    if sid not in DB:
        raise HTTPException(status_code=404, detail="Student not found")
    changes = data.model_dump(exclude_unset=True)
    DB[sid].update(changes)
    return DB[sid]


c = TestClient(app)
print(c.post("/students", json={"name": "Yash", "email": "yash@example.edu", "password": "Banyan-tree-7"}).json())
print(c.patch("/students/1", json={"phone": "98xxxxxx11"}).json())
print(c.patch("/students/1", json={"name": "Yash Jain"}).json())     # phone untouched
print(c.patch("/students/1", json={"phone": None}).json())           # phone cleared on purpose
print(c.patch("/students/1", json={"name": "Y"}).status_code)
print("password_hash" in c.get("/openapi.json").text)

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'name': 'Yash', 'email': 'yash@example.edu', 'id': 1, 'phone': None} {'name': 'Yash', 'email': 'yash@example.edu', 'id': 1, 'phone': '98xxxxxx11'} {'name': 'Yash Jain', 'email': 'yash@example.edu', 'id': 1, 'phone': '98xxxxxx11'} {'name': 'Yash Jain', 'email': 'yash@example.edu', 'id': 1, 'phone': None} 422 False

Key points

  • Separate create, update and read models
  • Read model hides secrets and adds server fields
  • Update model has all fields optional
  • PATCH applies model_dump(exclude_unset=True)
  • exclude_unset distinguishes 'not sent' from 'set to null'

Common mistakes

  • Using one model for input and output and leaking password hashes
  • Using exclude_none for PATCH and ignoring intentional nulls
  • Letting the update model include id or role fields
  • Implementing PATCH with a model whose fields are required

Follow-ups

  • What is the difference between PUT and PATCH in practice?
  • How would you prevent a student from changing their own role?
  • How would you implement JSON Merge Patch or JSON Patch?

Tips

  • Explain why each model exists
  • Show exclude_unset and explain its difference from exclude_none
  • Mention PUT versus PATCH