Skip to content

⚑ Quick Start

Get up and running with APIException in just a few minutes!

βœ… Install the Package

If you haven't done it yet, Let's first start by installing APIException from PyPI:

pip install apiexception

βœ… Register Exception Handlers

Add the register_exception_handlers to your FastAPI app to automatically handle and standardize your responses:

from APIException import register_exception_handlers
from fastapi import FastAPI

app = FastAPI()

register_exception_handlers(app=app)
That’s it! Your API now returns consistent success & error responses, and unexpected server errors are automatically logged with a clear JSON output.

βœ… Example Endpoint

Here’s a minimal example:

from fastapi import FastAPI, Path
from APIException import APIException, ExceptionStatus, register_exception_handlers, ResponseModel, APIResponse, BaseExceptionCode
from pydantic import BaseModel, Field

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 = Field(..., example=1, description="Unique identifier of the user")
    username: str = Field(..., example="Micheal Alice", description="Username or full name of the user")


# 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."
    )
The below gif demonstrates what actually the example code does.

Consistent Swagger Responses

Swagger UI will be well structured.

πŸ“š Next

βœ”οΈ Want to learn how to customize your responses?
Check out 🧩 Usage for response models, custom exception codes, and fallback middleware.

βœ”οΈ Need to fine-tune Swagger docs?
See πŸ“š Advanced for better documentation & logging tips.