Victor
Victor

Reputation: 61

Dynamically creating get request taking query parameter list based on Pydantic schema

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

Upvotes: 1

Views: 527

Answers (1)

Josh
Josh

Reputation: 1976

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

Upvotes: 2

Related Questions