title: How to use middleware with routing in FastAPI
body: <p>I am following the FastAPI documentation <a href="https://fastapi.tiangolo.com/" rel="nofollow noreferrer">here</a> and trying to implement routing with a middleware.
  My main contains:</p>
  
  <pre><code>app = FastAPI()
  
  
  app.include_router(
      SomeService.router,
      prefix="/services",
      tags=["services"]
  )
  
  
  @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
  </code></pre>
  
  <p>When sending a request, it is correctly executed and returns the right value but does not contain the value appended through the middleware.</p>
  
  <p>I have tried defining the middleware inside the service route
  and defining the middleware before app.include_router</p>