FastAPI : Adding a custom middleware to specific endpoints / path operations

31 Views Asked by At

I am new to Python and FASTAPI. I would like to add custom middleware only to specific endpoints / path operations. Currently the middleware is getting executed for all the requests.

I tried to filter the request method and path and later did some operations on the same ( but not able to avoid execution of the middleware). code for reference:

@app.middleware('http')
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    items = request.items()
    path = ''
    for k,i in items:
        if k == 'path':
            path = i
            break
    if path == '/users' and request.method == 'GET':
        process_time = time.time() - start_time
        response.headers['X-Process-Time'] = str(process_time)
    return response
  1. Is there a way to set the middleware execute for certain type of requests? Or is it by design Middleware should be executed for all the requests

  2. Should we use dependencies (which will be tied to the specific request) for such cases as mentioned in point 1.

Wanted to understand the production level design for these cases. Please help me understand.

Thanks!!!

0

There are 0 best solutions below