Skip to main content

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!" }

Docshttp://localhost:8080/docs
Healthhttp://localhost:8080/health
OpenAPI JSONhttp://localhost:8080/openapi.json (also /openapi.yaml)
Metricshttp://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 concerns
  • Input / Output — DTOs with automatic OpenAPI schema generation via Pydantic Field()
  • Output.status_code — custom HTTP status codes per response
  • UseCaseException — 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.json and /openapi.yaml — raw spec download
  • Health check at GET /healthIETF Health Check Response Format
  • Prometheus metrics at GET /metricsPrometheus 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.typed marker (PEP 561)

Installation

pip install modular-api

With Uvicorn for api.serve():

pip install modular-api[serve]

Error handling

async def execute(self) -> None:
    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",
        )
    self._output = FoundUserOutput(name=user.name)

Testing

def test_hello_world():
    usecase = HelloWorld(HelloInput(name="World"))
    error = usecase.validate()
    assert error is None

    await usecase.execute()
    assert usecase.output.message == "Hello, World!"

See doc/testing_guide.md for the full testing guide.


License

MIT — see LICENSE.

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

macss_modular_api-0.4.2.tar.gz (35.7 kB view details)

Uploaded Source

Built Distribution

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

macss_modular_api-0.4.2-py3-none-any.whl (36.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: macss_modular_api-0.4.2.tar.gz
  • Upload date:
  • Size: 35.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.0

File hashes

Hashes for macss_modular_api-0.4.2.tar.gz
Algorithm Hash digest
SHA256 41b14e2c62a760529141debf5773b3f8dc9fec1bf0c54c02d0d990f4959e8366
MD5 28634d87778d84fda6d831cd0820bcac
BLAKE2b-256 6b38ea27448adb23ad79f69edd20c8e2076d18dfe85a48d1ec79a8a01659dae5

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for macss_modular_api-0.4.2-py3-none-any.whl
Algorithm Hash digest
SHA256 4a1702c6b862efec9b1b9734b4e148febafb3ab0f223905832d76614aa1a6380
MD5 3491badfb89617b35067e1b254b6b756
BLAKE2b-256 e8eadf0eddbfa5f9e8a32e28ed6be9d91c9f09d6a5d9e30af9a4c8ae7f3e65fe

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