Clear JSON Errors in FastAPI: One Shape for Every Failure
Updated: October 26, 2026 A phone app calls an API and gets an error. The app wants to show a short, kind message. But the error comes back in a shape the app did not expect, so it shows "undefined" instead. This happens a lot. FastAPI is easy to work with. Its default errors just do not all look alike. Below, every error gets one JSON shape, and a few tests check it. Tested with: Python 3.13.5,…
FastAPI, a popular Python web framework, can return errors with different JSON structures depending on the type of exception that occurs. When a developer does not provide custom exception handlers, FastAPI generates two distinct JSON error shapes for the same HTTP status code.
In the first error, the "detail" field contains a string, such as "Book not found". In the second error, the "detail" field holds a list of objects that describe the specific issue encountered. This discrepancy in error shapes can cause client code to struggle with handling errors consistently.
To address this issue, the author of the post introduces a single, uniform JSON error shape for all exceptions. This approach simplifies error handling for client code, as they would only need to check for a single "error" field with consistent keys. The chosen JSON shape consists of three main fields: "error", "status", "code", and "message".
The "status" field mirrors the HTTP status code, aiding in log analysis. The "code" field is an easily recognizable, stable string that remains constant across different errors. The "message" field is intended for human-readable error descriptions.
By implementing this consistent error shape, developers can avoid the need to handle multiple JSON structures for the same error code. This simplification enhances the maintainability and readability of API client code. Additionally, the post mentions that the Problem Details format (RFC 9457) is another viable option for providing a standardized JSON error structure for public APIs.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.