Fastapi: ERROR: Error getting request body

Created on 18 Jun 2020  路  3Comments  路  Source: tiangolo/fastapi

Example

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}

Description


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:
  • Program blocked

Environment

  • OS: [e.g. Linux / Windows / macOS]: macOS
  • FastAPI Version [e.g. 0.3.0]: 0.54.1
  • Python version: Python 3.7.4
question

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.

All 3 comments

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:

Was this page helpful?
0 / 5 - 0 ratings