Skip to main content

domainkit, a domain-driven FastAPI framework

domainkit

A Django-style framework for domain-driven FastAPI services. It provides:

  • settings modules and installed domains
  • manage.py commands and migrations
  • DDD building blocks, with the layer rules between them enforced
  • several databases: domains routed to their own, sharding by key, PostgreSQL range partitioning, and immudb ledgers for evidence
  • caches in memory or in Redis and Valkey (one server, Sentinel, or Cluster), with stampede protection, and rate limits shared by every replica, globally or per route
  • answers in the caller's language (English and Arabic ship), times shown in the business's time zone, and numbers and dates in local formats
  • file storage and uploads checked by their content, under names the storage makes
  • background work through a transactional outbox, run by polling workers or through RabbitMQ, with queues for separate worker pools
  • users, groups, and permissions per content type, as in Django's contrib.auth: password hashing and rules, backends, object permissions, and a swappable user model; token or JWT authentication, and route rules as in Django REST framework
  • optional apps for reliable messaging, audit trails, idempotent requests, tamper-evident evidence, signed outgoing webhooks, feature flags, and privacy requests (export, erasure, and retention)
pip install "domainkit[postgres]"     # the extras are listed below

The extras: postgres, sqlite (database drivers); argon2, jwt, mfa (passwords, JSON Web Tokens, and second factors for contrib.auth); immudb (ledgers); redis (shared caches and rate limits); rabbitmq (the worker's broker); metrics, tracing (Prometheus and OpenTelemetry); uploads (multipart forms); httpclient (outgoing HTTP calls); webhooks; testing (the pytest plugin); tzdata (time zones where the system has none); uvloop and granian (a faster event loop, and a server).

Documentation

  • docs/tutorial.md: from pip install to an authenticated endpoint with one aggregate, every command run in CI

  • docs/reference.md: settings, middleware, errors, the API surface (OpenAPI, versions, deprecations), observability, testing, commands, and extension points

  • docs/databases.md: several databases, routing, sharding, partitioning, and ledgers

  • docs/queries.md: querying repositories, pages, filters, soft delete, row locks, and savepoints

  • docs/resources.md: aggregates over REST: resource routes, commands and queries, derived schemas, partial changes, ETags and conditional writes, field policies, nesting, the generators, and the generic admin

  • docs/runtime.md: how async work runs (event loops, background tasks, clean contexts, logging off the loop, finding blocking code, free-threaded Python, the shutdown budget, readiness, event-handler timeouts, workers and the outbox), running under load (request deadlines, load shedding, database timeouts and PgBouncer, outgoing HTTP calls), and servers

  • docs/cache.md: caches in memory, Redis, and Valkey, and shared rate limits

  • docs/contrib.md: messaging (and workers on RabbitMQ), webhooks, audit and records' history, idempotency, evidence, and feature flags

  • docs/auth.md: users, groups, permissions, content types, passwords, backends, tokens, route rules, and the admin API

  • docs/mail.md: email, mail templates, text messages, and push notifications, sent through the outbox

  • docs/i18n.md: responses in the caller's language, time zones, and number and date formats

  • docs/uploads.md: file storages, receiving uploads, and serving files

  • docs/live.md: WebSockets and Server-Sent Events, bounded and re-authorized while open, and committed events streamed live

  • docs/privacy.md: exporting and erasing a person's data, and retention

  • docs/testing.md: the pytest plugin: test databases, sync and async clients, factories, a clock to freeze, and query counts

  • docs/performance.md: what a request costs, the benchmark ladder CI gates on, and how to make requests cheaper

  • docs/versioning.md: compatibility, deprecations, releases, and which releases get security fixes

  • docs/threat-model.md: what domainkit protects, where the trust boundaries are, what it does at each, and what is left to a project

  • docs/audit/0.9.0.md: the 0.9.0 audit's findings that the CHANGELOG names, with their status

  • docs/api.md: the public API, module by module, one line a name

  • docs/adr/: the decisions behind the design

  • CHANGELOG.md and SECURITY.md

Quick start

python3.13 -m venv .venv && . .venv/bin/activate
pip install "domainkit[postgres,sqlite,testing]"
domainkit init billingAPI billing     # the name sets the variable prefix: BILLING_API_*
cd billing
python manage.py check
python manage.py startdomain invoices --aggregate Invoice   # installs and mounts it
python manage.py makemigrations -m "create invoices" && python manage.py migrate
read -rsp "Password: " PASSWORD && export PASSWORD    # admin's, typed, not echoed
BILLING_API_SUPERUSER_PASSWORD="$PASSWORD" \
  python manage.py createsuperuser --noinput --username admin --email admin@example.com
unset PASSWORD                        # so that no later process inherits it
pytest
python manage.py runserver            # http://127.0.0.1:8000/docs

Then, from a second shell in billing with the same environment active, log in, typing the same password, and list the invoices. The password is read at a prompt and sent on standard input, so it is in no command line and no shell history:

read -rsp "Password: " PASSWORD && export PASSWORD
TOKEN=$(python -c "import json, os; print(json.dumps({'username': 'admin', 'password': os.environ['PASSWORD']}))" \
  | curl -s http://127.0.0.1:8000/auth/login -H "Content-Type: application/json" -d @- \
  | python -c "import json, sys; print(json.load(sys.stdin)['access_token'])")
unset PASSWORD
curl http://127.0.0.1:8000/api/v1/invoices/invoices -H "Authorization: Bearer $TOKEN"

The answer is the first page, empty: {"items":[],"next_cursor":null}. The domain's router is mounted at /api/v1/invoices, and its resource is /invoices within it; startdomain prints both commands for the domain it made. A route the caller may not reach answers 404, as an unknown path does, so check the path first (/docs lists every route). createsuperuser without options asks for each value instead. docs/tutorial.md goes on from here: a resource created, changed, and refused by its rules.

domainkit init creates a project that passes check and its tests as it is. Users, groups, and permissions are installed, requests are authenticated, and every route must say who may call it: generated domains need their model permissions, and /auth and /admin/auth log users in and manage them (docs/auth.md).

billing/
  pyproject.toml          the name, dependencies, and the pytest plugin
  manage.py
  .env                    selects config.settings.local on this machine
  .gitignore
  src/config/settings/    base, local, test, and production settings
  src/config/urls.py      the root router: mount each domain's router here
  src/config/asgi.py      the application, for uvicorn
  src/domains/            the bounded contexts
  tests/test_health.py

The production settings read BILLING_API_ALLOWED_HOSTS, BILLING_API_DATABASE_URL, and BILLING_API_TRUSTED_PROXIES (the load balancers' networks, or empty) from the environment, and the deployment checks refuse to start without them, or without verified TLS to the database. They also turn the API docs off, send HSTS for a year, and limit each caller to 300 requests a minute; BILLING_API_API_DOCS, BILLING_API_SECURE_HSTS_SECONDS, and BILLING_API_RATE_LIMIT change that.

Serve it with one worker process per core, each on its own event loop: uvicorn config.asgi:application --workers 4 --loop uvloop, or Granian (pip install 'domainkit[granian]'). docs/reference.md gives the whole command with its limits, and docs/performance.md how many cores a load needs.

Developing domainkit

poetry install --all-extras            # Python 3.13
pre-commit install                     # after: pipx install pre-commit

poetry run ruff check . && poetry run ruff format --check . && poetry run mypy
poetry run deptry .                    # every imported package is declared
poetry run pytest --cov                # random order, 2 minutes a test; coverage gate in pyproject.toml
poetry run mutmut run "domainkit.http*" && poetry run mutmut results

Without servers, the database tests use SQLite, the Redis and RabbitMQ tests use in-memory fakes, and the tests that need PostgreSQL, immudb, or a real Redis, Valkey, or RabbitMQ are skipped. Point them at throwaway servers to run them; each test cleans up after itself:

docker run -d --rm --name domainkit-postgres -e POSTGRES_PASSWORD=postgres \
  -p 127.0.0.1:55432:5432 postgres:18-alpine
docker run -d --rm --name domainkit-redis -p 127.0.0.1:56379:6379 redis:8-alpine
DOMAINKIT_TEST_POSTGRES_URL=postgresql+asyncpg://postgres:postgres@127.0.0.1:55432/postgres \
DOMAINKIT_TEST_REDIS_URL=redis://127.0.0.1:56379/0 \
  poetry run pytest

The other variables (immudb, Redis over TLS, Valkey, RabbitMQ) are listed at the top of domainkit_tests/test_immudb.py, test_redis.py, and test_rabbitmq.py. Each run must cover 98%; CI also combines the runs with and without servers, which must cover 100%. To check that locally, run pytest --cov once without and once with the servers, each with its own COVERAGE_FILE, then coverage combine and coverage report --fail-under=100.

CI (.github/workflows/ci.yml) runs on every push and pull request:

  • lint, strict typing, and deptry: every package the code imports is declared
  • the tests on Python 3.13 and 3.14
  • the tests again against PostgreSQL 18, immudb with TLS and a signing key, Redis 8 (plain and TLS), Valkey 9, and RabbitMQ 4 (plain and TLS); no test may be skipped there
  • coverage of both runs combined, which must be 100%
  • the benchmark ladder: Python calls and database round trips per request, against budgets (python -m benchmarks; docs/performance.md)
  • a wheel build, installed and imported in a clean environment, and its CycloneDX bill of materials
  • Semgrep's Python and OWASP Top 10 rules, pip-audit, and a gitleaks scan of the whole history
  • on pull requests and weekly, the tests again with the newest releases the dependency ranges allow, not the lock's, and with the oldest

A full mutation testing run happens weekly, in 17 shards that run side by side; each writes its score and the mutants no test caught to its job summary. Releases are published to PyPI from a version tag; see docs/versioning.md.

License

MIT; see LICENSE.

Metadata

Release files for domainkit 0.9.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for domainkit 0.9.3
File Size Uploaded Provenance Actions
domainkit-0.9.3.tar.gz 799.5 kB With provenance Details for domainkit-0.9.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for domainkit 0.9.3
File Interpreter ABI Platform Actions
domainkit-0.9.3-py3-none-any.whl Python 3 none any Details for domainkit-0.9.3-py3-none-any.whl

Total release size: 1.8 MB

Release files / domainkit-0.9.3.tar.gz

Download URL domainkit-0.9.3.tar.gz
Size 799.5 kB
Tags Source
SHA-256 checksum
How to use checksums
5a61b0dbe4110d6c5fc4c1bf2b91574e903a5f96610fea3132d8cc5389fbcf90
BLAKE2b-256 checksum
How to use checksums
3264ebab3132b66eca5cefbafe4d9115eb1103942ab9783d92e8caa0db32630b
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 26, 2026.

Transparency log

Release files / domainkit-0.9.3-py3-none-any.whl

Download URL domainkit-0.9.3-py3-none-any.whl
Size 990.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
56d881386df62d2bb4a8468426714f4c1ac4294416868df5521ccbf55060b526
BLAKE2b-256 checksum
How to use checksums
145cf66b49703007f7007ad7a7b6c16e3c1740b2e0c3b0847997b1ad5fe73e60
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 26, 2026.

Transparency log

Security for domainkit 0.9.3

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for domainkit-0.9.3.tar.gz

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 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.9.3 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page