Use-case-centric toolkit for building modular APIs with Starlette. Define UseCase classes (input → validate → execute → output), connect them to HTTP routes, and expose OpenAPI documentation automatically.
Project description
modular-api
Use-case-centric toolkit for building modular APIs with Starlette.
Define UseCase classes (input → validate → execute → output), connect them to HTTP routes, and get automatic OpenAPI documentation.
Also available in Dart: modular_api · TypeScript: @macss/modular-api
Quick start
from modular_api import ModularApi, ModuleBuilder
# ─── Module builder (separate file in real projects) ──────────
def build_greetings_module(m: ModuleBuilder) -> None:
m.usecase("hello", HelloWorld)
# ─── Server ───────────────────────────────────────────────────
api = ModularApi(base_path="/api")
api.module("greetings", build_greetings_module)
api.serve(port=8080)
curl -X POST http://localhost:8080/api/greetings/hello \
-H "Content-Type: application/json" \
-d '{"name":"World"}'
{ "message": "Hello, World!" }
Docs → http://localhost:8080/docs
Health → http://localhost:8080/health
OpenAPI JSON → http://localhost:8080/openapi.json (also /openapi.yaml)
Metrics → http://localhost:8080/metrics (opt-in)
See example/example.py for the full implementation including Input, Output, UseCase with validate(), and the builder.
Features
UseCase[I, O]— pure business logic, no HTTP concernsInput/Output— DTOs with automatic OpenAPI schema generation via PydanticField()Output.status_code— custom HTTP status codes per responseUseCaseException— structured error handling (status_code, message, error_code, details)ModularApi+ModuleBuilder— module registration and routing- Constructor-based unit testing with fake dependency injection
cors_middleware— built-in CORS support- Scalar docs at
/docs— auto-generated from registered use cases - OpenAPI spec at
/openapi.jsonand/openapi.yaml— raw spec download - Health check at
GET /health— IETF Health Check Response Format - Prometheus metrics at
GET /metrics— Prometheus exposition format - Structured JSON logging — Loki/Grafana compatible, request-scoped with trace_id
- All endpoints default to
POST(configurable per use case) - Full type annotations with
py.typedmarker (PEP 561)
Installation
pip install modular-api
With Uvicorn for api.serve():
pip install modular-api[serve]
Error handling
async def execute(self) -> FoundUserOutput:
user = await repository.find_by_id(self.input.user_id)
if not user:
raise UseCaseException(
status_code=404,
message="User not found",
error_code="USER_NOT_FOUND",
)
return FoundUserOutput(name=user.name)
Testing
async def test_hello_world():
usecase = HelloWorld(HelloInput(name="World"))
error = usecase.validate()
assert error is None
output = await usecase.execute()
assert output.message == "Hello, World!"
See doc/testing_guide.md for the full testing guide.
License
MIT — see LICENSE.
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file macss_modular_api-0.4.5.tar.gz.
File metadata
- Download URL: macss_modular_api-0.4.5.tar.gz
- Upload date:
- Size: 35.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
beca40d53f4e374e7ce4eab37aa7f77a78d39481c1e5592ae7d68c56316ca585
|
|
| MD5 |
397be5a3552363c438f995a414ed4c73
|
|
| BLAKE2b-256 |
945f91d6d64732b51df72211cc98e9ca172addb4dd0a3b7a97c69c6ce9609949
|
File details
Details for the file macss_modular_api-0.4.5-py3-none-any.whl.
File metadata
- Download URL: macss_modular_api-0.4.5-py3-none-any.whl
- Upload date:
- Size: 35.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d1b223fbd00662c7514fcae79ab2c45d2caa2ee33833b5c12b04a007831dce7e
|
|
| MD5 |
ba886c9a212b7d9bed6e987d275e7df1
|
|
| BLAKE2b-256 |
b2dbdbf612cabd0914952013c5577a53a61117740caa0454ad98d7bd9a1c0a07
|