|
MantisBase v0.3.7
|
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 REST endpoints live under /api/v1/ and are grouped by namespace:
| Prefix | Description |
|---|---|
/api/v1/auth/<entity>/ | Entity user authentication (login, refresh, logout) for auth-type entities |
/api/v1/entities/ | Entity 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/settings/ | Application settings |
/api/v1/realtime | Server-Sent Events 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 |
All entity endpoints require authentication via JWT tokens. Include the token in the Authorization header:
For authentication endpoints, see Authentication API.
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:
getAuthToken()** - Extracts JWT token from Authorization header and stores it in request contexthydrateContextData()** - Validates token, fetches user data from database, and populates request context with user informationAdditionally, entity endpoints automatically have:
hasAccess(entity_name)** - Evaluates entity access rules to determine if the authenticated user can perform the requested operation. Called automatically by entity endpoints to confirm access rules before data query.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 |
requireEntityAuth(entity_name) | Require authentication from specific entity | Only allows users from specified entity table |
requireAdminOrEntityAuth(entity_name) | Require admin OR entity auth | Allows admins or users from specified entity |
requireGuestOnly() | Require no authentication | Blocks authenticated users, only allows guests |
requireExprEval(expr) | Evaluate custom expression | Custom expression-based access control |
rateLimit(max_requests, window_seconds, use_user_id) | Rate limiting middleware | Limits requests per time window by IP or user ID |
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 Entity (Standard Table):
View Entity (SQL View):
Auth Entity (Authentication Table):
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 |
Entity names must follow these rules:
_ characters allowedInvalid names will be rejected with a 400 error.
When updating a schema, you can add, update, or remove fields:
Field Operations:
name that doesn't existidid and "op": "delete" or "op": "remove"⚠️ Admin Only: All schema endpoints require admin authentication. Regular users cannot access these endpoints.
Future support for filtering, sorting, and pagination:
You can create custom API endpoints using the router:
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.
MantisBase supports three types of entities:
Standard database tables with fields. Use for most data storage needs.
Authentication entities with built-in password and user management fields. Automatically includes:
password - Hashed password fieldemail - Email field (typically unique)SQL views based on queries. Read-only, no fields defined. Use view_query instead of fields.
All entity names are automatically validated to prevent SQL injection and ensure consistency:
Validation Rules:
a-z, A-Z, 0-9, _)Invalid Examples:
my-table (contains hyphen)my table (contains space)my@table (contains special character)Invalid names will result in a 400 Bad Request error with a descriptive message.
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:
foreign_key.entity must existforeign_key.field must exist in the referenced entityNote: 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.
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/sys/settings/config | Get application settings |
| PATCH | /api/v1/sys/settings/config | Update application settings |
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, pagination, and sorting capabilities. Requires admin authentication.
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/v1/sys/logs | Get system logs with filtering and pagination |
| Parameter | Type | Default | Description |
|---|---|---|---|
page | integer | 1 | Page number (1-based) |
page_size | integer | 50 | Number of records per page (max 1000) |
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) |
sort_by | string | "timestamp" | Sort field: level, origin, message, timestamp, created_at |
sort_order | string | "desc" | Sort order: asc or desc |
Log levels in order of severity (lowest to highest):
trace - Detailed debugging informationdebug - General debugging informationinfo - Informational messageswarn - Warning messagescritical - Critical errorsWhen 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. Requires topics query parameter. |
| POST | /api/v1/realtime | Update topics for an existing session or clear topics to disconnect. Requires JSON body. |
Establishes a long-lived SSE stream. Pass a comma-separated list of topics in the query string.
Query parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
topics | string | Yes | Comma-separated list of topics. Each topic is an entity name (e.g. posts) or entity:row_id (e.g. posts:019c1b81-364b-7000-8120-b5416b2c42c2) for a specific row. |
Example
Response
text/event-streamThe stream sends events in SSE format. Each event has an event type and a data line (JSON).
Updates the list of topics for an existing SSE session, or clears topics to effectively disconnect. Requires the client_id (session identifier) returned in the connected event from the GET request.
Request body (JSON)
| Field | Type | Required | Description |
|---|---|---|---|
client_id | string | Yes | Session ID returned when the SSE connection was established. |
topics | array | Yes | New list of topics. Each topic is an entity name or entity:row_id. Pass an empty array to clear subscriptions and disconnect. |
Example: Update topics
Example: Clear topics (disconnect)
| Event | Description |
|---|---|
connected | Sent once when the SSE connection is established. Contains client_id, topics, and timestamp. |
ping | Keep-alive sent periodically (e.g. every ~30 s). Contains timestamp. |
change | A database change (insert, update, or delete) for a subscribed topic. |
connected
ping
change
| Field | Type | Description |
|---|---|---|
action | string | One of insert, update, delete. |
entity | string | Entity (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. |
Example change (insert)
Example change (delete)
Realtime endpoints use the same access rules as entity list and get:
posts) requires list access on that entity.posts:<id>) requires get access.Invalid or unauthorized topics result in 400 or 403 responses.
Realtime is supported for:
LISTEN/NOTIFY and triggers.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.