Reputation: 336
I'm using FastAPI framework and I want to send a list of lists using Query
parameters. I can send a list using the below syntax, but I am unable to pass list of lists.
sections_to_consider: Optional[List[str]] = Query(None)
I get the below output.
What I want is something like this
{
"sections_to_consider": [
["string", "string2"],
["string3", "string4"]
]
}
I tried below syntax but getting an error.
sections_to_consider: Optional[List[list]] = Query(None)
sections_to_consider: Optional[List[List[str]]] = Query(None)
I need to accept list of lists. This is an optional parameter but, if passed, the inner list must have exactly 2 strings. Is there any way to do it in FastAPI? Or any work around?
Thanks in advance.
Upvotes: 4
Views: 12921
Reputation: 1258
As of now, fastApi does not supports nested list from query parameters. you can find more in multiselection lists Multiselect and dropdownMenu.
Workaround can be using request body. Instead of sending the List[List[str]] form Query, can send the data by request body
Example using class: app.py
from typing import List
import uvicorn
from fastapi import FastAPI, Query
from pydantic import BaseModel
app = FastAPI()
class newList(BaseModel):
sections_to_consider: List[List[str]]
@app.post("/items/")
async def read_items(q: newList):
return q
if __name__ == '__main__':
uvicorn.run("6:app",host='127.0.0.1', port=8000, reload=True)
You can use a curl request
or Request URL
and request body
from OpenApi docs
curl request
:
curl -X 'POST' \
'http://127.0.0.1:8000/items/' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"sections_to_consider": [
["string", "string2"],
["string3", "string4"]
]
}'
Request URL
:
http://127.0.0.1:8000/items/
Request Body
:
{
"sections_to_consider": [
["string", "string2"],
["string3", "string4"]
]
}
The Response from the request will be as below:
ResponseBody
:
{
"sections_to_consider": [
[
"string",
"string2"
],
[
"string3",
"string4"
]
]
}
Upvotes: 5