Serializers & DTOs: Controlling What Your API Exposes

Published: (February 25, 2026 at 02:48 PM EST)
1 min read
Source: Dev.to

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:

  • id
  • name
  • description
  • price
  • created_at
  • internal_db_id ← sensitive internal field
  • deleted_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/full would return all model fields, including internal_db_id and deleted_at.
  • With DTO – a request to /items returns only the fields defined in ItemResponseDTO, keeping sensitive data hidden.

Always define explicitly what your API exposes.

0 views
Back to Blog

Related posts

Read more »