{"id":27140365,"url":"https://github.com/barabum0/fastapi-enum-errors","last_synced_at":"2026-05-18T09:10:45.364Z","repository":{"id":284923946,"uuid":"956443392","full_name":"barabum0/fastapi-enum-errors","owner":"barabum0","description":"Addon for FastAPI that simplifies working with custom errors and allows you to operate on them as if they were values in an Enum.","archived":false,"fork":false,"pushed_at":"2025-04-20T17:32:40.000Z","size":41,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-20T18:35:02.675Z","etag":null,"topics":["enum","error","error-handling","fastapi","python"],"latest_commit_sha":null,"homepage":"https://pypi.org/project/fastapi_enum_errors/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/barabum0.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-03-28T09:09:20.000Z","updated_at":"2025-04-20T17:32:05.000Z","dependencies_parsed_at":null,"dependency_job_id":"2aac6735-b85a-490e-80f8-faf9d899cb66","html_url":"https://github.com/barabum0/fastapi-enum-errors","commit_stats":null,"previous_names":["barabum0/fastapi-enum-errors"],"tags_count":6,"template":false,"template_full_name":"barabum0/python-template-uv","purl":"pkg:github/barabum0/fastapi-enum-errors","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/barabum0%2Ffastapi-enum-errors","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/barabum0%2Ffastapi-enum-errors/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/barabum0%2Ffastapi-enum-errors/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/barabum0%2Ffastapi-enum-errors/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/barabum0","download_url":"https://codeload.github.com/barabum0/fastapi-enum-errors/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/barabum0%2Ffastapi-enum-errors/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279001778,"owners_count":26083173,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-09T02:00:07.460Z","response_time":59,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["enum","error","error-handling","fastapi","python"],"created_at":"2025-04-08T05:51:54.969Z","updated_at":"2025-10-09T16:43:31.455Z","avatar_url":"https://github.com/barabum0.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# FastAPI Enum Errors\n\n---\n\n[![Stable Version](https://img.shields.io/pypi/v/fastapi-enum-errors?color=blue)](https://pypi.org/project/fastapi-enum-errors/)\n[![Downloads](https://img.shields.io/pypi/dm/fastapi-enum-errors)](https://pypistats.org/packages/fastapi-enum-errors)\n[![Checked with mypy](https://www.mypy-lang.org/static/mypy_badge.svg)](https://mypy-lang.org/)\n[![Linting: Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)\n\n---\n\nA library for defining and handling HTTP errors in your FastAPI applications using Python enums. It lets you create\nstructured error definitions that automatically generate standardized JSON responses, API documentation, and even\ndetailed Markdown tables for error summaries.\n\n## Features\n\n- **Enum-Based Error Definitions:** Define HTTP errors as enum members with associated error codes and descriptions.\n- **Automatic JSON Response Generation:** Each error can build its own JSON body (optionally enhanced with extra\n  details).\n- **Custom Exception Conversion:** Easily convert enum errors into HTTP exceptions for FastAPI.\n- **FastAPI Responses Schema:** Build OpenAPI response definitions from your enum errors, with schema properties and\n  examples.\n- **Documentation Utilities:** Generate Markdown tables summarizing all defined errors.\n- **Automatic Docstring Integration:** Extract human-friendly error details from docstrings defined right after enum\n  members.\n\n## Installation\n\nInstall the package via pip:\n\n```bash\npip install fastapi-enum-errors\n```\n\n\u003e **Note:** This project requires [FastAPI](https://fastapi.tiangolo.com/), [httpx](https://www.python-httpx.org/),\n\u003e and [Pydantic](https://docs.pydantic.dev/) as peer dependencies.\n\n## Quick Start\n\nDefine your error responses and errors by extending the base classes provided by the library.\n\n### 1. Define a Custom Error Response Model\n\nYou can extend the built-in `ErrorResponse` model to add additional details to your error responses:\n\n```python\nfrom pydantic import Field\nfrom fastapi_enum_errors.models import ErrorResponse\n\n\nclass NotSoImportantErrorDetails(ErrorResponse):\n    some_ids: list[int] = Field(\n        examples=[[123, 456, 789]],\n        description=\"List of relevant IDs for the error context.\"\n    )\n```\n\n### 2. Define Your Error Enum\n\nExtend `ErrorEnum` to declare your project's errors. Use `auto()` for automatic error code generation and specify the\nHTTP status code for each error. The docstring for each member serves as the error description.\n\n```python\nfrom enum import auto\nfrom fastapi_enum_errors import ErrorEnum\n\n\nclass SomeErrors(ErrorEnum):\n    SOME_VERY_IMPORTANT_ERROR = (auto(), 404)\n    \"\"\"THIS ERROR IS VERY VERY IMPORTANT\"\"\"\n\n    NOT_SO_IMPORTANT_ERROR = (auto(), 500)\n    \"\"\"This error is not very important, but it has some additional details.\"\"\"\n\n    @classmethod\n    def error_response_models(cls) -\u003e dict:\n        # Map specific errors to their response models.\n        return {\n            cls.NOT_SO_IMPORTANT_ERROR: NotSoImportantErrorDetails,\n        }\n```\n\n### 3. Using the Enum in Your Application\n\nThe library automatically configures your application by including the built‑in helper function `errorenum_prepare_app`.\nYou just need to call it to ensure your FastAPI (or Starlette) application has the correct exception handler.\n\n#### a. Converting an Error to an Exception\n\nBelow is an example that shows how to raise an error:\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_enum_errors import errorenum_prepare_app\n\napp = FastAPI()\nerrorenum_prepare_app(app)\n\n\n@app.get(\"/example\")\nasync def example():\n    # Raise an enum error.\n    raise SomeErrors.SOME_VERY_IMPORTANT_ERROR.as_exception()\n\n@app.get(\"/example_2\")\nasync def example_2():\n    # Raise an enum error with additional fields.\n    raise SomeErrors.NOT_SO_IMPORTANT_ERROR.as_exception(some_ids=[1, 2, 3])\n\n# When these endpoints are hit, FastAPI will respond with a properly formatted JSON error body.\n```\n\n#### b. Asserting API Responses in Tests\n\nUse the `assert_response` method to verify that the HTTP response from your API matches the expected error format:\n\n```python\nimport httpx\n\n# Assert basic error.\nresponse = httpx.get(\"http://localhost:8000/example\")\nSomeErrors.SOME_VERY_IMPORTANT_ERROR.assert_response(response)\n\n# Assert basic error and check additional fields.\nresponse = httpx.get(\"http://localhost:8000/example_2\")\nSomeErrors.SOME_VERY_IMPORTANT_ERROR.assert_response(response, some_ids=[1, 2, 3])\n```\n\n#### c. Generating API Response Documentation\n\nAutomatically build the OpenAPI response specifications for an endpoint by calling:\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_enum_errors import errorenum_prepare_app\n\napp = FastAPI()\nerrorenum_prepare_app(app)\n\n\n@app.get(\n    \"/example\",\n    responses=SomeErrors.build_responses(\n        SomeErrors.SOME_VERY_IMPORTANT_ERROR,\n    ),\n)\nasync def example():\n    # Raise an enum error.\n    raise SomeErrors.SOME_VERY_IMPORTANT_ERROR.as_exception()\n\n@app.get(\n    \"/example_2\",\n    responses=SomeErrors.build_responses(\n        SomeErrors.NOT_SO_IMPORTANT_ERROR,\n    ),\n)\nasync def example_2():\n    # Raise an enum error with additional fields.\n    raise SomeErrors.NOT_SO_IMPORTANT_ERROR.as_exception(some_ids=[1, 2, 3])\n```\n\nThis returns a dictionary mapping HTTP status codes to response details, including:\n\n- A description combining the HTTP status phrase and error details.\n- A JSON schema for the error response.\n- Examples for documentation.\n\n#### d. Generating a Markdown Table Summary\n\nGenerate a Markdown table summarizing all errors defined in your enum:\n\n```python\ntable_md = SomeErrors.build_md_table_for_all_errors()\nprint(table_md)\n```\n\nExample output:\n\n| Error Code                  | Description                                                           | Status code                   |\n|-----------------------------|-----------------------------------------------------------------------|-------------------------------|\n| `some_very_important_error` | THIS ERROR IS VERY VERY IMPORTANT                                     | **404** Not Found             |\n| `not_so_important_error`    | This error is not very important, but it has some additional details. | **500** Internal Server Error |l\n\nThen, you can insert this table right into your documentation!\n\n#### e. Converting string to an error\n\nBelow is an example that shows how to convert string to an error\n\n```python\nSomeErrors.from_str(\"not_so_important_error\")\n# SomeErrors.NOT_SO_IMPORTANT_ERROR\n\n# This method is case-independent\nSomeErrors.from_str(\"NOt_sO_impORTant_eRROr\")\n# SomeErrors.NOT_SO_IMPORTANT_ERROR\n```\n\n## Contributing\n\nContributions are welcome! If you find any bugs or have feature requests, please open an issue or submit a pull request\non GitHub.\n\n## License\n\nDistributed under the MIT License. See `LICENSE` for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbarabum0%2Ffastapi-enum-errors","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbarabum0%2Ffastapi-enum-errors","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbarabum0%2Ffastapi-enum-errors/lists"}