Skip to main content

from example import SomeErrors

FastAPI Enum Errors


Stable Version Downloads Checked with mypy Linting: Ruff


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.

Metadata

Release files for fastapi_enum_errors 0.2.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi_enum_errors 0.2.2
File Size Uploaded Provenance
fastapi_enum_errors-0.2.2.tar.gz 25.5 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for fastapi_enum_errors 0.2.2
File Interpreter ABI Platform
fastapi_enum_errors-0.2.2-py3-none-any.whl Python 3 none any Details

Total release size: 34.4 kB

Release files / fastapi_enum_errors-0.2.2.tar.gz

Download URL fastapi_enum_errors-0.2.2.tar.gz
Size 25.5 kB
Tags Source
SHA-256 checksum
How to use checksums
abd25f254b79efaa4b4745ac241ce4fd9edc4f6956697431916dd32c61b57e9d
BLAKE2b-256 checksum
How to use checksums
4bd1f6bd4b9b025f2e0a5d3b98d4d7c9791c229efacb65adf3440222bf53c4ad
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.6.14

Release files / fastapi_enum_errors-0.2.2-py3-none-any.whl

Download URL fastapi_enum_errors-0.2.2-py3-none-any.whl
Size 9.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5e038225859bd3899be2cba6ecfe6bce46a9216c80b74c43e7ac3a2e34b03ce4
BLAKE2b-256 checksum
How to use checksums
b8f86ffdcdbd8afe846c4e85d2b2339f8f233c82bf96ef6a89eaecc52c0e684f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.6.14

Security for fastapi_enum_errors 0.2.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page