I want my fastapi routes to include a dependency injection formed from the parameters of a CLI.
In the skeleton code below, a, b and c are the CLI parameters, Consort is the DI and the fastapi class is King.
How can this be achieved?
import charles, william, george #program modules
from fastapi import FastAPI, Depends
app = FastAPI()
class Consort:
def __init__(self, a, b, c):
self.x = a_stuff(a)
self.y = b_stuff(b)
self.z = c_stuff(c)
class King:
def __init__(self, a, b, c):
... ...
@router.post("/create")
async def create(self, consort=Depends(Consort())):
return charles.create()
@router.post("/read")
async def read(self, consort=Depends(Consort())):
return william.read()
@router.post("/update")
async def update(self, consort=Depends(Consort())):
return george.update()
@router.post("/delete")
async def delete(self, consort=Depends(Consort())):
return elizabeth.delete()
def main(args):
a, b, c = arg_parse()
service = King(a, b, c)
uvicorn.run(... ... ...)
return
if __name__ == "__main__":
main(sys.argv)
Depends
. It requires a callable (e.g.Consort
) not a class instance (e.g.Consort()
). Also, you can’t use@router
on a class method as explained in #63854313 – Blandina