0
0
FastAPIframework~5 mins

Response model exclude and include in FastAPI

Choose your learning style9 modes available
Introduction

Sometimes you want to send only some parts of your data to users. Exclude and include help you pick what to show or hide in the response.

You want to hide sensitive info like passwords from API responses.
You want to show only a few fields from a big data object.
You want to customize the response for different users or roles.
You want to reduce data size by excluding unnecessary fields.
You want to include extra fields only in some responses.
Syntax
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional

class User(BaseModel):
    id: int
    name: str
    email: Optional[str] = None
    password: Optional[str] = None

app = FastAPI()

@app.get("/user", response_model=User, response_model_exclude={"password"})
async def get_user():
    return User(id=1, name="Alice", email="alice@example.com", password="secret")

response_model_exclude hides fields from the response.

response_model_include shows only listed fields.

Examples
This hides the password field from the response.
FastAPI
@app.get("/user", response_model=User, response_model_exclude={"password"})
async def get_user():
    return User(id=1, name="Alice", email="alice@example.com", password="secret")
This shows only the id and name fields in the response.
FastAPI
@app.get("/user", response_model=User, response_model_include={"id", "name"})
async def get_user():
    return User(id=1, name="Alice", email="alice@example.com", password="secret")
This excludes fields that were not set in the returned object.
FastAPI
@app.get("/user", response_model=User, response_model_exclude_unset=True)
async def get_user():
    return User(id=1, name="Alice")
Sample Program

This FastAPI app defines a User model with four fields. The endpoint /user returns a User but excludes the password field from the response. So users will see id, name, and email only.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional

class User(BaseModel):
    id: int
    name: str
    email: Optional[str] = None
    password: Optional[str] = None

app = FastAPI()

@app.get("/user", response_model=User, response_model_exclude={"password"})
async def get_user():
    return User(id=1, name="Alice", email="alice@example.com", password="secret")
OutputSuccess
Important Notes

You can use sets or dictionaries for exclude/include to specify fields.

Exclude and include can be combined with nested models using dot notation or dictionaries.

response_model_exclude_unset hides fields not set in the returned object, useful for partial updates.

Summary

Exclude and include control what fields appear in API responses.

Use response_model_exclude to hide fields like passwords.

Use response_model_include to show only specific fields.