Skip to main content

A simple package to easily handle and document all HTTP exceptions and other errors in a FastAPI app.

Project description

FastAPI Easy Responses

A simple package to easily handle and document all HTTP exceptions and other errors in a FastAPI app.

Installation

uv add fastapi-easy-responses
pip install fastapi-easy-responses

Usage

# main
from fastapi_easy_responses import register_custom_exceptions
app = FastAPI()
register_custom_exceptions(app) # 1.

# exceptions
from fastapi_easy_responses import CustomAppException
class DuplicateItemError(CustomAppException): # 2.
    status_code = 409
    description = "Duplicate item already exists"

# crud
async def create_item(session: AsyncSession, item: Item) -> Item:
    try:
        session.add(item)
        await session.commit()
        await session.refresh(item)
        return item
    except IntegrityError as e:
        await session.rollback()
        raise DuplicateItemError() from e # 3.

# router
from fastapi_easy_responses import get_responses
@router.post(
    "",
    response_model=ItemRead,
    status_code=201,
    responses=get_responses(DuplicateItemError), # 4.
)
async def create_item_endpoint(item: ItemCreate, session: AsyncSession):
    db_item = Item.model_validate(item)
    return await create_item(session, db_item) # 5.

This gives you a centralized, more consistent and easier-to-maintain exception handling and documentation.

Note the following:

  1. Call register_custom_exceptions(app) to activate the centralized exception handler for CustomAppExceptions.
  2. Inherit your exception class from CustomAppException, and provide the required status_code and description as class variables: as such, these are static per exception class, not dynamic per raise. You'll use this exception class everywhere.
  3. Raise your exception in any operation.
  4. Use the same exception class to generate the OpenAPI documentation. No magic numbers and strings needed, so you have proper autocomplete.
  5. No need to manually catch and convert your exception to HTTPException, the centralized exception handler does it for you. Or more precisely, it returns the same JSONResponse as the default exception handler for HTTPException would.

Why

For comparison, this is something like what you would usually do in a FastAPI app.

# exceptions
class DuplicateItemError(ValueError):
    pass

# crud
async def create_item(session: AsyncSession, item: Item) -> Item:
    try:
        session.add(item)
        await session.commit()
        await session.refresh(item)
        return item
    except IntegrityError as e:
        await session.rollback()
        raise DuplicateItemError("An item with this name already exists.") from e

# router
@router.post(
    "",
    response_model=ItemRead,
    status_code=201,
    responses={
        409: {"model": Message, "description": "An item with this name already exists."}
    }
)
async def create_item_endpoint(item: ItemCreate, session: AsyncSession):
    try:
        db_item = Item.model_validate(item)
        return await create_item(session, db_item)
    except DuplicateItemError as e:
        raise HTTPException(status_code=409, detail=str(e)) from e

Which means you have to manually maintain all the original exception to HTTPException mappings. If you forget it, your unhandled exception will raise a generic internal server error. It also requires additional manual work to provide consistent documentation.

Similar packages

There are similar packages with similar purpose, like

This package is simpler for basic use-cases, which may or may not be what you want. This package doesn't introduce new response schemas, custom error codes, doesn't provide logging (yet); but gives you the least amount of code you have to write.

License

MIT

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_easy_responses-0.1.0.tar.gz (3.2 kB view details)

Uploaded Source

Built Distribution

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

fastapi_easy_responses-0.1.0-py3-none-any.whl (4.2 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_easy_responses-0.1.0.tar.gz.

File metadata

  • Download URL: fastapi_easy_responses-0.1.0.tar.gz
  • Upload date:
  • Size: 3.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.16 {"installer":{"name":"uv","version":"0.11.16","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for fastapi_easy_responses-0.1.0.tar.gz
Algorithm Hash digest
SHA256 80439a25481fc39ae233470167ef131b280beb569665403c6f35687df3a981d4
MD5 08e7f5161769ec5f03a06f29b69194e9
BLAKE2b-256 eb46ca9b0146d564b8985ccf4416bcaaf0c6ccfd0abedd2b139aa6797557bfb5

See more details on using hashes here.

File details

Details for the file fastapi_easy_responses-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: fastapi_easy_responses-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 4.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.11.16 {"installer":{"name":"uv","version":"0.11.16","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for fastapi_easy_responses-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c875d26470bac35541c29d35b62e949f142a8443f3fd6c57586ab01c69d71792
MD5 6b44eada4f48e86d3cb15085253c05ff
BLAKE2b-256 33fb70660d45b66d4e17c0b993cefcda797fca143479a166736f9d4fdc426a23

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