Reputation: 3010
Consider the following
from pydantic import BaseModel, Field
class Model(BaseModel):
required: str
This will make required
a required field for Model
, however, in the FastAPI autogenerated Swagger docs it will have an example value of "string".
How can I make a required field with a sensible default? If I make a model like
from pydantic import BaseModel, Field
class Model(BaseModel):
required: str = 'Sensible default'
Then the field required
is no longer required, but it shows up with a sensible default in the docs. Is there an easy workaround for this?
Upvotes: 2
Views: 1141
Reputation: 41
You can use Field() to set up those options and check.
from pydantic import BaseModel, Field
class Model(BaseModel):
something: str # required, shows "string"
something: str = None # not required, shows "string"
something: str = Field(..., example="this is the default display") # required, shows example
something: str = Field(None, example="Foobar") #not required, show example
There are a multitude of different parameters that Field() can validate against.
Upvotes: 4
Reputation: 22459
I haven't looked into why the (pydantic) model representation within the openapi version that ships with FastAPI leaves the asterisk out, but the field is definitely still required (try putting a null value, or anything other than string). This might just be an UI inconsistency.
Upvotes: 2