Jake
Jake

Reputation: 2912

Pydantic: Specify value as required yet input example value

I am using Pydantic in FastAPI, to define in an OpenAPI doc. Realised that to define a value as required, I need to keep the values empty, like below.

class Item(BaseModel):
    name: str
    description: str
    price: float
    tax: float

However, I wanted to give an the JSON with example values, which I can create with the below syntax.

class Item(BaseModel):
    name: str = "my name"
    description: str = "my description"
    price: float = 0.234
    tax: float = 0.20

But this will render them as not required in OpenAPI docs. Is there any way where I can specify them as required, and yet give an example value?

Upvotes: 1

Views: 3650

Answers (1)

vishes_shell
vishes_shell

Reputation: 23484

Based on docs Schema Extra - Example:

You can declare extra Config.schema_extra for your BaseModel as such:

class Item(BaseModel):
    name: str
    description: str
    price: float
    tax: float

    class Config:
        schema_extra = {
            "example": {
                "name": "my name",
                "description": "my description",
                "price": 0.234,
                "tax": 0.20
            }
        }

Or declare explicitly with pydantic.Field:

from pydantic import BaseModel, Field

class Item(BaseModel):
    name: str = Field(..., example="my name")
    description: str = Field(..., example="my description")
    price: float = Field(..., example=0.234)
    tax: float = Field(..., example=0.20)

Upvotes: 10

Related Questions