1

According to https://fastapi.tiangolo.com/tutorial/middleware/, we could apply a FastAPI Middleware on async def endpoints.

Currently I have several non-async def endpoints, how to apply FastAPI Middleware on non-async def endpoint? If I still register an async Middleware, will it work for the non-async def endpoint ?

For example:


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

Will the Middleware work properly if call_next is a non-async def method ?

Thank you.

Chris
  • 18,724
  • 6
  • 46
  • 80
zhfkt
  • 2,415
  • 3
  • 21
  • 24
  • Yes, because the call_next will be a coroutine created by Starlette. Your “sync” endpoints are executed in a thread pool and ran as async methods/functions. – JarroVGIT Jan 06 '23 at 14:51
  • @JarroVGIT Thank you for replying. Just curious where could I find the tutorial of `“sync” endpoints are executed in a thread pool and ran as async methods/functions`. It is a new concept for me. – zhfkt Jan 06 '23 at 15:28

1 Answers1

1

A coroutine is created based on any synchronous function. So yes, this will work fine for you. You can read more about this here.

JarroVGIT
  • 4,291
  • 1
  • 17
  • 29