5.7 Swagger
To change the example response shown in Swagger UI for a FastAPI endpoint, you need to customize the OpenAPI schema or use Pydantic models with example data.
How to change the example response in FastAPI:
Section titled “How to change the example response in FastAPI:”- Add example data to your Pydantic response model using
Config.schema_extra
Example:
from typing import Listfrom pydantic import BaseModel, Fieldfrom fastapi import FastAPI
app = FastAPI()
class User(BaseModel): id: int = Field(..., example=123) email: str = Field(..., example="alice@example.com") full_name: str = Field(..., example="Alice Wonderland")
class Config: schema_extra = { "example": { "id": 1, "email": "user@example.com", "full_name": "John Doe" } }
@app.get("/test/users", response_model=List[User])async def list_users(): return [ {"id": 1, "email": "user@example.com", "full_name": "John Doe"} ]This will update the example JSON you see in Swagger UI to:
[ { "id": 1, "email": "user@example.com", "full_name": "John Doe" }]- Alternatively, specify an example directly in the endpoint with
responsesparameter
@app.get( "/test/users", response_model=List[User], responses={ 200: { "content": { "application/json": { "example": [ { "id": 99, "email": "custom@example.com", "full_name": "Custom User" } ] } } } })async def list_users(): return [ {"id": 99, "email": "custom@example.com", "full_name": "Custom User"} ]Summary
Section titled “Summary”- The most maintainable way is to add examples inside your Pydantic model with
Field(..., example=...)orConfig.schema_extra. - You can also override examples directly in the route
responsesargument.
If you want, I can help rewrite your code snippet with a custom example response! Just share your current model.
==============================================
That’s because in Pydantic (v1 or v2), the examples keyword in Field() isn’t directly used by FastAPI’s OpenAPI generator to show examples in Swagger UI.
FastAPI’s OpenAPI generator only shows a single example (singular) unless you explicitly define multiple examples in the route parameter/body declaration using example or examples at the request schema level, not the field level.
Here’s why:
Field(..., examples=[...])is a Pydantic feature for JSON Schema generation, but OpenAPI 3.0 (what Swagger UI uses) doesn’t have direct support for an array of examples per field.- To display multiple examples in Swagger UI, you must define them in the FastAPI
Body(..., examples={...})or at the@app.postrequest level.
Option 1 — Single Example at Field Level
Section titled “Option 1 — Single Example at Field Level”If you just want one example per field:
from pydantic import BaseModel, EmailStr, Field
class UserBase(BaseModel): email: EmailStr = Field(..., example="alice@example.com") # singular full_name: str = Field(..., example="Alice Wonderland")Option 2 — Multiple Examples at Request Level
Section titled “Option 2 — Multiple Examples at Request Level”from fastapi import FastAPI, Body
app = FastAPI()
@app.post("/users/")def create_user( user: UserCreate = Body( ..., examples={ "example1": { "summary": "Example Alice", "description": "A normal user account.", "value": { "email": "alice@example.com", "full_name": "Alice Wonderland", "password": "secret123" } }, "example2": { "summary": "Example Nadith", "description": "Another user account.", "value": { "email": "chathurdara@gmail.com", "full_name": "Nadith Pathirage", "password": "mypassword" } } } )): return userThis way, Swagger UI will show two selectable examples in the request body dropdown.
If you want, I can rewrite your UserBase model so it still uses Field() for type hints but pulls its multiple examples into the route doc so they show in Swagger UI. That way you keep your schema clean but still have the multiple examples in the UI.
===========================================
Troubleshooting
Section titled “Troubleshooting”class User(UserBase): id: int = Field(..., examples=[123, 000])
class Config: orm_mode = True schema_extra = { "example": { "id": 1, "email": "user@example.com", "full_name": "John Doe" } }Error:
pydantic.errors.PydanticUserError: "Config" and "model_config" cannot be used together
Right — that error happens because in Pydantic v2 you can’t mix the old Config class (v1 style) with the new model_config dict (v2 style) in the same model.
Since you have
class Config: orm_mode = Trueyou’re using v1 style, but model_config is v2 style — they are mutually exclusive.
In Pydantic v2, the equivalent of orm_mode is:
Section titled “In Pydantic v2, the equivalent of orm_mode is:”model_config = { "from_attributes": True # replaces orm_mode = True}Your fixed User model in Pydantic v2
Section titled “Your fixed User model in Pydantic v2”from pydantic import BaseModel, EmailStr, Field
class UserBase(BaseModel): email: EmailStr = Field(..., example="alice@example.com") full_name: str = Field(..., example="Alice Wonderland")
class UserCreate(UserBase): password: str = Field(..., example="mypassword")
class User(UserBase): id: int = Field(..., example=1)
model_config = { "from_attributes": True, # replaces orm_mode "json_schema_extra": { "example": { "id": 1, "email": "user@example.com", "full_name": "John Doe" } } }✅ Changes made:
- Removed
Configclass entirely. - Used
model_configdict for bothfrom_attributes(ORM mode) andjson_schema_extra(full example). - Used
example=instead ofexamples=inField()because OpenAPI only shows one per field.
If you want multiple complete examples to show in Swagger UI for this model, you can’t do it at the Field or model_config level — you have to define them at the route level with Body(examples={...}).
Do you want me to show you that multi-example route setup for this exact User model? That way Swagger will give a dropdown of example users.
===============================
In Pydantic v2, json_schema_extra can only have one "example" key for a single example.
If you want multiple examples, OpenAPI supports them, but FastAPI only shows them if you define them at the endpoint level using examples in Body(...).
Why you can’t just do this:
Section titled “Why you can’t just do this:”"json_schema_extra": { "examples": [ {...}, {...} ] # ❌ Won’t render in Swagger UI for models}Swagger UI ignores multiple examples at the schema level — it expects multiple examples to be defined per request body.
Correct way — multiple examples in FastAPI route
Section titled “Correct way — multiple examples in FastAPI route”from fastapi import FastAPI, Bodyfrom pydantic import BaseModel, EmailStr, Field
app = FastAPI()
class User(BaseModel): id: int = Field(..., example=1) email: EmailStr = Field(..., example="user@example.com") full_name: str = Field(..., example="John Doe")
model_config = { "from_attributes": True }
@app.post("/users/")def create_user( user: User = Body( ..., examples={ "Example1": { "summary": "John Doe", "value": {"id": 1, "email": "user@example.com", "full_name": "John Doe"} }, "Example2": { "summary": "Alice Wonderland", "value": {"id": 2, "email": "alice@example.com", "full_name": "Alice Wonderland"} } } )): return userNow in Swagger UI:
- You get a dropdown for
Example1andExample2. - The examples are tied to the request body, not just the schema.
If you want, I can make it so your User model still has one default example, but your route shows multiple examples in the dropdown. That’s the cleanest combo.