I would like to implement a logic where every API endpoint will have its API Credits (int
), which I am going to use in an HTTP middleware to deduct credits from the user's balance.
I have searched a lot but have been unable to find any solution. Could anyone help me to achieve this? I am providing a pseudo-code to explain what I am trying to achieve.
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
# here I want to read API credits for request
print(request.api_credit)
response = await call_next(request)
return response
@app.post("/myendpoint1")
async def myendpoint1():
# define api credit for this endpoint
api_credit = 2
return {"message": "myendpoint"}
@app.post("/myendpoint2")
async def myendpoint2():
# define api credit for this endpoint
api_credit = 5
return {"message": "myendpoint2"}
As demonstrated in this answer, as well as here and here, one could use
request.state
to store arbitrary state and pass data between middlewares and FastAPI endpoints. Please refer to those answers for more details.Working Example