0
0
FastAPIframework~5 mins

Example data in schema in FastAPI

Choose your learning style9 modes available
Introduction

Example data helps show what kind of information your API expects or returns. It makes your API easier to understand and test.

When you want to show sample input data for an API endpoint.
When you want to document the expected format of data in your API.
When you want to help frontend developers understand what data to send.
When you want to generate automatic API docs with clear examples.
When you want to test your API with realistic sample data.
Syntax
FastAPI
from pydantic import BaseModel, Field

class Item(BaseModel):
    name: str = Field(..., example="Apple")
    price: float = Field(..., example=1.99)
    is_offer: bool = Field(default=False, example=True)

The example parameter inside Field() sets example data for each field.

This example data appears in the automatic API docs generated by FastAPI.

Examples
Example data for username and email fields helps show expected input format.
FastAPI
from pydantic import BaseModel, Field

class User(BaseModel):
    username: str = Field(..., example="johndoe")
    email: str = Field(..., example="john@example.com")
Example data can be numbers, strings, or booleans depending on the field type.
FastAPI
from pydantic import BaseModel, Field

class Product(BaseModel):
    id: int = Field(..., example=123)
    name: str = Field(..., example="T-shirt")
    price: float = Field(..., example=19.99)
Sample Program

This FastAPI app defines an Item schema with example data. When you visit the API docs, you will see these examples. The POST endpoint returns the item you send.

FastAPI
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)
    is_offer: bool = Field(default=False, example=True)

@app.post("/items/")
async def create_item(item: Item):
    return item
OutputSuccess
Important Notes

Example data does not affect validation; it only helps with documentation and testing.

Use clear and realistic examples to make your API easier to use.

Summary

Example data shows sample values for API fields.

It helps users understand what data to send or expect.

FastAPI uses Field(..., example=...) to add example data.