APIException: Standardised Exception Handling for FastAPI¶
β‘ Quick Installation¶
Download the package from PyPI and install it using pip:
pip install apiexception
Just import the register_exception_handlers
function from APIException
and call it with your FastAPI app instance to set up global exception handling:
from APIException import register_exception_handlers
from fastapi import FastAPI
app = FastAPI()
register_exception_handlers(app=app)
Now all your endpoints will return consistent success
and error
responses, and your Swagger docs will be beautifully documented.
Exception handling will be logged, and unexpected errors will return a clear JSON response instead of FastAPIβs default HTML error page.
π See It in Action!¶
from fastapi import FastAPI, Path
from APIException import APIException, ExceptionStatus, register_exception_handlers, ResponseModel, APIResponse, BaseExceptionCode
from pydantic import BaseModel
app = FastAPI()
# Register exception handlers globally to have the consistent
# error handling and response structure
register_exception_handlers(app=app)
# Create the validation model for your response
class UserResponse(BaseModel):
id: int
username: str
# Define your custom exception codes extending BaseExceptionCode
class CustomExceptionCode(BaseExceptionCode):
USER_NOT_FOUND = ("USR-404", "User not found.", "The user ID does not exist.")
INVALID_API_KEY = ("API-401", "Invalid API key.", "Provide a valid API key.")
PERMISSION_DENIED = ("PERM-403", "Permission denied.", "Access to this resource is forbidden.")
@app.get("/user/{user_id}",
response_model=ResponseModel[UserResponse],
responses=APIResponse.default()
)
async def user(user_id: int = Path()):
if user_id == 1:
raise APIException(
error_code=CustomExceptionCode.USER_NOT_FOUND,
http_status_code=401,
)
data = UserResponse(id=1, username="John Doe")
return ResponseModel[UserResponse](
data=data,
description="User found and returned."
)
When you run your FastAPI app and open Swagger UI (/docs
),
your endpoints will display clean, predictable response schemas like this:
- Successful API Response?¶
{
"data": {
"id": 7,
"username": "John Doe"
},
"status": "SUCCESS",
"message": "Operation completed successfully.",
"error_code": null,
"description": "User fetched successfully."
}
- Error API Response?¶
{
"data": null,
"status": "FAIL",
"message": "User not found.",
"error_code": "USR-404",
"description": "The user ID does not exist."
}
- π’ 200: Success responses are clearly documented with your data model.
- π 401/403: Custom error codes & messages show exactly what clients should expect.
- π No more guesswork β your consumers, frontend teams, and testers see exactly how your API behaves for success and error cases.
- β
Bonus: Even
unexpected server-side issues
β like database errors, unhandled exceptions, or third-party failures β still return a consistent JSON response that follows your ResponseModel schema. No more raw HTML 500 pages! Every error is logged automatically so you always have a clear trail of what went wrong.
This is how APIException helps you build trustable, professional APIs from day one!
π₯ Who should use this?¶
β
FastAPI developers who want consistent success & error responses.
β
Teams building multi-client or external APIs.
β
Projects where Swagger/OpenAPI docs must be clear and human-friendly.
β
Teams that need extensible error code management.
If youβre tired of:
-
Inconsistent response structures,
-
Confusing Swagger docs,
-
Messy exception handling,
-
Finding yourself while trying to find the exception that isn't logged
-
Backend teams asking βWhat does this endpoint return?β,
-
Frontend teams asking βWhat does this endpoint return in error?β,
then this library is for you.
π― Why did I build this?¶
After 4+ years as a FastAPI backend engineer, Iβve seen how crucial a clean, predictable response model is.
When your API serves multiple frontends or external clients, having different JSON shapes, missing status info, or undocumented error codes turns maintenance into chaos.
So, this library:
β
Standardizes all success & error responses,
β
Documents them beautifully in Swagger,
β
Provides a robust ExceptionCode pattern,
β
Adds an optional global fallback for unexpected crashes β all while keeping FastAPIβs speed.
β¨ Core Principles¶
β’ π Consistency: Success and error responses always follow the same format.
β’ π Clear Docs: OpenAPI/Swagger stays clean and human-friendly.
β’ πͺΆ Zero Boilerplate: Register once, use everywhere.
β’ β‘ Extensible: Fully customizable error codes & handlers.
π Next Steps¶
Ready to integrate? Check out: - π Installation β How to set up APIException.
-
β‘ Quick Start β Add it to your project in minutes.
-
π§© Usage β Response models, custom codes, and fallback middleware.
-
π Advanced β Swagger integration, logging, debugging.
-
π API Reference β Full reference docs.