Reputation: 5217
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
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)
Upvotes: 1