Skip to main content

Service layer base class with domain error hierarchy

Project description

csrd.service

Service-layer boilerplate for the CSRD pattern (Controller → Service → Repository / Delegate).

What it provides

Component Purpose
BaseService Lightweight base class with per-class logger and request-context accessors (current_user(), current_request_id())
ServiceError Base domain exception — keeps business logic free of HTTPException
NotFoundError 404 — resource doesn't exist
ConflictError 409 — duplicate, version mismatch, etc.
ValidationError 422 — business-rule validation (not schema validation)
AuthorizationError 403 — authenticated user lacks permission
DownstreamError 502 — a delegate call to another service failed
service_exception_handler FastAPI handler that maps any ServiceError → structured APIErrorResponse JSON

Dependency tier

Tier 1 (standalone)     csrd.models · csrd.lifespan · csrd.context
Tier 2 (uses Tier 1)    csrd.delegate · csrd.repository · csrd.service  ← NEW
Tier 3 (uses Tier 1+2)  csrd.versioning

csrd.service depends on csrd.context and csrd.models only. It does not import csrd.repository or csrd.delegate — your services accept those as constructor params.

Quick start

from csrd.service import BaseService, NotFoundError, DownstreamError


class OrderService(BaseService):
    def __init__(self, repo: OrderRepository, payments: PaymentsDelegate):
        super().__init__()
        self._repo = repo
        self._payments = payments

    async def get_order(self, order_id: int) -> Order:
        order = await self._repo.get_by_id(order_id)
        if order is None:
            raise NotFoundError("Order not found", detail=f"order_id={order_id}")
        return order

    async def place_order(self, cart: Cart) -> Order:
        order = await self._repo.create(cart)
        try:
            await self._payments.charge(order)
        except Exception as exc:
            raise DownstreamError("Payment failed", cause=exc) from exc
        return order

Register the exception handler

With csrd.versioning:

from csrd.service import ServiceError, service_exception_handler
from csrd.versioning import VersionedApiConfig

configure_versioned_api(
    app,
    version_mapping=VERSIONS,
    config=VersionedApiConfig(
        ex_handlers=[(ServiceError, service_exception_handler)],
    ),
)

Or on a plain FastAPI app:

app.add_exception_handler(ServiceError, service_exception_handler)

Wire into FastAPI DI

from functools import cache
from typing import Annotated
from fastapi import Depends

@cache
def order_service_factory(repo: OrderRepository, payments: PaymentsDelegate):
    return OrderService(repo, payments)

OrderServiceDep = Annotated[OrderService, Depends(order_service_factory)]

# In your endpoint:
@router.get("/orders/{order_id}")
async def get_order(service: OrderServiceDep, order_id: int):
    return await service.get_order(order_id)

Installation

uv add csrd-service  # or: pip install csrd-service

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

csrd_service-0.1.44.tar.gz (7.5 kB view details)

Uploaded Source

Built Distribution

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

csrd_service-0.1.44-py3-none-any.whl (6.5 kB view details)

Uploaded Python 3

File details

Details for the file csrd_service-0.1.44.tar.gz.

File metadata

  • Download URL: csrd_service-0.1.44.tar.gz
  • Upload date:
  • Size: 7.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for csrd_service-0.1.44.tar.gz
Algorithm Hash digest
SHA256 2decdf839e1e7d620445a230759ecd6994b46affd365cfb8270c047f7df53d10
MD5 a17f71936a48a4384d01f92564741ec5
BLAKE2b-256 e737109d56ac7f9811b3632269d2bf958c2756bc62f3d4f8236f3673f03f5e93

See more details on using hashes here.

Provenance

The following attestation bundles were made for csrd_service-0.1.44.tar.gz:

Publisher: release.yml on csrd-api/fastapi-common

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file csrd_service-0.1.44-py3-none-any.whl.

File metadata

  • Download URL: csrd_service-0.1.44-py3-none-any.whl
  • Upload date:
  • Size: 6.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for csrd_service-0.1.44-py3-none-any.whl
Algorithm Hash digest
SHA256 751e955e6fdf6c8f183219327fcfb0b9f1be4ff00e4dd9f80e50631f53cade63
MD5 68908abb87742d837049f329ad5c6546
BLAKE2b-256 288d196ef1334290b6c7d3395b582cf25e0ce7aa3bc1d464ef4f9d8f4c301aae

See more details on using hashes here.

Provenance

The following attestation bundles were made for csrd_service-0.1.44-py3-none-any.whl:

Publisher: release.yml on csrd-api/fastapi-common

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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