JSON Schema and Data Examples

JSON Schema and Data Examples

Make your API self-explanatory. Learn how to provide example payloads and rich descriptions for your Pydantic models in the documentation.

JSON Schema and Data Examples

A developer looks at your API docs and sees id: int. But what does a real ID look like? Is it 1? Is it 99999? Providing Examples is the fastest way to help other developers (and LLMs) understand how to use your API correctly.

In this lesson, we use Pydantic to enrich our documentation with context.


1. Adding Examples to Models

Inside your BaseModel, you can use the Config or Field to provide a sample payload.

from pydantic import BaseModel, Field

class Item(BaseModel):
    name: str = Field(..., examples=["Acoustic Guitar"])
    price: float = Field(..., examples=[499.99])
    description: str | None = Field(default=None, examples=["A high-quality 6-string guitar."])

2. Global Model Examples

If you want to provide a complete "Full Object" example, use the model_config (Pydantic v2).

class UserCreate(BaseModel):
    username: str
    email: str

    model_config = {
        "json_schema_extra": {
            "examples": [
                {
                    "username": "shshell_dev",
                    "email": "dev@shshell.com",
                }
            ]
        }
    }

This example will appear in the Swagger UI "Request Body" section automatically.


3. Rich Schema Descriptions

You can use Markdown inside your descriptions to provide links or bold text.

class SearchQuery(BaseModel):
    q: str = Field(
        ..., 
        description="The search keywords. Supports **AND** and **OR** operators."
    )

4. Why AI Agents Love Examples

When you use your FastAPI app as a Tool for an AI Agent, the agent reads the OpenAPI schema. If you provide examples, the agent has a "Template" to follow. This significantly reduces the chance of the AI sending a "422 Validation Error" because it guessed the data format wrong.


Visualizing the Schema Detail

FeatureWithout CustomizationWith Customization
Fieldname: stringname: string (Example: "Acoustic Guitar")
Description(Empty)The unique identifier for the product.
Constraints(None)Minimum Length: 5, Match: ^[A-Z]+$

Summary

  • examples: The most direct way to show "What the data looks like."
  • description: The best way to explain "What the data means."
  • json_schema_extra: Provides deep customization of the final OpenAPI file.
  • Context: Good documentation reduces support tickets and integration time.

In the next lesson, we wrap up Module 13 with Exercises on documentation mastery.


Exercise: The Perfect Sample

You are building an API for a Weather App. Create a Pydantic model for a forecast.

  1. Include fields for city, temperature, and humidity.
  2. Add a description for each field.
  3. Add an example for the city field (e.g., "Paris").

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn