Question

FastAPI returns 422 for a request that Postman accepts

Solved · 365 viewsasked by marco_py

Frontend sends JSON, gets 422. Postman with the same body: 200.

What I’ve tried

Compared the bodies byte by byte in the network tab. Identical.

Comment

2 answers

Marked as helpful by the asker
olu_backend

Identical bodies, different headers. Your frontend sends Content-Type: text/plain (fetch does that for string bodies without a header), so FastAPI does not parse JSON. Add headers: { 'Content-Type': 'application/json' }. The 422 body tells you: value is not a valid dict.

Comment
Content-Type. Embarrassing, I teach this. marco_py
grace_mw

For the next 422: log what FastAPI actually rejected. The default response body is easy to miss in the network tab, a handler puts it in your server log:

@app.exception_handler(RequestValidationError)
async def log_422(request, exc):
    logger.warning("422 on %s: %s", request.url.path, exc.errors())
    return JSONResponse(status_code=422, content={"detail": exc.errors()})

The loc field says exactly which part failed: ["body"] for the whole body means it wasn't parsed as JSON at all.

Comment
Added to our template project. Would have saved me the embarrassment. marco_py