Skip to main content

GenesisDB client for Python

The official client for GenesisDB, the open source event sourcing database. Synchronous and asynchronous clients, fully typed, one dependency (httpx), Python 3.9+.

Version 2.0.0 targets GenesisDB 2.0 and is not compatible with GenesisDB 1.x servers or with the 1.x client API. Routes, configuration, type names and method signatures have changed. Keep a 1.x client for a 1.x server.

Existing 1.x clients keep working against a GenesisDB 2.0 server, which still serves the unchanged 1.x API under /api/v1, so the server can be upgraded first and the clients at your own pace. New 2.0 features (stored events returned by commit, upper bounds, schemas, typed errors) need this 2.0.0 client.

pip install genesisdb-client

Quick start

import os
from genesisdb import Client

db = Client(url="http://localhost:8080", token=os.environ["GENESISDB_AUTH_TOKEN"])

db.commit([
    {"source": "io.example.shop", "subject": "/customer/42", "type": "io.example.shop.customer-registered", "data": {"name": "Bruce Wayne"}},
])

events = db.fetch("/customer/42")

url and token fall back to GENESISDB_URL and GENESISDB_AUTH_TOKEN, so Client() works in an environment that sets both. The client is a context manager, with Client() as db: closes the connection pool on exit.

Events

# Commit a batch atomically. The server assigns ID, time and hashes and returns the stored events.
stored = db.commit([
    {"source": "io.example.shop", "subject": "/order/1", "type": "io.example.shop.order-placed", "data": {"total": 99.5}},
    {"source": "io.example.shop", "subject": "/order/1/item/1", "type": "io.example.shop.item-added", "data": {"sku": "A1", "qty": 2}},
])
stored[0].id    # "3f2c..."
stored[0].hash  # "a9b1..."
stored[0].time  # datetime with timezone

# A subject with one segment gets a generated ID appended.
db.commit([{"source": "io.example.shop", "subject": "/customer", "type": "io.example.shop.customer-registered", "data": {"name": "Selina"}}])

# Fetch a subject with all descendants, in commit order.
all_events = db.fetch("/order/1")

# Resume after a known event, or stop at one.
since = db.fetch("/order", {"lowerBound": last_seen_id, "includeLowerBoundEvent": False})
until = db.fetch("/order", {"upperBound": some_id, "includeUpperBoundEvent": True})

# Only the newest event of a type below the subject.
latest = db.fetch("/order/1", {"latestByEventType": "io.example.shop.order-placed"})

Events are frozen dataclasses with the CloudEvents attribute names (source, subject, type, id, time, data, hash, predecessorhash, ...).

Preconditions

Preconditions are checked atomically with the commit. A failed precondition raises PreconditionFailedError and writes nothing.

from genesisdb import PreconditionFailedError, is_subject_new, is_query_result_true

try:
    db.commit(
        [{"source": "io.example.shop", "subject": "/customer/42", "type": "io.example.shop.customer-registered", "data": {"email": "bruce@example.com"}}],
        [
            is_subject_new("/customer/42"),
            is_query_result_true("STREAM e FROM events WHERE e.data.email == 'bruce@example.com' MAP COUNT() == 0"),
        ],
    )
except PreconditionFailedError as error:
    print(error.precondition_type, error.reason)  # "isSubjectNew" "subject /customer/42 already has events"

Helpers: is_subject_new, is_subject_existing, is_query_result_true.

Subscriptions

subscribe is a generator over Server-Sent Events. It yields the existing history first, then new events as they are committed, and runs until you stop iterating.

for event in db.subscribe("/order", interval=0.5):
    print(event.type, event.data)
    if should_stop:
        break

interval is the poll interval in seconds (default 1). The bound options of fetch work here as well, so a consumer that persists the last processed event ID resumes with options={"lowerBound": ...}.

Queries

GDBQL runs on the server. Results come back as rows, a bare aggregate as a single-element list.

rows = db.query("STREAM e FROM events WHERE e.subject UNDER '/customer' MAP { name: e.data.name, total: e.data.total }")

[count] = db.query("STREAM e FROM events WHERE e.type == 'io.example.shop.order-placed' MAP COUNT()")

by_category = db.query(
    "STREAM e FROM events WHERE e.type == 'io.example.shop.item-added' GROUP BY e.data.category "
    "MAP { category: e.data.category, items: COUNT(), revenue: SUM(e.data.total) }"
)

GDPR: reference payloads and erasure

Store a payload as reference data and it can be erased later. The event, its hash and the chain stay intact, the payload becomes {}.

db.commit([
    {
        "source": "io.example.shop",
        "subject": "/customer/42",
        "type": "io.example.shop.customer-registered",
        "data": {"name": "Bruce", "email": "bruce@example.com"},
        "options": {"storeDataAsReference": True},
    },
])

db.erase("/customer/42")  # administrator token

Inline payloads are immutable. erase on a subject without reference payloads raises UnprocessableError (422).

Schemas

db.register_schema("io.example.shop.order-placed", {
    "type": "object",
    "properties": {"total": {"type": "number"}, "currency": {"type": "string"}},
    "required": ["total"],
})

schemas = db.schemas()

Commits of that type are validated. A violation raises GenesisDBError with status 400.

Catalog, status, administration

db.subjects()          # ["/customer", "/order"]
db.types()             # ["io.example.shop.customer-registered", ...]
db.status()            # Status(version=..., event_count=..., ready=True, ...)
db.ping()              # "Pong", no token required

db.audit()             # "Audit passed. All 1234 events integrity checks succeeded."

Audit, erase and schema registration need the administrator token. Everything else works with a reader token (GENESISDB_READ_TOKEN), commit additionally with a writer token.

Async

AsyncClient has the same methods, awaited. subscribe is an async generator.

import asyncio
from genesisdb import AsyncClient

async def main():
    async with AsyncClient() as db:
        await db.commit([{"source": "app", "subject": "/order/1", "type": "order.placed", "data": {"total": 10}}])
        async for event in db.subscribe("/order"):
            print(event.id)

asyncio.run(main())

Errors

Every non-2xx answer raises GenesisDBError with status, body and operation. Subclasses: PreconditionFailedError (412, with precondition_type and reason), AuthenticationError (401, 403), NotFoundError (404), ConflictError (409), UnprocessableError (422), NotReadyError (503). A subscription that the server ends with an error raises GenesisDBError from the generator.

Configuration

Client(
    url="http://localhost:8080",  # or GENESISDB_URL
    token="...",                  # or GENESISDB_AUTH_TOKEN
    timeout=30.0,                 # seconds, for non-streaming calls, None disables
    http=httpx.Client(...),       # optional, bring your own httpx client (proxies, TLS, retries)
)

Development

python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
pytest tests/test_client.py                                                  # unit tests against a mocked server
GENESISDB_URL=http://localhost:8080 GENESISDB_AUTH_TOKEN=... pytest tests/test_integration.py   # against a running GenesisDB

License

MIT

Metadata

Release files for genesisdb-client 2.0.0

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

Source distribution (sdist)

Source distribution for genesisdb-client 2.0.0
File Size Uploaded Provenance Actions
genesisdb_client-2.0.0.tar.gz 13.9 kB With provenance Details for genesisdb_client-2.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for genesisdb-client 2.0.0
File Interpreter ABI Platform Actions
genesisdb_client-2.0.0-py3-none-any.whl Python 3 none any Details for genesisdb_client-2.0.0-py3-none-any.whl

Total release size: 25.5 kB

Release files / genesisdb_client-2.0.0.tar.gz

Download URL genesisdb_client-2.0.0.tar.gz
Size 13.9 kB
Tags Source
SHA-256 checksum
How to use checksums
4cc363cab79cac72f2782d9495e117eeedb29e49ad90bf716fc673f403554f9e
BLAKE2b-256 checksum
How to use checksums
69dda6f5c2541bac7c92a800f9ea00eb9c92493012ead16903ed779169ffd827
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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

Transparency log

Release files / genesisdb_client-2.0.0-py3-none-any.whl

Download URL genesisdb_client-2.0.0-py3-none-any.whl
Size 11.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f04658ceaa603e61b722c033c4fc3db1ee663703a2ec6cd0e256fec76e409c86
BLAKE2b-256 checksum
How to use checksums
13a7324fac25f45e1f175313d78a1ab86dda0dd195cbabb3bdce5e5a458e5b61
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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

Transparency log

Security for genesisdb-client 2.0.0

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 genesisdb_client-2.0.0.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 29, 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

2.0.0 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