FastAPI FoundationsLesson 1.4
How FastAPI response models and status codes work
response_model parameter, response filtering, HTTP status codes, status_code parameter, HTTPException, JSONResponse, response typing
Response Models and Status Codes
The response_model parameter on a route decorator controls what FastAPI serializes and returns. It strips fields not in the response model — critical for hiding internal data like password hashes.
Filtering output with response_model
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class UserIn(BaseModel):
username: str
password: str
class UserOut(BaseModel):
username: str
@app.post("/users/", response_model=UserOut)
def create_user(user: UserIn):
# password never leaves this function in the response
return user
Even though the handler returns the full UserIn object, FastAPI serializes only the fields declared in UserOut.
Setting status codes
from fastapi import FastAPI, status
@app.post("/items/", status_code=status.HTTP_201_CREATED)
def create_item():
return {"created": True}
Use status.HTTP_201_CREATED instead of raw integers. The constants are self-documenting and appear correctly in OpenAPI.
Raising HTTP errors
from fastapi import HTTPException
@app.get("/items/{item_id}")
def get_item(item_id: int):
if item_id > 100:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}
HTTPException short-circuits the handler and returns a JSON error body with the detail field. Use it for all expected error states — not found, forbidden, conflict.
