Menu

Clear JSON Errors in FastAPI: One Shape for Every Failure
📰

Clear JSON Errors in FastAPI: One Shape for Every Failure

DEV Community: fastapi·ByteBridge Talent LLC·1 day ago
#rE1ex0IN
#devtofastapi#devto#dev#error#code
Reading 0:00
15s threshold

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 0.161.0, Pydantic 2.14.1 and pytest 9.1.1 on Linux. Outputs are pasted from a single run.

Two words first

Exception: a Python error that stops the normal flow of code.

Exception handler: a function that catches one kind of exception and turns it into a response.

FastAPI lets you register a handler for each kind of exception. That is the whole trick.

The problem: two shapes by default

Here is a tiny app with no custom handlers.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.