Here's a self-contained, minimal, reproducible, example with my use case:
from fastapi import FastAPI, Body
from pydantic import BaseModel
from fastapi.requests import Request
app = FastAPI()
class Name(BaseModel):
name: str
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
body = await request.body()
print(f"Body: {body}")
response = await call_next(request)
return response
@app.post('/')
def root(name: Name):
return {"hello": name.name}
curl -X POST "http://127.0.0.1:8000/" -H "accept: application/json" -H "Content-Type: application/json" -d '{"name": 111}'
* ERROR: Error getting request body:
If I understood this correctly the last time this came up, awaiting the request body in the middleware consumes it, which means it becomes unusable after. You can try the solution proposed here as a workaround (no time to test it myself currently).
For an even better approach, you can look into https://github.com/tiangolo/fastapi/pull/589, or into the documentation version of that pull request.
@IgnatovFedor Thanks
Thanks for the help here @igotinfected ! :clap: :bow:
Thanks for reporting back and closing the issue @fishs-x :+1:
Most helpful comment
If I understood this correctly the last time this came up,
awaiting the request body in the middleware consumes it, which means it becomes unusable after. You can try the solution proposed here as a workaround (no time to test it myself currently).For an even better approach, you can look into https://github.com/tiangolo/fastapi/pull/589, or into the documentation version of that pull request.