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 ServiceError and all other unhandled exceptions → structured APIErrorResponse JSON |
Consumer Feature Matrix (BaseService + ServiceError)
| Capability area | Common expectation | Actual support | How to use / notes |
|---|---|---|---|
| Request context access | Service can read current user and request id | ✅ Built-in | BaseService.current_user() and BaseService.current_request_id() |
| Service base class | Lightweight base for domain services | ✅ Built-in | Inherit from BaseService; inject repo/delegate dependencies in your constructor |
| Domain error taxonomy | Business errors map to consistent HTTP statuses | ✅ Built-in | Use NotFoundError (404), ConflictError (409), ValidationError (422), AuthorizationError (403), DownstreamError (502) |
| Structured API error responses | Service and unhandled exceptions become API error payloads | ✅ Built-in (with registration) | Register service_exception_handler for Exception |
| Per-error status override | Override default status code per raise | ✅ Built-in | raise ValidationError(..., status_code=409) |
| Error metadata | Include detail/code fields for clients | ✅ Built-in | detail and code are preserved by the handler |
| Logging integration | Auto logging from service methods | ⚙️ Via composition | Mix in csrd.logging.LoggingMixin; not part of BaseService itself |
| Transport-agnostic domain logic | Avoid HTTPException in business layer |
✅ Built-in pattern | Raise ServiceError subclasses and keep HTTP concerns in handler layer |
| Dependency injection wiring | FastAPI DI helper exists in package | ⚙️ Pattern-based | Use your own factory + Depends; package documents the pattern |
| Transactions / unit-of-work | Automatic transactional boundaries | ❌ Not built-in | Handle in repository/DB layer |
| Idempotency utilities | Built-in idempotency keys/replay protection | ❌ Not built-in | Implement per endpoint/service policy |
| Policy engine / RBAC framework | Full authorization policy runtime | ❌ Not built-in | Use claim checks in service code and/or external policy layer |
Dependency tier
Tier 1 (standalone) csrd.models · csrd.lifespan · csrd.context
Tier 2 (uses Tier 1) csrd.delegate csrd.repository csrd.service
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 service_exception_handler
from csrd.versioning import VersionedApiConfig
configure_versioned_api(
app,
version_mapping=VERSIONS,
config=VersionedApiConfig(
ex_handlers=[(Exception, service_exception_handler)],
),
)
Or on a plain FastAPI app:
app.add_exception_handler(Exception, 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
Metadata
Release files for csrd-service 0.7.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| csrd_service-0.7.0.tar.gz | 8.7 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| csrd_service-0.7.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 16.2 kB
Release files / csrd_service-0.7.0.tar.gz
| Download URL | csrd_service-0.7.0.tar.gz |
|---|---|
| Size | 8.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
98805cd51de681f951a38c2092aa756dd7cb2be9bc866f9ce675d11003ec623a
|
|
BLAKE2b-256 checksum How to use checksums |
76bf3427079894663c722b807d310b88ee2fd5101460b54c25a8d5dceb9b5ed4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 16, 2026.
Transparency logRelease files / csrd_service-0.7.0-py3-none-any.whl
| Download URL | csrd_service-0.7.0-py3-none-any.whl |
|---|---|
| Size | 7.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
496e2c96cae921a88b5e2273388e3fd024841b9dd8a498df5ac73b32373873bc
|
|
BLAKE2b-256 checksum How to use checksums |
e894bddbf066157649bef3f893d7488938be659a13557219731018b2e5043ca8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 16, 2026.
Transparency log