![]() |
MantisBase v0.4.9
|
MantisBase provides auto-generated RESTful APIs for interacting with database entities. This document covers the entity endpoints, schema management, realtime (SSE) API for live database change notifications (SQLite and PostgreSQL), and request handling.
When MantisBase is running locally:
You can configure the port and host using command-line arguments:
All HTTP responses include:
When running behind a reverse proxy or load balancer, set MB_TRUSTED_PROXIES to a comma-separated list of proxy IP addresses. Only then is X-Forwarded-For trusted for client-IP resolution (rate limits, logging). If unset, the direct peer address is used so the header cannot be spoofed. See Docker Guide.
All REST endpoints live under /api/v1/ and are grouped by namespace:
| Prefix | Description |
|---|---|
| /api/v1/auth/ | MbEntity user authentication: token verify (/verify), plus per-entity login, email OTP login, refresh, logout, API keys, and OAuth |
| /api/v1/entities/ | MbEntity record CRUD |
| /api/v1/schemas/ | Schema management (admin only) |
| /api/v1/files/ | Uploaded file serving |
| /api/v1/health | Server health check |
| /api/v1/sys/logs/ | System logs (admin only) |
| /api/v1/sys/admins/ | Admin accounts, admin auth, and initial setup |
| /api/v1/sys/api-keys/ | Admin API key management |
| /api/v1/sys/oauth/ | OAuth provider registry and entity enablement (admin) |
| /api/v1/sys/settings/ | Application settings |
| /api/v1/realtime | Server-Sent Events for live database changes |
| WS /api/v1/realtime/ws | WebSocket for live database changes |
MantisBase automatically exposes CRUD endpoints for each entity (table or view):
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/entities/<entity> | List all records |
| GET | /api/v1/entities/<entity>/:id | Get a specific record |
| POST | /api/v1/entities/<entity> | Create a new record |
| PATCH | /api/v1/entities/<entity>/:id | Update partial fields |
| DELETE | /api/v1/entities/<entity>/:id | Delete a record |
MbAuth-type entity responses never include the password field in list, get, or realtime change payloads.
All entity endpoints require authentication via JWT tokens. Include the token in the Authorization header:
For authentication endpoints, see Authentication API.
| Code | Meaning |
|---|---|
| 401 Unauthorized | Missing, invalid, or expired credentials (no valid JWT or API key) |
| 403 Forbidden | Valid credentials, but the authenticated user is not permitted to access the resource (access rules, admin-only routes, custom expressions) |
| 503 Service Unavailable | The route is temporarily disabled (for example, by an environment gate such as MB_DISABLE_ADMIN_MUTATIONS) |
Middlewares are functions that run before your route handler, allowing you to add authentication, authorization, and request processing logic.
Every endpoint automatically has two middlewares applied globally:
Additionally, entity endpoints automatically have:
You can use these middlewares when creating custom endpoints:
| Middleware | Description | Usage |
|---|---|---|
| getAuthToken() | Extract token from Authorization header | Applied globally to all routes |
| hydrateContextData() | Validate token and load user data | Applied globally to all routes |
| hasAccess(entity_name) | Check entity access rules | Applied automatically to entity endpoints |
| requireAdminAuth() | Require admin authentication | Blocks non-admin users |
| requireExprEval(expr) | Custom expression gate on a route | Evaluates auth / req context; 403 "Access denied!" when the expression is false (no upfront auth requirement) |
| requireEntityAuth(entity_name) | Require auth from a specific entity | 401 without valid credentials; 403 when authenticated as another entity |
| requireAdminOrEntityAuth(entity_name) | Require admin or entity auth | 401 without valid credentials; 403 when authenticated as neither admin nor the given entity |
| requireGuestOnly() | Require no authentication | Blocks authenticated users, only allows guests |
| rateLimit(max_requests, window_seconds, use_user_id) | Rate limiting middleware | Limits requests per time window by IP or user ID |
| envGateMiddleware(env_var, block_when_truthy) | Environment gate | Blocks with 503 when the env var is truthy (true, 1, on, yes); otherwise the request continues |
Blocks route execution when an environment variable matches a configured truthy value. The env var is read on each request (not cached at startup).
| Env value | Behavior |
|---|---|
| Unset | Normal operation |
| false, 0, or any other non-truthy string | Normal operation (ignored) |
| true, 1, on, yes, t | 503 — {"status":503,"error":"Resource action temporarily disabled","data":{}} |
See Docker environment variables for production flags.
When creating custom endpoints, you can specify middlewares as the third parameter:
After middlewares run, you can access authenticated user data from the request context:
Note: Middlewares execute in the order they are specified. If a middleware returns HandlerResponse::Handled, subsequent middlewares and the handler are skipped.
Schema management endpoints allow you to create, read, update, and delete entity schemas. These endpoints require admin authentication only.
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/schemas | List all schemas |
| GET | /api/v1/schemas/:schema_name_or_id | Get a specific schema |
| POST | /api/v1/schemas | Create a new schema |
| PATCH | /api/v1/schemas/:schema_name_or_id | Update a schema |
| DELETE | /api/v1/schemas/:schema_name_or_id | Delete a schema |
Base MbEntity (Standard Table):
View MbEntity (SQL View):
MbAuth MbEntity (Authentication Table):
auth is only valid on auth entities. Password login defaults to enabled. OTP and OAuth default to disabled. requireEmailVerification defaults to off. Change the flags with an admin PATCH /api/v1/schemas/<name>; other clients receive 403 on a disabled login route. Auth tables also store email_verified (default false). Admin accounts do not. See Authentication API.
MantisBase supports three entity types:
| Type | Description | Fields | Special Properties |
|---|---|---|---|
| base | Standard database table | Yes | Standard CRUD operations |
| auth | Authentication entity | Yes | Includes password, email, and user management fields automatically |
| view | SQL view (read-only) | No | Requires view_query instead of fields |
MbEntity names must follow these rules:
Invalid names will be rejected with a 400 error.
Field names follow the same rules as entity names:
Invalid field names are rejected with a 400 error when creating or updating schemas.
view entities require a view_query that:
Invalid view queries are rejected with a 400 error.
When updating a schema, you can add, update, or remove fields:
Field Operations:
⚠️ Admin Only: All schema endpoints require admin authentication. Regular users cannot access these endpoints.
MbEntity list endpoints use cursor-based pagination ordered by record id (ascending):
| Parameter | Default | Description |
|---|---|---|
| limit | 50 | Number of records to return (1–500) |
| after | — | Cursor (id of the last item from the previous page) |
| filter | — | URL-encoded JSON object of field equality filters, e.g. {"status":"active"} |
Example:
Response:
When has_more is false, you have reached the last page.
You can create custom API endpoints using the router:
PUT/PATCH/POST handlers share the single (req, res) signature. Both JSON and multipart/form-data bodies are read through MbRequest (parsed lazily, once per request):
| Method | Behavior |
|---|---|
| req.jsonBody() | Unified parsed body. JSON requests return the parsed body and throw MbException(400) on malformed JSON; multipart requests return an empty object until parseFormDataToEntity() maps the fields. |
| req.bodyAsJson() | Non-throwing alternative returning a {body, error} pair. |
| req.isMultipartFormData() | true when the body is multipart/form-data. |
| req.formData() | Multipart parts (text and file fields: name, content, filename, content_type); empty for JSON bodies. |
| req.filesMetadata() | File metadata keyed by form field name, available after parseFormDataToEntity(). |
| req.parseFormDataToEntity(entity) | Map multipart fields onto an entity for create/update (no-op for JSON). |
| req.writeFiles(entity_name) / req.undoWrittenFiles(entity_name) | Persist uploaded files / roll them back on failure (no-ops for JSON). |
A custom endpoint accepting both JSON and file uploads:
Uploaded files are served at GET /api/v1/files/<entity>/<filename>. See File Handling for more details.
Redirect one path to another without writing a handler. The default is a 302 Found redirect for GET requests; pass an explicit 3xx status and method constraints to customize, or an empty constraint list to allow all methods:
Check the Embedding Guide for more details.
Files uploaded via multipart/form-data are stored and can be accessed at:
See File Handling for more details.
Foreign keys allow you to establish relationships between entities. When creating or updating schemas with foreign key fields, MantisBase automatically validates the relationships.
Foreign keys are defined using a foreign_key object in the field definition:
| Property | Type | Required | Default | Description |
|---|---|---|---|---|
| entity | string | Yes | - | Name of the referenced entity (table) |
| field | string | No | "id" | Column name in the referenced entity |
| on_update | string | No | "RESTRICT" | Action when referenced record is updated |
| on_delete | string | No | "RESTRICT" | Action when referenced record is deleted |
Both on_update and on_delete support the following policies:
| Policy | Description |
|---|---|
| CASCADE | Automatically update/delete related records |
| SET NULL | Set foreign key field to NULL when referenced record is updated/deleted |
| RESTRICT | Prevent update/delete if related records exist (default) |
| NO ACTION | Similar to RESTRICT, but checked after the operation |
| SET DEFAULT | Set foreign key field to its default value |
When creating or updating schemas with foreign keys, MantisBase automatically validates:
Note: If the referenced entity doesn't exist yet, a warning is issued but the schema is still created. The database will enforce the constraint when the DDL is executed.
Example 1: Comments with Post Reference
Example 2: User Profile with User Reference
Example 3: Removing a Foreign Key
To remove a foreign key constraint, set foreign_key to null:
Foreign key constraints are automatically named using the pattern: fk_<table_name>_<field_name>
For example, a foreign key on post_id in the comments table would create a constraint named fk_comments_post_id.
Most system endpoints are grouped under /api/v1/sys/. The health check is at /api/v1/health.
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/health | Server health and uptime |
See Healthcheck for details.
Requires admin authentication for all settings endpoints.
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/sys/settings/config | Get application settings |
| PATCH | /api/v1/sys/settings/config | Update application settings |
| POST | /api/v1/sys/settings/smtp/test | Send an SMTP test message |
PATCH returns 503 when MB_DISABLE_CONFIG_MUTATIONS is set to a truthy value. A successful PATCH reloads the CORS allowlist immediately (no server restart required).
The settings object contains the following fields:
| Field | Type | Default | Description |
|---|---|---|---|
| orgName | string | "ACME Corp" | Organization display name |
| siteDomain | string | "https://acme.example.com" | Public site URL (OAuth callbacks, JWT audience) |
| corsAllowedOrigins | array of strings | ["http://localhost:3000", "http://127.0.0.1:3000"] | Browser origins allowed for cross-origin requests with credentials |
| maxFileSize | integer | 10485760 | Max file upload size in bytes (10 MiB). Uploads above this are rejected with 413 |
| logRetentionDays | integer | 5 | Delete application logs older than this many days (hourly cleanup job) |
| disableAdminRegistration | boolean | false | When true, blocks creating new admin accounts via the API (POST /api/v1/sys/admins, POST /api/v1/sys/admins/setup) with 503. When false or unset, admin API registration is allowed. Does not affect mantisbase admins --add. |
| disableSchemaMutations | boolean | false | When true, blocks schema mutations via the API (POST, PATCH, DELETE on /api/v1/schemas/*) with 503. GET remains available. Does not affect mantisbase schema CLI commands. |
| emailVerificationRequired | boolean | false | Require email verification on registration |
| sessionTimeout | integer | 86400 | User session timeout in seconds (24 h) |
| adminSessionTimeout | integer | 3600 | Admin session timeout in seconds (1 h) |
| jwtEnableSetIssuer | boolean | false | Set JWT issuer from orgName |
| jwtEnableSetAudience | boolean | false | Set JWT audience from siteDomain |
| smtp | object | see below | Outbound mail configuration |
SMTP credentials are stored in the smtp object of application settings. There is no SMTP environment variable. Any of these writes the same record and applies it to the mailer immediately (no restart):
MB_DISABLE_CONFIG_MUTATIONS blocks the dashboard save and the PATCH endpoint (503). A script running inside the server can still call app.settings().set.
| Field | Type | Default | Description |
|---|---|---|---|
| host | string | "" | SMTP server hostname. Empty host disables sending. mock and localhost:0 capture messages in-process and do not connect (tests). |
| port | integer | 587 | SMTP port, 1–65535 |
| user | string | "" | AUTH username. Leave empty to skip authentication |
| password | string | "" | AUTH password |
| from | string | "" | Envelope and header From address. Required, together with host, before the mailer will send |
| tls | boolean | true | Encrypt the session. See below |
TLS modes:
Password handling is the same for the dashboard, PATCH, and app.settings().set:
The dashboard password box is filled with that mask when a password is already stored. Leave the mask as it is, or clear the box, to keep the current password. Type a new value to replace it. The dashboard cannot clear a stored password; send "password": "" through the API or a script to remove it. A password that is literally eight asterisks cannot be stored, because that string means "keep the current value".
Example (admin auth required):
POST /api/v1/sys/settings/smtp/test sends a message whose subject and body are Hey, it works! to the address in the body. Admin authentication is required. The call uses the SMTP settings already stored; it does not change them, and MB_DISABLE_CONFIG_MUTATIONS does not block it.
Success:
Failures use the same envelope, with data as {}:
| Status | When |
|---|---|
| 400 | email is missing, not a string, or not an address. SMTP is not configured (host and from are required). |
| 401 | Missing or invalid admin credentials |
| 429 | That recipient already received 3 messages in the last hour |
| 502 | The SMTP server rejected the message or could not be reached |
The GET response also includes mantisVersion (the running server version).
MantisBase enables credentialed cross-origin browser access when the request Origin header matches an entry in the allowlist. Allowed origins are loaded from:
Example environment variable:
Example settings PATCH (admin auth required):
For credentialed requests (fetch(..., { credentials: "include" })), responses echo the exact matching origin and set Access-Control-Allow-Credentials: true. Wildcard Access-Control-Allow-Origin: * is not used.
http://localhost:3000 and http://127.0.0.1:3000 are different origins; list each host your frontend uses. Preflight OPTIONS requests are handled automatically for allowed origins.
See also Docker configuration for MB_CORS_ORIGINS in container deployments.
Admin account CRUD and authentication live under /api/v1/sys/admins/.
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/v1/sys/admins/login | Admin login |
| POST | /api/v1/sys/admins/refresh | Refresh admin token |
| POST | /api/v1/sys/admins/logout | Admin logout |
| POST | /api/v1/sys/admins/setup | Create initial admin (first boot only) |
| GET | /api/v1/sys/admins | List admin accounts |
| GET | /api/v1/sys/admins/:id | Get admin account |
| POST | /api/v1/sys/admins | Create admin account |
| PATCH | /api/v1/sys/admins/:id | Update admin account |
| DELETE | /api/v1/sys/admins/:id | Delete admin account |
The logs endpoint provides access to system logs with filtering and cursor pagination. Requires admin authentication. Results are ordered by log id (ascending).
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/sys/logs | Get system logs with filtering and pagination |
| Parameter | Type | Default | Description |
|---|---|---|---|
| limit | integer | 50 | Number of records per page (max 1000) |
| after | string | — | Cursor (id of last item from previous page) |
| level | string | — | Filter by exact log level: trace, debug, info, warn, critical |
| min_level | string | — | Filter by minimum log level (includes that level and above) |
| search | string | — | Search in log messages |
| start_date | string | — | Start date filter (ISO 8601 format) |
| end_date | string | — | End date filter (ISO 8601 format) |
Pass the returned cursor value as the after parameter in subsequent requests to page through results. When has_more is false, you have reached the last page.
Log levels in order of severity (lowest to highest):
When using min_level, all logs at that level and above are included. For example, min_level=warn includes warn and critical logs.
503 Service Unavailable - Log database not initialized:
500 Internal Server Error - Server error:
MantisBase provides realtime database change notifications over Server-Sent Events (SSE) for both SQLite and PostgreSQL backends. Clients subscribe to topics (entity names and optionally specific row IDs) and receive live insert, update, and delete events as they occur.
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/realtime | Open an SSE connection (optional initial topics). Returns client_id in the connected event. |
| POST | /api/v1/realtime | Set topics for an existing session. Returns granted topics and a denied list. |
Realtime connections accept optional credentials via ?token= (overrides header) or Authorization: Bearer <token>. Invalid or expired tokens at connect time are treated as guest. MbAuth can be upgraded on subscribe (POST or WS subscribe message) but cannot be downgraded or switched to another user.
Session IDs use the prefixes rt_sse_... and rt_ws_....
Connect-only sessions with no subscribed topics are closed after 60 seconds. Authenticated sessions expire when the JWT/session is revoked or expires; idle subscribed sessions are closed after 10 minutes.
Establishes a long-lived SSE stream. Topics are optional on connect; use POST to subscribe after receiving client_id.
Query parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| topics | string | No | Comma-separated list of topics. Each topic is an entity name (e.g. posts) or entity:row_id. Granted topics are filtered by access rules; denied topics appear in the connected event when present. |
| token | string | No | JWT or API key. Overrides Authorization when both are set. |
Example (connect only)
Example (connect with public topics)
Response
The stream sends events in SSE format. Each event has an event type and a data line (JSON).
Sets the topic list for an existing SSE session (replaces prior subscriptions). Pass optional auth to upgrade from guest.
Request body (JSON)
| Field | Type | Required | Description |
|---|---|---|---|
| client_id | string | Yes | Session ID from the connected event (rt_sse_...). |
| topics | array | Yes | Topics to subscribe to. Empty array clears subscriptions. |
| token | string | No | JWT or API key for auth upgrade (alternative to Authorization header). |
Response (200)
MbAuth downgrade or switching to another user returns 403.
Example
| Event | Description |
|---|---|
| connected | Sent once when the SSE connection is established. Contains client_id, topics, and timestamp. |
| ping | Keep-alive sent periodically (every ~30 s). Contains timestamp. |
| change | A database change (insert, update, or delete) for a subscribed topic. |
| error | Session error (e.g. token_expired). Connection may close afterward. |
connected
ping
change
| Field | Type | Description |
|---|---|---|
| action | string | One of insert, update, delete. |
| entity | string | MbEntity (table) name. |
| row_id | string | ID of the affected row. |
| topic | string | Topic that matched (entity or entity:row_id). |
| timestamp | number | Unix timestamp of the change. |
| data | object | null | For insert and update, the row payload; for delete, null. Password fields on auth entities are omitted. |
Example change (insert)
Example change (delete)
Realtime endpoints use the same access rules as entity list and get:
Invalid or unauthorized topics result in 400, 401, or 403 responses depending on whether the request is malformed, unauthenticated, or forbidden by access rules.
Realtime is supported for:
In addition to SSE, MantisBase provides a WebSocket endpoint for realtime notifications. It uses the same topic model as SSE.
Authentication is optional at connect. Supply a JWT or API key (mb_sk_...) via ?token= (overrides header) or Authorization: Bearer <token>. Invalid tokens are treated as guest. You receive a client_id immediately and subscribe afterward.
On connect, the server sends:
Send { "type": "subscribe", "topics": [...] }. Optional token upgrades auth (for browsers that cannot set headers after connect). { "type": "auth", "token": "..." } is equivalent to a token-only upgrade.
Topics follow the same format as SSE — entity name or entity:row_id. Subscribing replaces the current topic set.
The subscribed acknowledgement lists granted topics and denied failures:
MbDatabase changes are delivered in the same format as SSE change events:
WebSocket realtime can be disabled by setting the environment variable MB_DISABLE_REALTIME_WS=1 (or true). SSE can be disabled with MB_DISABLE_REALTIME_SSE=1.
The MantisBase Admin Dashboard is a comprehensive web-based interface accessible at /mb (e.g., http://localhost:7070/mb). It provides a visual alternative to the REST API for managing your backend.