FastAPI - Swagger UI 文档未将列表数组呈现为查询参数

问题描述 投票:0回答:1

根据文档,可以传递值列表https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#query-parameter-list-multiple-values

我已经尝试过,端点 http://localhost:8000/items/?q=foo&q=bar 正确地将值处理为列表:

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

但是文档没有,并将其解释为字符串并且不呈现多个选项:

enter image description here

这是我的

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
python swagger fastapi openapi swagger-ui
1个回答
1
投票

这似乎是FastAPI示例

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

给出:

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

删除

| None
即可正常工作:

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

上面是:

fastapi 0.110.0
python 3.12
© www.soinside.com 2019 - 2024. All rights reserved.