FastAPI
Response Model
Shape and filter responses with response_model.
By EZ4Code Team
responsepydantic
Code
from pydantic import BaseModel
from fastapi import FastAPI
app = FastAPI()
class UserIn(BaseModel):
username: str
password: str
class UserOut(BaseModel):
username: str
id: int
@app.post("/users", response_model=UserOut)
def create_user(user: UserIn):
stored = {"username": user.username, "password": "hashed", "id": 1}
return stored
@app.get("/users/{uid}", response_model=list[UserOut])
def list_users(uid: int):
return [{"username": "alice", "id": 1}, {"username": "bob", "id": 2}]Explanation
response_model defines the public shape of the response independent of the internal object returned. FastAPI filters out fields not in the model, so a stored password never leaks to the client. The same model also powers the auto-generated OpenAPI schema.
More FastAPI Snippets
Path Parameters
Capture typed path segments with validation.
Query Parameters
Parse query strings with defaults and validation.
Pydantic Request Body
Validate JSON bodies with Pydantic models.
Dependency Injection
Share logic via Depends and yield-based dependencies.
JWT Auth
Issue and verify JSON Web Tokens with OAuth2.
Async and Await
Define async handlers and run blocking work in a thread.