Addon for FastAPI that simplifies working with custom errors and allows you to operate on them as if they were values in an Enum.
Project description
from example import SomeErrors
FastAPI Enum Errors
A library for defining and handling HTTP errors in your FastAPI applications using Python enums. It lets you create structured error definitions that automatically generate standardized JSON responses, API documentation, and even detailed Markdown tables for error summaries.
Features
- Enum-Based Error Definitions: Define HTTP errors as enum members with associated error codes and descriptions.
- Automatic JSON Response Generation: Each error can build its own JSON body (optionally enhanced with extra details).
- Custom Exception Conversion: Easily convert enum errors into HTTP exceptions for FastAPI.
- FastAPI Responses Schema: Build OpenAPI response definitions from your enum errors, with schema properties and examples.
- Documentation Utilities: Generate Markdown tables summarizing all defined errors.
- Automatic Docstring Integration: Extract human-friendly error details from docstrings defined right after enum members.
Installation
Install the package via pip:
pip install fastapi-enum-errors
Note: This project requires FastAPI, httpx, and Pydantic as peer dependencies.
Quick Start
Define your error responses and errors by extending the base classes provided by the library.
1. Define a Custom Error Response Model
You can extend the built-in ErrorResponse model to add additional details to your error responses:
from pydantic import Field
from fastapi_enum_errors.models import ErrorResponse
class NotSoImportantErrorDetails(ErrorResponse):
some_ids: list[int] = Field(
examples=[[123, 456, 789]],
description="List of relevant IDs for the error context."
)
2. Define Your Error Enum
Extend ErrorEnum to declare your project's errors. Use auto() for automatic error code generation and specify the
HTTP status code for each error. The docstring for each member serves as the error description.
from enum import auto
from fastapi_enum_errors import ErrorEnum
class SomeErrors(ErrorEnum):
SOME_VERY_IMPORTANT_ERROR = (auto(), 404)
"""THIS ERROR IS VERY VERY IMPORTANT"""
NOT_SO_IMPORTANT_ERROR = (auto(), 500)
"""This error is not very important, but it has some additional details."""
@classmethod
def error_response_models(cls) -> dict:
# Map specific errors to their response models.
return {
cls.NOT_SO_IMPORTANT_ERROR: NotSoImportantErrorDetails,
}
3. Using the Enum in Your Application
The library automatically configures your application by including the built‑in helper function errorenum_prepare_app.
You just need to call it to ensure your FastAPI (or Starlette) application has the correct exception handler.
a. Converting an Error to an Exception
Below is an example that shows how to raise an error:
from fastapi import FastAPI
from fastapi_enum_errors import errorenum_prepare_app
app = FastAPI()
errorenum_prepare_app(app)
@app.get("/example")
async def example():
# Raise an enum error.
raise SomeErrors.SOME_VERY_IMPORTANT_ERROR.as_exception()
@app.get("/example_2")
async def example_2():
# Raise an enum error with additional fields.
raise SomeErrors.NOT_SO_IMPORTANT_ERROR.as_exception(some_ids=[1, 2, 3])
# When these endpoints are hit, FastAPI will respond with a properly formatted JSON error body.
b. Asserting API Responses in Tests
Use the assert_response method to verify that the HTTP response from your API matches the expected error format:
import httpx
# Assert basic error.
response = httpx.get("http://localhost:8000/example")
SomeErrors.SOME_VERY_IMPORTANT_ERROR.assert_response(response)
# Assert basic error and check additional fields.
response = httpx.get("http://localhost:8000/example_2")
SomeErrors.SOME_VERY_IMPORTANT_ERROR.assert_response(response, some_ids=[1, 2, 3])
c. Generating API Response Documentation
Automatically build the OpenAPI response specifications for an endpoint by calling:
from fastapi import FastAPI
from fastapi_enum_errors import errorenum_prepare_app
app = FastAPI()
errorenum_prepare_app(app)
@app.get(
"/example",
responses=SomeErrors.build_responses(
SomeErrors.SOME_VERY_IMPORTANT_ERROR,
),
)
async def example():
# Raise an enum error.
raise SomeErrors.SOME_VERY_IMPORTANT_ERROR.as_exception()
@app.get(
"/example_2",
responses=SomeErrors.build_responses(
SomeErrors.NOT_SO_IMPORTANT_ERROR,
),
)
async def example_2():
# Raise an enum error with additional fields.
raise SomeErrors.NOT_SO_IMPORTANT_ERROR.as_exception(some_ids=[1, 2, 3])
This returns a dictionary mapping HTTP status codes to response details, including:
- A description combining the HTTP status phrase and error details.
- A JSON schema for the error response.
- Examples for documentation.
d. Generating a Markdown Table Summary
Generate a Markdown table summarizing all errors defined in your enum:
table_md = SomeErrors.build_md_table_for_all_errors()
print(table_md)
Example output:
| Error Code | Description | Status code |
|---|---|---|
some_very_important_error |
THIS ERROR IS VERY VERY IMPORTANT | 404 Not Found |
not_so_important_error |
This error is not very important, but it has some additional details. | 500 Internal Server Error |
Then, you can insert this table right into your documentation!
e. Converting string to an error
Below is an example that shows how to convert string to an error
SomeErrors.from_str("not_so_important_error")
# SomeErrors.NOT_SO_IMPORTANT_ERROR
# This method is case-independent
SomeErrors.from_str("NOt_sO_impORTant_eRROr")
# SomeErrors.NOT_SO_IMPORTANT_ERROR
Contributing
Contributions are welcome! If you find any bugs or have feature requests, please open an issue or submit a pull request on GitHub.
License
Distributed under the MIT License. See LICENSE for more information.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastapi_enum_errors-0.2.2.tar.gz.
File metadata
- Download URL: fastapi_enum_errors-0.2.2.tar.gz
- Upload date:
- Size: 25.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: uv/0.6.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
abd25f254b79efaa4b4745ac241ce4fd9edc4f6956697431916dd32c61b57e9d
|
|
| MD5 |
816fd93409185ad2c019b7257ca5ead5
|
|
| BLAKE2b-256 |
4bd1f6bd4b9b025f2e0a5d3b98d4d7c9791c229efacb65adf3440222bf53c4ad
|
File details
Details for the file fastapi_enum_errors-0.2.2-py3-none-any.whl.
File metadata
- Download URL: fastapi_enum_errors-0.2.2-py3-none-any.whl
- Upload date:
- Size: 9.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: uv/0.6.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5e038225859bd3899be2cba6ecfe6bce46a9216c80b74c43e7ac3a2e34b03ce4
|
|
| MD5 |
f77a6bedcd910f3a1e81b0b07568b8a5
|
|
| BLAKE2b-256 |
b8f86ffdcdbd8afe846c4e85d2b2339f8f233c82bf96ef6a89eaecc52c0e684f
|