python data_error ai_generated true

fastapi.exceptions.HTTPException: 422: Unprocessable Entity - json_invalid: JSON decode error

ID: python/fastapi-body-not-json

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-11-21First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

The request Content-Type is application/json but the body is malformed JSON (trailing comma, single quotes, empty body).

generic

中文

请求 Content-Type 为 application/json,但请求体是格式错误的 JSON(尾随逗号、单引号、空体)。

Workarounds

  1. 93% success
    import json
    body = json.dumps({'name': 'x'})
    requests.post(url, data=body, headers={'Content-Type': 'application/json'})
  2. 95% success
    requests.post(url, json={'name': 'x'})

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Accepting non-JSON violates the API contract.

  2. 90% fail

    FastAPI then rejects because the endpoint expects a Pydantic body.