For a FastAPI Pydanctic class I have these values
class ErrorReportRequest(BaseModel):
sender: Optional[str] = Field(..., description="Who sends the error message.")
error_message_displayed_to_client: str = Field(..., description="The error message displayed to the client.")
I use the class as an input model
router = APIRouter()
@router.post(
"/error_report",
response_model=None,
include_in_schema=True,
)
def error_report(err: ErrorReportRequest):
pass
When I run this, sender
is a required field. If it's not included in the incoming JSON, I get a validation error.
Input:
{
"error_message_displayed_to_client": "string"
}
Results in:
{
"detail": [
{
"loc": [
"body",
"sender"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
If I remove the Field description like this:
class ErrorReportRequest(BaseModel):
sender: Optional[str]
error_message_displayed_to_client: str = Field(..., description="The error message displayed to the client.")
the request passes.
How can I add a Field description to an optional field so that it's still allowed to omit the field name?