How to Add Example in Schema FastAPI: Simple Guide
To add an example in a FastAPI schema, use the
example parameter inside the Pydantic model's Field() function. This example will appear in the OpenAPI docs and help users understand the expected data format.Syntax
Use the Field() function from Pydantic to add metadata to model fields. The example argument inside Field() sets a sample value shown in API docs.
Example parts:
Field(..., example=value): marks the field as required and adds an example.Field(default, example=value): sets a default and example.
python
from pydantic import BaseModel, Field class Item(BaseModel): name: str = Field(..., example="Apple") price: float = Field(..., example=1.99) description: str = Field(None, example="A fresh apple")
Example
This example shows a FastAPI app with a schema that includes examples. The examples appear in the interactive API docs (Swagger UI) to guide users on what data to send.
python
from fastapi import FastAPI from pydantic import BaseModel, Field app = FastAPI() class Item(BaseModel): name: str = Field(..., example="Banana") price: float = Field(..., example=0.99) description: str = Field(None, example="A ripe banana") @app.post("/items/") async def create_item(item: Item): return item
Output
When you run this app and open http://127.0.0.1:8000/docs, the POST /items/ endpoint shows example values for each field in the request body.
Common Pitfalls
Common mistakes when adding examples in FastAPI schemas include:
- Not using
Field()and trying to addexampledirectly to the type annotation. - Forgetting to import
Fieldfrompydantic. - Using
exampleinside the model'sConfigclass instead of on fields (this does not work).
Correct usage is always inside Field() for each field you want to document.
python
from pydantic import BaseModel # Wrong way - example ignored class WrongItem(BaseModel): name: str # example="Orange" does nothing here # Right way from pydantic import Field class RightItem(BaseModel): name: str = Field(..., example="Orange")
Quick Reference
Summary tips for adding examples in FastAPI schemas:
- Use
Field(..., example=value)to add examples per field. - Examples appear in OpenAPI docs automatically.
- Use
Noneas default if the field is optional. - Examples help API users understand expected data formats.
Key Takeaways
Add examples in FastAPI schemas using Pydantic's Field(example=...).
Examples improve API docs and help users send correct data.
Always import Field from pydantic and use it on each field.
Do not try to add examples directly to type annotations.
Optional fields can have examples with default None.