How can I set a number of default values for many FastAPI endpoints

Viewed 1370

I am using FastAPI and I have a number of endpoints that look like this:

@app.get("/REDS/")
def query_REDS(   request: Request, lighter: Optional[bool] = False, darker: Optional[bool] = False, inverse: Optional[bool] = False, amount: Optional[int] = 10):
    pass # Work done here

@app.get("/BLUES/")
def query_BLUES(  request: Request, lighter: Optional[bool] = False, darker: Optional[bool] = False, inverse: Optional[bool] = False, amount: Optional[int] = 10):
    pass # Work done here

@app.get("/GREENS/")
def query_GREENS( request: Request, lighter: Optional[bool] = False, darker: Optional[bool] = False, inverse: Optional[bool] = False, amount: Optional[int] = 10):
    pass # Work done here

This looks like this in the swagger UI:

The real config is passed in the request and parsed manually. Whenever I need to update the signature of these endpoints, I need to update it in like 20 different places. Is there a way to define those specific default arguments in one place?

I tried using the pydantic BaseModel to define an input model:

class Arguments(BaseModel):
    lighter: Optional[bool] = False
    darker: Optional[bool] = False
    inverse: Optional[bool] = False
    amount: Optional[int] = 10

@app.get("/REDS/")
def query_REDS(   request: Request, arguments: Arguments):
    pass # Work done here

@app.get("/BLUES/")
def query_BLUES(  request: Request, arguments: Arguments):
    pass # Work done here

@app.get("/GREENS/")
def query_GREENS( request: Request, arguments: Arguments):
    pass # Work done here. 

But this is not what I am after, first of all because using a body in a get request is not recommended and not supported everywhere and second of all because it is not that useful in the swagger UI:

Is there a way to define a sort of default signature to a number of different enpoints?

1 Answers

To do what you want, you can use regular classes or pydantic models as class dependencies:

class CommonParams:
    def __init__(self, request: Request, lighter: Optional[bool] = False, darker: Optional[bool] = False, inverse: Optional[bool] = False, amount: Optional[int] = 10):
        self.request = request
        self.lighter = lighter
        self.darker = darker
        self.inverse = inverse
        self.amount = amount

class Arguments(BaseModel):
    lighter: Optional[bool] = False
    darker: Optional[bool] = False
    inverse: Optional[bool] = False
    amount: Optional[int] = 10

@app.get("/REDS/")
def query_REDS(params=Depends(CommonParams)):
    pass # Work done here

@app.get("/BLUES/")
def query_BLUES(params=Depends(Arguments)):
    pass # Work done here
Related