如何使用嵌套模式作为 FastAPI 的查询参数?

How to Use Nested Schema as Query Parameters with FastAPI?

注意我们如何使用 Pydantic 模型为路径生成查询参数,如下所示:

from fastapi import FastAPI, Depends
from pydantic import BaseModel

class MyModel(BaseModel):
    value: int | None
    strict: bool | None

@app.get("/")
def get_value(p: MyModel = Depends()):
    ...

按预期工作。

但是,如果我的 Pydantic 模型具有嵌套结构,生成的文档会将嵌套模型视为请求正文的一部分,而不是查询参数。

from fastapi import FastAPI, Depends
from pydantic import BaseModel

class Value(BaseModel):
    data: int
    age: int

class MyModel(BaseModel):
    value: Value | None
    strict: bool | None

@app.get("/")
def get_value(p: MyModel = Depends()):
    ...

这会产生类似

的结果
"/": {
    "get": {
        ...
        "parameters": [
            {
                "required": false,
                "schema": {
                    "title": "Strict",
                    "type": "boolean"
                },
                "name": "strict",
                "in": "query"
            }
        ],
        "requestBody": {
            "content": {
                "application/json": {
                    "schema": {
                        "$ref": "#/components/schemas/Value"
                    }
                }
            }
        },
        ...
    }
}

不需要 requestBody

问题是,我应该如何修改函数的类型签名或模型的构造,以使此嵌套结构作为查询参数用于此 GET 操作?

您可以使用 Depends on the Value model as well, and have the parameters inside it declared as Optional。示例:

class Value(BaseModel):
    data: Optional[int] = None
    age: Optional[int] = None

class MyModel(BaseModel):
    value: Value = Depends()
    strict: Optional[bool] = None