GET Request with Pydantic List field #9133
-
|
Hi, I'm new to FastAPI (migrating from Flask) and I'm trying to create a Pydantic Model to my GET route When I'm running But if I'm changing What is the reason that Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 9 comments
-
|
class SortModel(BaseModel):
field: Optional[str]
directions: List[str]
def sort_model(field: Optional[str] = Query(None), directions: List[str] = Query([])):
return SortModel(field=field, directions=directions)
@router.get("/pydanticmodel")
def get_sort(sort: SortModel = Depends(sort_model)): |
Beta Was this translation helpful? Give feedback.
-
|
@SirTelemak Yes you can't send an array inside query but you can send a body with -d flag, the code works fine when you send a Body with using -d flag In: curl -X GET "http://127.0.0.1:8000/pydanticmodel?field=123" -d "[\"string\"]"
Out: {"field":"123","directions":["string"]} |
Beta Was this translation helpful? Give feedback.
-
|
@ycd ye, but it's quite unintuitive and works bad with OpenAPI so I think better way to use like I suggested, so you can use |
Beta Was this translation helpful? Give feedback.
-
|
Hi everybody, Thank you for your replies. Do you know any other way to avoid it? |
Beta Was this translation helpful? Give feedback.
-
|
Instead of using basemodel, you can use and validate directly through Python class if in case you are getting the data from a form. this will work out for form validation.. |
Beta Was this translation helpful? Give feedback.
-
Actually, that's what Swagger suggests for the query. |
Beta Was this translation helpful? Give feedback.
-
|
@tiangolo any help |
Beta Was this translation helpful? Give feedback.
-
|
Just chiming in here since I am having the same issue. When defining a list in a basemodel, the swagger spec moves that query parameter into the body. I dont know if the issue lies in the pydantic model or in the swagger spec generator. |
Beta Was this translation helpful? Give feedback.
-
|
Since FastAPI 0.115.0 you can officially use Pydantic models to declare Query parameters: from fastapi import FastAPI, Query
from pydantic import BaseModel
from typing import Optional, List
app = FastAPI()
class SortModel(BaseModel):
field: Optional[str]
directions: List[str]
@app.get("/pydanticmodel")
def get_sort(criteria: SortModel = Query()):
pass # my code for handling this route.....Docs: https://fastapi.tiangolo.com/tutorial/query-param-models/ |
Beta Was this translation helpful? Give feedback.
Since FastAPI 0.115.0 you can officially use Pydantic models to declare Query parameters:
Docs: https://fastapi.tiangolo.com/tutorial/query-param-models/