5

According to the docs it is possible to pass a list of values https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#query-parameter-list-multiple-values .

I have tried on my end and the endpoint http://localhost:8000/items/?q=foo&q=bar correctly process the values as a list:

{"q":["foo","bar"]}

But the docs do not, and interpret it as a string and do not render multiple options:

enter image description here

Here is my main.py:

from db import engine,get_db
from models import Example,ExampleModel,Base,Color,Item
from fastapi import FastAPI,Depends,Query,Path
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from contextlib import asynccontextmanager
from typing import Annotated,Union,List
from fastapi.responses import HTMLResponse


@asynccontextmanager
async def lifespan(app: FastAPI):
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    yield

app = FastAPI(lifespan=lifespan) # type: ignore


@app.get("/items/")
async def read_items(q: Annotated[List[str] | None, Query()] = None):
    query_items = {"q": q}
    return query_items
6
  • Could you please try it without using Annotated, as demonstrated here? Commented Jan 17, 2024 at 7:53
  • @Chris I think using Annotated is preferred way now because of pydantic2.0. Commented Jan 17, 2024 at 8:02
  • 1
    Annotated[List[str], Query()] = None does the thing. But it looks incorrect:') Commented Jan 17, 2024 at 8:07
  • async def read_items(q: list[str] | None = Query(default=None)): tried but didn't work Commented Jan 17, 2024 at 8:11
  • worked for me yes: Annotated[list[str],Query()] = None): but pylance complains about typing Commented Jan 17, 2024 at 8:14

1 Answer 1

2

It seems to be the FastAPI example:

@app.get("/items/")
async def read_items(q: Annotated[list[str] | None, Query()] = None):
    query_items = {"q": q}
    return query_items

gives:

TypeError: unsupported operand type(s) for |: 'types.GenericAlias' and 'NoneType'

Removing the | None makes it work:

@app.get("/items/")
async def read_items(q: Annotated[list[str], Query()] = None):
    query_items = {"q": q}
    return query_items

Above is with:

fastapi 0.110.0
python 3.12
Sign up to request clarification or add additional context in comments.

1 Comment

How about when the query is from a pydantic object whose fields are lists of strings? I don't get the swagger rendering for them, only for scalar fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.