Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set swagger ui to use list fields in query parameters with FastAPI

When making an app that uses dependency injection with a list field, the parameter automatically goes to the request body in SwaggerUI:

from fastapi import FastAPI, Query, Depends
import uvicorn
from pydantic import BaseModel, Field
from typing import List


class QueryParams(BaseModel):
    name: str = Field(...)
    ages: List[int] = Field([])


app = FastAPI()


@app.get("/test")
def test(query: QueryParams = Depends()):
    return "hi"

uvicorn.run(app)

SwaggerUI

Which means I cant test it in swagger UI. Even if I change field to query, it still doesn’t work:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from fastapi import FastAPI, Query, Depends
import uvicorn
from pydantic import BaseModel, Field
from typing import List


class QueryParams(BaseModel):
    name: str = Field(...)
    ages: List[int] = Query([])  # <-- Query


app = FastAPI()


@app.get("/test")
def test(query: QueryParams = Depends()):
    return "hi"

uvicorn.run(app)

If I put it in the route function, it works:

from fastapi import FastAPI, Query, Depends
import uvicorn
from pydantic import BaseModel, Field
from typing import List


class QueryParams(BaseModel):
    name: str = Field(...)


app = FastAPI()


@app.get("/test")
def test(query: QueryParams = Depends(), ages: List[int] = Query([])):
    return "hi"

uvicorn.run(app)

Working UI

How can I get swagger UI to recognize a list query field in a basemodel with dependency injection?

>Solution :

As described in this answer, one can’t use a List field inside a Pydantic model and expect it to be a query parameter. The way to do this is to implement your query parameter-parsing in a separate dependency class, as shown below:

class QueryParams:
    def __init__(
        self,
        name: str,
        ages: List[int] = Query(...)
    ):
        self.name = name
        self.ages = ages
        
@app.get("/test")
def test(query: QueryParams = Depends()):
    return "hi"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading