Fastapi: [QUESTION] How to pass parameters to call_next in the middleware

Created on 7 Jun 2020  路  8Comments  路  Source: tiangolo/fastapi

First check

  • [x] I used the GitHub search to find a similar issue and didn't find it.
  • [x] I searched the FastAPI documentation, with the integrated search.
  • [x] I already searched in Google "How to X in FastAPI" and didn't find any information.

Description

I have a middleware that extracts the token from the request's header. If the token was valid, the middleware should get the user_id from jwt token and pass it to the function that should be called next (using call_next).
How can I pass parameters to the function that will be called with call_next?

@app.middleware("http")
async def check_token_validity(request: Request, call_next):
    try:
        id_token = request.headers["authorization"].split(" ")[1]
        decoded_token = auth.verify_id_token(id_token)
        uid = decoded_token['uid']
        response = await call_next(request)
        return response
    except:
        return JSONResponse(
            content = jsonable_encoder({"detail": "Unauthorized"}),
            status_code = 401,
        )
answered question

All 8 comments

You can do something like:

request.state.uid = decoded_token['uid']
response = await call_next(request)

Reference: https://www.starlette.io/requests/

Thanks for the help here @Kludex ! :clap: :bow:

If that solves the original problem, then you can close this issue @saeedesmaili :heavy_check_mark:

Team,
I have tried to access uuid property set in Middleware as explained about. No Luck

In Middleware I have set

request.state.uuid = uuid.uuid4()

In the method
print(Request.state) Result is : --
print(Request.state.uuid) AttributeError: 'property' object has no attribute 'uuid'

print(Request.state._state['uuid']) AttributeError: 'property' object has no attribute '_state'

am I referencing in the wrong way?

Why is your Request a capital R? That is a class name rather than the parameter request.

Here is both methods

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
request.state.uuid = uuid.uuid4()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response

@app.get("/welcome")

def read_root1():
print(Request.state)
print(Request.state._state['suuid'])
print(Request.state.uuid)
return {"Hello": "Welcome"}

This is how to use Request in your path operation: https://fastapi.tiangolo.com/advanced/using-request-directly/#use-the-request-object-directly

Thanks @phy25 :clap: :bow:

@eaiesb if you still have problems, please create a new issue following the template, that will make it easier to help you :bug: :heavy_check_mark:

My problem did resolve. Thanks.

Was this page helpful?
0 / 5 - 0 ratings