python type_error ai_generated true

AttributeError: 'Request' object has no attribute 'json'

ID: python/fastapi-attributeerror-starlette-request-json

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-08-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Using request.json directly instead of await request.json() in async handlers.

generic

中文

在异步处理程序中使用 request.json 而不是 await request.json()。

Workarounds

  1. 95% success Use await request.json()
    @app.post('/data')
    async def handle(request):
        data = await request.json()
        return {'received': data}
  2. 90% success Use FastAPI's Body dependency
    from fastapi import Body
    @app.post('/data')
    async def handle(data: dict = Body(...)):
        return {'received': data}

Dead Ends

Common approaches that don't work:

  1. Using request.body() without await 70% fail

    Similar issue: body is a coroutine.

  2. Importing json module and parsing manually 50% fail

    Overcomplicates; Starlette provides built-in method.