response_model_exclude in FastAPI?response_model_exclude to hide some fields. What will the JSON response include?from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class User(BaseModel): id: int username: str email: str @app.get("/user", response_model=User, response_model_exclude={"email"}) def get_user(): return User(id=1, username="alice", email="alice@example.com")
The response_model_exclude option tells FastAPI to remove specified fields from the response. Here, email is excluded, so it won't appear in the JSON output.
response_model_include affect the FastAPI response?response_model_include?from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Product(BaseModel): id: int name: str price: float description: str @app.get("/product", response_model=Product, response_model_include={"id", "name"}) def get_product(): return Product(id=10, name="Book", price=12.99, description="A nice book")
response_model_include will be shown.The response_model_include option limits the response to only the specified fields. Here, only id and name are included.
response_model_exclude syntax?response_model_exclude syntax?from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): id: int name: str price: float @app.get("/item", response_model=Item, response_model_exclude=["price"]) def get_item(): return Item(id=5, name="Pen", price=1.5)
response_model_exclude.The response_model_exclude parameter expects a set or dict, not a list. Passing a list causes a TypeError because lists are unhashable.
response_model_include and response_model_exclude?from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Profile(BaseModel): id: int username: str email: str bio: str @app.get( "/profile", response_model=Profile, response_model_include={"id", "username", "email"}, response_model_exclude={"email"} ) def get_profile(): return Profile(id=2, username="bob", email="bob@example.com", bio="Hello!")
response_model_exclude removes fields even if included.When both response_model_include and response_model_exclude are used, FastAPI first includes only the specified fields, then excludes the ones listed. Here, email is included but then excluded, so it is removed.
response_model_exclude?response_model_exclude is set?from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Data(BaseModel): a: int b: int c: int @app.get("/data", response_model=Data, response_model_exclude={"b"}) def get_data(): return {"a": 1, "b": 2, "c": 3}
FastAPI applies response_model_exclude only when the returned value is an instance of the response model class. Returning a plain dict bypasses this filtering.