title: FastAPI middleware peeking into responses
body: <p>I try to write a simple middleware for FastAPI peeking into response bodies.</p>
  
  <p>In this example I just log the body content:</p>
  
  <pre class="lang-py prettyprint-override"><code>app = FastAPI()
  
  @app.middleware("http")
  async def log_request(request, call_next):
      logger.info(f'{request.method} {request.url}')
      response = await call_next(request)
      logger.info(f'Status code: {response.status_code}')
      async for line in response.body_iterator:
          logger.info(f'    {line}')
      return response
  </code></pre>
  
  <p>However it looks like I "consume" the body this way, resulting in this exception:</p>
  
  <pre><code>  ...
    File ".../python3.7/site-packages/starlette/middleware/base.py", line 26, in __call__
      await response(scope, receive, send)
    File ".../python3.7/site-packages/starlette/responses.py", line 201, in __call__
      await send({"type": "http.response.body", "body": b"", "more_body": False})
    File ".../python3.7/site-packages/starlette/middleware/errors.py", line 156, in _send
      await send(message)
    File ".../python3.7/site-packages/uvicorn/protocols/http/httptools_impl.py", line 515, in send
      raise RuntimeError("Response content shorter than Content-Length")
  RuntimeError: Response content shorter than Content-Length
  </code></pre>
  
  <p>Trying to look into the response object I couldn't see any other way to read its content. What is the correct way to do it?</p>