Reputation: 2370
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
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