使用 FastAPI 和 Pydantic,如何定义带有描述的可选字段

Using FastAPI & Pydantic, how do I define an Optional field with a description

对于 FastAPI Pydanctic class 我有这些值

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.")

我使用class作为输入模型

router = APIRouter()

@router.post(
    "/error_report",
    response_model=None,
    include_in_schema=True,

)
def error_report(err: ErrorReportRequest):
    pass

当我运行这个的时候,sender是必填字段。如果它未包含在传入 JSON 中,我会收到验证错误。

输入:

{
  "error_message_displayed_to_client": "string"
}

结果:

{
  "detail": [
    {
      "loc": [
        "body",
        "sender"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}

如果我像这样删除字段描述:

    class ErrorReportRequest(BaseModel):
        sender: Optional[str]
        error_message_displayed_to_client: str = Field(..., description="The error message displayed to the client.")

请求通过。

如何将字段描述添加到可选字段,以便它仍然允许省略字段名称?

您需要为 Field 提供明确的默认值,例如 None 而不是 ...:

class ErrorReportRequest(BaseModel):
    sender: Optional[str] = Field(None, description="Who sends the error message.")
    error_message_displayed_to_client: str = Field(..., description="The error message displayed to the client.")

...表示必填。这当然与 Optional 冲突,但看起来 pydantic 更优先于 ...

来自documentation of Field:

default: (a positional argument) the default value of the field. Since the Field replaces the field's default, this first argument can be used to set the default. Use ellipsis (...) to indicate the field is required.