python data_error ai_generated true

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

ID: python/fastapi-request-body-malformed-json

Also available as: JSON · Markdown · 中文
80%Fix Rate
89%Confidence
0Evidence
2024-12-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

客户端发送的请求体不是有效的 JSON,或者 Content-Type 不是 application/json。

generic

中文

客户端发送的请求体不是有效的 JSON,或者 Content-Type 不是 application/json。

Workarounds

  1. 90% success
    from pydantic import BaseModel
    class Item(BaseModel):
        name: str
    @app.post('/items')
    async def create(item: Item):
        return item
  2. 95% success
    import requests
    requests.post(url, json={'name': 'test'})

Dead Ends

Common approaches that don't work:

  1. 60% fail

    FastAPI 可能仍然尝试解析 JSON,导致错误。

  2. 70% fail

    原始数据可能不是 JSON,解析仍会失败。