Skip to content

Python SDK

namidb-cloud is the official Python client. It runs Cypher over the HTTP API and wraps the management API. The synchronous client uses only the standard library; the asyncio client needs httpx. Python 3.9+, Apache-2.0.

Terminal window
pip install namidb-cloud # sync client, no dependencies
pip install 'namidb-cloud[async]' # adds AsyncNamiDB (httpx)

The package for the cloud service is namidb-cloud (module namidb_cloud). The embedded engine you run yourself is a different package, namidb: see Python (self-hosted).

Quick start

from namidb_cloud import NamiDB
db = NamiDB() # reads NAMIDB_API_KEY (and NAMIDB_URL, default https://db.namidb.com)
db.query("movies", "CREATE (:Movie {id: $id, title: $title})", {"id": "m1", "title": "Heat"})
result = db.query("movies", "MATCH (m:Movie) RETURN m.title AS title ORDER BY title LIMIT $n", {"n": 10})
for row in result:
print(row["title"])
movies = db.database("movies") # bind one database
schema = movies.schema()

Async:

import asyncio
from namidb_cloud import AsyncNamiDB
async def main() -> None:
async with AsyncNamiDB() as db:
result = await db.query("movies", "MATCH (m:Movie) RETURN m.title AS title LIMIT 5")
print(result.rows)
asyncio.run(main())

NamiDB(api_key=None, url=None, timeout=90.0, max_retries=2)

ArgumentDefault
api_key$NAMIDB_API_KEYRequired; otherwise raises missing_api_key
url$NAMIDB_URL, then https://db.namidb.com
timeout90.0Seconds per socket operation; covers the longest plan query timeout plus a cold start
max_retries2Retries after the first attempt

AsyncNamiDB takes the same arguments plus http_client (an httpx.AsyncClient you manage). Both are context managers (close() / await aclose()). NamiDB is thread-safe and keeps one connection alive per thread.

Methods

db.query(database, cypher, params=None, *, idempotent=None, timeout=None)

Returns a QueryResult:

  • columns: list[str]
  • rows: list[dict], one dict per row keyed by column
  • write_outcome: WriteOutcome | None (nodes_created, edges_created, nodes_deleted, edges_deleted, properties_set)
  • request_id: str | None, quote it to support
  • engine_ms: float | None

Iterating a QueryResult yields its rows; len() is the row count. Values use the engine’s JSON encoding (nodes as {"_kind": "node", …}, relationships as {"_kind": "rel", …}, datetimes as RFC 3339 strings, bytes as base64, vectors as lists of floats). params must be JSON-serializable.

db.schema(database)

A Schema with constraints, indexes, labels, relationship_types and request_id; each constraint and index is a SchemaEntry (name, type, entity_type, labels_or_types, properties).

db.databases()

list[DatabaseInfo] (name, status) for the databases the key can reach.

db.running_queries(database) and db.cancel_query(database, query_id)

running_queries returns the statements running on the database right now, longest-running first, as list[RunningQuery] (id, protocol, statement, elapsed_ms). cancel_query stops one at its next cancellation check, and its client gets a cancelled error. Both need a read-write key (read_only_key otherwise), since statement text includes its literals. Cancelling a statement that is no longer running raises query_not_found.

from namidb_cloud import ErrorCode, NamiDBError
for q in db.running_queries("movies"):
if q.elapsed_ms > 60_000:
try:
db.cancel_query("movies", q.id)
except NamiDBError as err:
if err.code != ErrorCode.QUERY_NOT_FOUND:
raise

Listing is retried like a read and never wakes a sleeping database (it then has nothing running). A cancel is retried only when NamiDB refused it before it could take effect. Neither counts as a request. AsyncNamiDB has the same two methods.

db.database(name)

A handle with query, schema, running_queries, cancel_query, bulk_write, import_nodes and import_relationships bound to that database.

Bulk import

db.import_nodes("movies", people, label="Person", key="id",
on_progress=lambda done, total, batches: print(done, total))
res = db.import_relationships(
"movies", [{"from": 1, "to": 2, "since": 2020}],
rel_type="KNOWS", from_label="Person", from_key="id", to_label="Person", to_key="id",
) # res.linked counts rows whose two ends exist
db.bulk_write("movies", "UNWIND $rows AS row MERGE (m:Movie {title: row.title})", titles, idempotent=True)

Batches are cut at batch_rows (default 1,000) and batch_bytes (default 1 MiB), wait out rate_limited and engine_starting (max_rate_limit_retries, default 30), and split on payload_too_large. MERGE batches are retried like reads; CREATE batches are never resent after an ambiguous failure. The async client has the same methods.

Errors

Every failure raises NamiDBError: code (constants in ErrorCode), status (0 when no response arrived), message, request_id, retry_after, and neo4j_code / gql_status when the engine reported them.

from namidb_cloud import ErrorCode, NamiDB, NamiDBError
try:
db.query("movies", 'CREATE (:Movie {id: "m1"})')
except NamiDBError as err:
if err.code == ErrorCode.READ_ONLY_KEY:
... # this key can only read
elif err.code == ErrorCode.PLAN_LIMIT:
... # allowance used up: upgrade, or wait err.retry_after seconds
else:
raise

Every code: Errors.

Retries

Up to max_retries times, waiting for Retry-After when the server sends one (longer than 60 s is raised instead of waited), else exponential backoff with jitter from 0.5 s to 8 s.

Writes are never retried once they may have reached the engine. A query counts as a write when it contains a write clause (CREATE, MERGE, SET, DELETE, REMOVE, DROP, CALL, …). Writes are still retried when NamiDB refused them before the engine saw them (engine_starting, rate_limited, control_plane_unavailable) or when the request never got out. Override per call:

db.query("movies", "MERGE (:Movie {id: $id})", {"id": "m1"}, idempotent=True) # safe to repeat
db.query("movies", "MATCH (n) RETURN n", idempotent=False) # never repeat

Management API

ManagementClient uses a management token (nmdb_mgmt_…) against https://app.namidb.com/api/v1.

from namidb_cloud import ManagementClient
with ManagementClient() as mgmt: # reads NAMIDB_MANAGEMENT_TOKEN (and NAMIDB_MANAGEMENT_URL)
db = mgmt.databases.create("movies")
key = mgmt.api_keys.create("movies-app", role="read-only", databases=["movies"])
print(key.token) # the full API key, returned this once
backup = mgmt.backups.create("movies")
mgmt.restores.create(backup_id=backup.id, database_name="movies-copy")
mgmt.clones.create("movies", name="movies-staging", source="fresh_snapshot")
# The database as it was then (exact inside the plan's restore-point window).
pit = mgmt.restores.point_in_time("movies", at="2026-11-03T09:00:00Z", database_name="movies-tuesday")
# poll mgmt.clones.get(pit.id); pit.recovery_point and pit.recovery_source say what it holds
# A short-lived token for a CI job (admin scope; never broader or longer-lived than this one).
ci = mgmt.management_tokens.create("ci", scope="write", expires_at="2026-11-04T00:00:00Z")
print(ci.token) # shown this once
exp = mgmt.exports.create("movies") # poll mgmt.exports.get(exp.id) until "succeeded"
cypher = mgmt.exports.download(exp.id, "import.cypher")
mgmt.ip_allowlist.add("203.0.113.0/24", label="office")
for d in mgmt.databases.iter():
print(d.name, d.status, d.endpoints["http"])
ResourceMethods
mgmt.organization(), mgmt.usage()The token’s organization; this period’s usage
mgmt.databaseslist, iter, create(name), get(name), delete(name)
mgmt.backupslist(database), create(database), get(id)
mgmt.restorescreate(backup_id=, database_name=), point_in_time(database, at=, database_name=) (a point_in_time clone), get(id)
mgmt.clonescreate(database, name=, source=, at=) (latest_backup, fresh_snapshot, point_in_time), get(id)
mgmt.exportslist(database), create(database), get(id), download(id, file)
mgmt.ip_allowlistlist(api_key_id=), add(cidr, label=, api_key_id=), remove(id)
mgmt.api_keyslist, iter, create(name, role=, databases=, expires_at=), get, rotate(id, overlap_days=), revoke(id)
mgmt.management_tokenslist, iter, create(name, scope=, expires_at=) (the secret is in token, once), get(id), revoke(id); admin scope
mgmt.memberslist, iter, remove(user_id)
mgmt.invitationslist, create(email, role=), revoke(id)
mgmt.supportlist, iter, create(subject, body, category=, severity=, database=), get(number), reply(number, body)

Arguments: token, url, timeout (seconds, default 30), max_retries (default 2). Results are frozen dataclasses (ManagedDatabase, ApiKey, ManagementToken, Backup, Restore, Clone, Export, IpRule, SupportTicket, Usage, Member, Invitation); an API key’s or management token’s token is left out of its repr. list returns a Page (data, next_cursor); iter walks every page. Transient failures are retried with backoff, and every create sends an Idempotency-Key (fresh, or the idempotency_key= you pass) that its retries reuse.

Changelog

Release notes are in the package’s CHANGELOG.md on PyPI.