MantisBase has been a C++ project from day one, and for a while that meant two ways in: embed it from C++, or talk to it over its HTTP API. Today there is a third: you can now run it from Python with a single command:
pip install mantisbaseThe Python bindings embed the MantisBase server inside your process and expose the same services the C++ API does: routing, SQL, entity CRUD, schemas, auth, files, settings, logs, realtime, and mail. This post walks through that flow end to end. The full reference lives in the Python bindings docs, which currently list v0.4.9.
Install
Published wheels cover CPython 3.10 to 3.14 on Linux (x86-64 and aarch64), Windows x86-64, and macOS (arm64 and x86-64). Windows ARM64 wheels start at 3.11. Each wheel vendors libmantisbase, so pip install is all you need. Python 3.9 can build the extension from source but has no published wheel.
One thing to know before you start the server: in production, start() refuses to serve when MB_JWT_SECRET is empty, has the same behaviour as the native C++ run, and the process exits. For local work, pass dev=True. For anything else, pass secret_key (or export MB_JWT_SECRET before creating the app).
A first app
Here is a small notes API. It creates a schema, adds two routes, and starts the server.
import mantisbase
app = mantisbase.App(port=8080, data_dir="./data", dev=True)
if not app.has_entity("notes"):
app.create_schema({
"name": "notes",
"type": "base",
"fields": [
{"name": "title", "type": "string", "required": True},
{"name": "body", "type": "string"},
],
"rules": {
"list": {"mode": "public"},
"get": {"mode": "public"},
"add": {"mode": "auth"},
"update": {"mode": "auth"},
"delete": {"mode": ""},
},
})
@app.router.get("/notes/{id}")
def read_note(req, res):
note = app.entity("notes").read(req.path_param("id"))
if note is None:
res.json(404, {"error": "Note not found"})
return
res.json(200, note)
@app.router.post("/notes", middlewares=[mantisbase.middlewares.get_auth_token()])
def create_note(req, res):
created = app.entity("notes").create(req.json())
res.json(201, created)
app.start()The schema dict has the same shape as the REST schema body. The has_entity guard is there because create_schema raises a MantisError on a duplicate name, which you would hit the second time the script runs.
The App constructor takes snake_case keywords: port, host, data_dir, db_type (sqlite3, or postgresql ), db_url, public_dir, scripts_dir, templates_dir, migrations_dir, pool_size, dev, skip_admin_setup and secret_key. Any other keyword is ignored, including the camelCase names used by the Node bindings.
Routing and middleware
Paths use {param} placeholders, and each verb (get, post, put, patch, delete) works as a decorator. A handler can take (req, res), (req), or nothing at all. If it returns anything other than None, that value is sent as JSON with status 200:
@app.router.get("/hello")
def hello():
return {"message": "Hello, World!"}When you need another status or want to write the response yourself, call res.json(status, data) and return None.
Middleware comes in two flavours. mantisbase.middlewares exposes the same C++ middleware the HTTP API uses: get_auth_token(), require_admin(), require_guest(), require_expr(expr), rate_limit(max_requests, window_seconds) and friends. You can also write your own in Python as (req, res) -> bool. Return True or None to continue, or False after writing a response to stop the chain. An exception becomes an HTTP 500 and stops the chain.
The request and response objects cover what you would expect. On req you get path_param, query_param, header, cookie, bearer_token, json(), and multipart helpers such as parse_form and write_files. On res you get json, text, html, send, empty, redirect, set_file, set_header and auth cookie helpers. One rule worth remembering: req and res are only valid for the duration of the handler or middleware that received them.
Entities and SQL
app.entity(name) gives you a table with create, read, update, remove, count, list and list_page. Listing is cursor-based: pass pagination.limit (1 to 500, default 50) and pagination.after (the id of the last row from the previous page), plus an equality filter.
page = app.entity("notes").list_page({
"pagination": {"limit": 20, "after": last_id},
"filter": {"title": "Hello"},
})This returns {"items", "has_more"}. One important detail: entity CRUD checks the schema and talks to the database directly, and it does not re-run HTTP access rules. Call it from a route whose own middleware has already decided who is allowed in.
For raw SQL, app.db.query takes named parameters and returns a list of dicts. Transactions are a context manager that commits on a clean exit and rolls back on an exception:
with app.db.transaction() as tx:
tx.query(
"UPDATE notes SET title = :title WHERE id = :id",
{"title": "Renamed", "id": note_id},
)Auth
app.auth issues and verifies JWTs, and it also owns API keys and OAuth.
token = app.auth.create_token({"id": user["id"], "entity": "users"}, timeout=3600)
checked = app.auth.verify_token(token)
user_id = checked["claims"]["id"]verify_token does not raise on a bad token. It returns {verified, error, claims}, so you check verified yourself. Beyond tokens there are hashed, entity-scoped API keys (the raw key is returned once, at creation), an OAuth provider registry with authorize_url and handle_callback, and email flows for OTP login, verification and password reset. Those email flows require SMTP to be configured.
Everything else
The remaining services follow the same pattern, so here is the short tour:
Files:
app.filesmanages entity upload directories under your data directory, with paths checked for traversal.Settings:
app.settingsis the same record as the admin Settings page. Useget,setandconfigs.Logs:
app.logs.info(origin, message, details="", data=None)and its siblings write structured log rows.Realtime:
app.router.broadcast(event)pushes a JSON event to SSE and WebSocket subscribers, andapp.rthandles change notification hooks.Mailer:
app.mailersends SMTP mail, renders templates, and has a mock transport that captures sent messages, which is handy in tests.Utils:
mantisbase.utilsmirrors the C++ helpers: ids, password hashing, filename sanitising and so on.
When something goes wrong in the C++ layer, you get a mantisbase.MantisError, with code as the HTTP-style status and description as the longer detail:
try:
app.entity("nope")
except mantisbase.MantisError as exc:
print(exc.code, exc)Threading
Handlers run on MantisBase worker threads. The GIL is acquired around each Python handler, middleware and callback, and released around database and filesystem work, so Python handlers serialise the same way they would on a Flask threaded server. app.start(blocking=False) runs the server on a background thread. Just do not call stop() from inside a handler running on the server thread; call it from another thread instead.
A note before you build on this
The Python bindings are experimental. Expect rough edges, and treat the API as something that can still move.
We also do not ship .pyi files yet. import mantisbase loads the native extension and nothing else, so mypy and Pyright see an untyped module. help() and __doc__ give you signatures, but App(...) is bound as **kwargs, which means your editor will not autocomplete constructor arguments like port or data_dir. Until stubs land, the docs page is the reference for parameters.
If you try it, I would love to hear what works and what bites. Issues and feedback are welcome on GitHub, and you can find the project at mantisbase.com.


