Skip to content

Awaiting request body in middleware blocks the application #394

@wyfo

Description

@wyfo

Describe the bug
Description in the title

To Reproduce
Minimal code:

from typing import Mapping

from fastapi import FastAPI
from starlette.requests import Request

app = FastAPI()

@app.middleware("http")
async def func(request: Request, call_next):
    print(await request.json())
    return await call_next(request)

@app.post("/")
def read_root(arg: Mapping[str, str]):
    return {"Hello": "World"}

Run the application with uvicorn <file>:app
Test the bug with curl localhost:8000 -d '{"status":"ok"}'

Expected behavior
The body of the request is printed, but the curl command stay pending for ever. If it is interrupted (Ctrl-C), the application then print ERROR: Error getting request body:

Environment:

  • OS: macOS
  • fastapi 0.33.0
  • python 3.7.3
  • (tested on Ubuntu too with Python 3.7.0 and 3.7.4)

Additional context

  • When the route function has no body argument (def read_root():), there is no problem : the body is printed and the response send.
  • Thinking the issue was maybe coming from Starlette, I tested the following code, which works without issue. The bug seems thus to come from fastapi
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse

app = Starlette()


@app.middleware("http")
async def func(request: Request, call_next):
    print(await request.json())
    return await call_next(request)


@app.route('/', methods=["POST"])
def homepage(request):
    return JSONResponse({"Hello": "World"})

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions