helt
helt

Reputation: 5217

pydantic v2 mark Field required in schema while having defaults

I use pydantic and fastapi to generate openapi specs. According to the docs, required fields, cannot have default values. However, my discriminator should have a default.

What is the best way to tell pydantic to add type to the list of required properties (without making it necessary to add a type when instantiating a Dog(name="scooby")?

class PetType(str, Enum):
    DOG = "Dog"
    CAT = "Cat"


class Pet(BaseModel):
    name: Annotated[str, Field(..., examples=["Unnamed pet"])]


class Dog(Pet):
    type: Literal[PetType.DOG] = PetType.DOG
{
    "title": "Dog",
    "type": "object",
    "properties": {
        "name": {
            "examples": [
                "Unnamed pet"
            ],
            "title": "Name",
            "type": "string"
        },
        "type": {
            "const": "Dog",
            "default": "Dog",
            "title": "Type"
        },
    },
    "required": [
        "name",
    ]
}

Upvotes: 0

Views: 1155

Answers (1)

user3552
user3552

Reputation: 13

You can add the following to your BaseModel class to make all of its fields required in the generated openapi spec, no matter if they have default values:

model_config = ConfigDict(json_schema_serialization_defaults_required=True)

See: https://docs.pydantic.dev/latest/api/config/#pydantic.config.ConfigDict.json_schema_serialization_defaults_required

Upvotes: 1

Related Questions