1

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?

1 Answer 1

10

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.