Skip to main content

Add your description here

Project description

FastAPI Docs Exception

📖 Automatically surface your controllers exceptions in FastAPI’s Swagger / ReDoc docs

fastapi_docs_exception is a tiny helper that turns your own HTTPException subclasses into fully-documented responses with somes line of code. No more copy-pasting responses={404: {...}, 500: {...}} in every route – let the library build a shared responses mapping for you, complete with example payloads.

Swagger UI screenshot that shows custom 404 & 500 error examples

Swagger UI screenshot that shows custom 404 & 500 error examples


🚀 Installation

# With uv (recommended)
uv add fastapi_docs_exception

# Or the classic way
pip install fastapi_docs_exception

⚡ Quickstart

from fastapi import FastAPI, HTTPException
from fastapi_docs_exception.handler import ExceptionResponseFactory

# 1️⃣  Define your exceptions any way you like
class ApiNotFoundException(HTTPException):
    """Custom exception for API not found errors in FastAPI."""

    def __init__(self, detail: str = "API key not found or invalid"):
        super().__init__(status_code=404, detail=detail)


class NotFoundError(HTTPException):
    """Custom exception for not found errors in FastAPI."""

    def __init__(self, detail: str = "Resource not found in the storage"):
        super().__init__(status_code=404, detail=detail)


class InternalServerError(HTTPException):
    """Custom exception for internal server errors in FastAPI."""

    def __init__(self, detail: str = "Internal server error, please try again later"):
        super().__init__(status_code=500, detail=detail)

# 2️⃣  Feed them to the factory (class allow more flexibility)
# You can specify Pydantic schemas, edit the JSON schema, etc.
exc_response_factory = ExceptionResponseFactory()

app = FastAPI(
    responses=exc_response_factory.build([
        NotFoundError(),          # 404 section
        ApiNotFoundException(),   # 404 section (grouped with the previous one)
        InternalServerError(),    # 500 section (only one)
    ]),
)

# 3️⃣  Use your exceptions in the code
@app.get("/items/{item_id}")
def get_item(item_id: str):
    if item_id != "42":
        raise NotFoundError()
    return {"item_id": item_id}

Open http://localhost:8000/docs and you will see the custom 404 and 500 responses in the Swagger UI and ReDoc documentation with example payloads.

🔧 Development

# Clone
git clone https://github.com/your-user/fastapi_docs_exception.git
cd fastapi_docs_exception

# Optional: create a virtual env
uv venv          # makes .venv and activates it
source .venv/bin/activate

# Install dev dependencies (test, lint, type-checking)
uv pip install -e ".[dev]"

Lint, format, type-check (all in one)

uv run lint  # will use ruff lint, ruff format, ty

Run the test-suite

pytest

A coverage report will be shown in the terminal and htmlcov will be generated in the project root.

🤝 Contributing

All kinds of contributions are welcome – bug reports, feature ideas, docs fixes...

  1. Fork the repo & create your branch: git checkout -b feat/amazing-stuff
  2. Commit your changes with clear messages.
  3. Run uv run lint && uv run test and ensure everything stays green.
  4. Open a Pull Request describing why the change is useful.

Please use commitizen to format your commit messages, e.g. cz commit


📜 License

fastapi_docs_exception is distributed under the MIT License – see LICENSE for details.

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

fastapi_docs_exception-0.4.2.tar.gz (184.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_docs_exception-0.4.2-py3-none-any.whl (5.9 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_docs_exception-0.4.2.tar.gz.

File metadata

File hashes

Hashes for fastapi_docs_exception-0.4.2.tar.gz
Algorithm Hash digest
SHA256 1c7244c1a9c5fb19fc09300effd93998d50707d4fc4bf8fb4e9e839558978001
MD5 bf976dcc27d6a47e53582e169d36f778
BLAKE2b-256 5da4eb28d366960e01106ebdfe66fe8ce55b33e0e4cd0067ad1a4b78009a97d3

See more details on using hashes here.

File details

Details for the file fastapi_docs_exception-0.4.2-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_docs_exception-0.4.2-py3-none-any.whl
Algorithm Hash digest
SHA256 7cc3c04b4b9b7326d3502163e4fd11d5f213496cad8d3b099549835b9b3bde35
MD5 5510a01fe8697ffddc8bb632501b2e23
BLAKE2b-256 055edcc48418995f5ba53eed92d270508f150e5d5ae12ebd896cedab43ff3103

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page