PIG208
PIG208

Reputation: 2370

How to Use Nested Schema as Query Parameters with FastAPI?

Notice how we can use Pydantic model to generate query parameters for a path like so:

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()):
    ...

which works as expected.

However, if my Pydantic model has a nested structure, the generated doc will consider the nested model as a part of the request body instead of query parameters.

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()):
    ...

This yields something like

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

where requestBody is not desired.

The question is, how should I modify the type signature of the function, or the constructs of the models to get this nested structure work for this GET operation as query parameters?

Upvotes: 1

Views: 2334

Answers (1)

Chris
Chris

Reputation: 34055

You could use Depends on the Value model as well, and have the parameters inside it declared as Optional. Example:

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

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

Upvotes: 1

Related Questions