1

I'm able to get requests like this with query parameters of a type list like this:

@router.get("/findStuff")
def get_stuff(a: List[int] = Query(None), b: List[str] = Query(None)):
    return {'a': a, 'b': b}

But I'm not sure how I'd do this dynamically from an arbitrary Pydantic schema? When I do this, the query params are interpreted as a request body and cannot be processed from the OpenAPI doc. Is there a way to get the same behavior from above without explicitly specifying each query param in the method arguments?

class MySchema(BaseModel):
    a: List[int] = Query(None)
    b: List[str] = Query(None)

@router.get("/findStuff")
def get_stuff(inputs: MySchema = Depends()):
    return inputs

1 Answer 1

2

The FastAPI documentation outlines how you can declare classes as dependencies.

An example based on the code you provided in your question:

import uvicorn
from typing import List
from fastapi import FastAPI, Depends, Query

app = FastAPI()

class MySchema:
    def __init__(self, a: List[int] = Query(None), b: List[str] = Query(None)):
        self.a = a
        self.b = b

@app.get("/findStuff")
def get_stuff(inputs: MySchema = Depends()):
    return inputs

if __name__ == "__main__":
    uvicorn.run(app='main:app', host='127.0.0.1', port=8000)

If you navigate to the documentation (/docs endpoint), you can see the query paramaters for that route:

example API docs

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Similar to this, I found that using a dataclass instead of a Pydantic schema works.
no problem! if this was useful to you, please consider accepting this answer.
Hi @Josh, How can we define the parameters in redoc documentation request sample?

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.