Serializers & DTOs: Controlling What Your API Exposes
Source: Dev.to
What is a DTO?
A DTO (Data Transfer Object) defines exactly which data is exposed to clients, preventing internal fields from being leaked.
Example model
Consider an Item model with the following fields:
idnamedescriptionpricecreated_atinternal_db_id← sensitive internal fielddeleted_at← sensitive internal field
Without a DTO, all of these fields would be returned to the client.
DTO definition
class ItemResponseDTO(BaseModel):
id: int
name: str
price: float
class Config:
from_attributes = True
This DTO only exposes id, name, and price.
Using the DTO in a FastAPI endpoint
@app.get("/items", response_model=List[ItemResponseDTO])
def get_all_items():
db = SessionLocal()
items = db.query(Item).all()
db.close()
return items
FastAPI’s response_model parameter filters the output based on the DTO.
- Without DTO – a request to
/items/fullwould return all model fields, includinginternal_db_idanddeleted_at. - With DTO – a request to
/itemsreturns only the fields defined inItemResponseDTO, keeping sensitive data hidden.
Always define explicitly what your API exposes.