← Back to FastAPI, page 3

fastapi-0054 · Easy fresher

How do GET, POST, PUT, PATCH and DELETE map to CRUD operations in FastAPI, and what status codes should each return?

GET reads (200, or 404 when missing), POST creates (201 with the new resource, ideally with a Location header), PUT replaces a resource completely (200 or 204), PATCH updates part of it (200), and DELETE removes it (204 No Content). GET is safe; GET, PUT and DELETE are idempotent; POST is neither. In FastAPI each is a decorator on a function, with status_code set where the default 200 is not right.

Full answer
MethodPurposeTypical successSafeIdempotent
GETread200yesyes
POSTcreate (or run an action)201nono
PUTreplace the whole resource200 or 204noyes
PATCHpartial update200nousually not guaranteed
DELETEremove204noyes

Design habits:

  • Use plural nouns for collections: /students and /students/{student_id}.
  • POST returns 201 Created with the created object and a Location header for the new URL. Validation errors are 422 (FastAPI) and conflicts such as duplicates are 409.
  • PUT needs the full representation, so missing fields are errors; PATCH accepts any subset: use a model whose fields are all optional and model_dump(exclude_unset=True).
  • DELETE returns 204 with an empty body (declare status_code=204, and return None). Deleting something already gone can return 204 or 404; choose one and document it.
  • Missing resources raise HTTPException(404).
  • Safe methods must not change state, because browsers, crawlers and caches may repeat GET requests.

FastAPI specifics: @app.post("/students", status_code=201, response_model=Student), and path parameters in the decorator path are passed to the function by name. Use separate schemas for input and output (create, update and read models) so clients cannot set ids or read internal fields.

An in-memory dict is fine for demos; production code uses a database with the same endpoint shapes.

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

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


class StudentIn(BaseModel):
    name: str
    grade: str


class StudentPatch(BaseModel):
    name: str | None = None
    grade: str | None = None


class Student(StudentIn):
    id: int


def get_or_404(student_id: int) -> dict:
    if student_id not in DB:
        raise HTTPException(status_code=404, detail="Student not found")
    return DB[student_id]


@app.post("/students", status_code=201, response_model=Student)
def create(s: StudentIn, response: Response):
    new_id = len(DB) + 1
    DB[new_id] = {"id": new_id, **s.model_dump()}
    response.headers["Location"] = f"/students/{new_id}"
    return DB[new_id]


@app.get("/students/{student_id}", response_model=Student)
def read(student_id: int):
    return get_or_404(student_id)


@app.put("/students/{student_id}", response_model=Student)
def replace(student_id: int, s: StudentIn):
    get_or_404(student_id)
    DB[student_id] = {"id": student_id, **s.model_dump()}
    return DB[student_id]


@app.patch("/students/{student_id}", response_model=Student)
def update(student_id: int, patch: StudentPatch):
    DB[student_id] = {**get_or_404(student_id), **patch.model_dump(exclude_unset=True)}
    return DB[student_id]


@app.delete("/students/{student_id}", status_code=204)
def delete(student_id: int):
    get_or_404(student_id)
    del DB[student_id]


c = TestClient(app)
r = c.post("/students", json={"name": "Asha", "grade": "B"})
print(r.status_code, r.headers["location"], r.json())
print(c.patch("/students/1", json={"grade": "A"}).json())
print(c.put("/students/1", json={"name": "Asha Rao", "grade": "A"}).json())
print(c.put("/students/1", json={"name": "Only name"}).status_code)
r = c.delete("/students/1")
print(r.status_code, repr(r.content), c.get("/students/1").status_code)

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): 201 /students/1 {'name': 'Asha', 'grade': 'B', 'id': 1} {'name': 'Asha', 'grade': 'A', 'id': 1} {'name': 'Asha Rao', 'grade': 'A', 'id': 1} 422 204 b'' 404

Key points

  • Map verbs to CRUD with correct status codes
  • POST returns 201 and a Location header
  • PUT replaces; PATCH updates a subset
  • DELETE returns 204 with no body
  • GET must be safe; GET, PUT and DELETE are idempotent

Common mistakes

  • Returning 200 for creation instead of 201
  • Using GET for operations that change data
  • Treating PUT as a partial update
  • Returning a body with 204
  • Using verbs in URLs such as /createStudent

Follow-ups

  • Why is PUT idempotent and POST not?
  • How do you make POST safe to retry?
  • When is PATCH not idempotent?

Tips

  • Fill the table from memory
  • State status codes
  • Explain safe vs idempotent