β‘ 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)
β 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."
)
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.