MantisBase is designed as a lightweight C++ library that can be embedded directly into your desktop, mobile, or embedded application. This guide explains how to integrate MantisBase into your project and configure it.
The same embedded server is available from Python. See the Python Bindings guide (pip install mantisbase).
Why Embed MantisBase?
- Add full-featured local storage and REST API support to your Qt, Slint, or CLI app
- Serve data to local UI components through HTTP or direct C++ API calls
- Retain full control of the application lifecycle and logic
- No separate server deployment required
Dependencies
On Linux, building MantisBase requires libpq (PostgreSQL client) and libuuid development packages. These match what CI installs in .github/workflows/build-matrix.yml:
sudo apt-get update
sudo apt-get install -y libpq-dev uuid-dev
Runtime shared libraries on Debian/Ubuntu are libpq5 and libuuid1 (see docker/Dockerfile).
Integration
As a Prebuilt Package (no source build)
Download the prebuilt C++ dev package for your OS from GitHub Releases (mantisbase_<tag>-linux-cpp-dev.zip, mantisbase_<tag>-windows-cpp-dev.zip or mantisbase_<tag>-darwin-cpp-dev.zip):
# For Windows
# set(MantisBase_DIR "/path/to/mantisbase-windows-cpp-dev/cmake")
# For macOS
# set(MantisBase_DIR "/path/to/mantisbase-darwin-cpp-dev/cmake")
set(MantisBase_DIR "/path/to/mantisbase-linux-cpp-dev/cmake")
find_package(MantisBase REQUIRED)
target_link_libraries(my_app PRIVATE mantisbase::shared)
See the C++ Dev Package Guide for the full walkthrough.
As a Static or Shared Library
Add MantisBase as a submodule or include it in your CMake project:
add_subdirectory(mantisbase)
target_link_libraries(your_app PRIVATE mantisbase)
Application lifecycle
MantisBase::create() returns a std::unique_ptr<MantisBase> that you own. There is no global MantisBase::instance() accessor. Hold the pointer in main (or your app object), pass const MantisBase& into your own code, and call app->run() to start the HTTP server.
Services that run inside MantisBase (MbEntity, MbRouter, MbRequest, MbApiKeyMgr, MbOAuthMgr, etc.) inherit MbAppMixin and expose mbApp() when you only have a request or service reference.
Basic Usage
Using Command-Line Arguments
The simplest way to embed MantisBase is using command-line arguments:
int main(
int argc,
char* argv[])
{
return app->run();
}
static std::unique_ptr< MantisBase > create(int argc, char **argv)
Create class instance given cmd args passed in.
Definition mantisbase.cpp:75
int main(const int argc, char *argv[])
MantisApp standalone entrypoint.
Definition main.cpp:16
The main application for mantisbase.
This allows your application to accept standard MantisBase CLI arguments like --db, --db_url, --dev, and subcommands such as serve --host / serve --port.
Using JSON Configuration
For more control when embedding, use JSON configuration:
{
config["dev"] = true;
config["serve"] = {
{"port", 8080},
{"host", "127.0.0.1"}
};
config["db"] = "sqlite3";
config["data-dir"] = "./data";
config["public-dir"] = "./public";
config["scripts-dir"] = "./scripts";
return app->run();
}
nlohmann::json json
Shorten JSON namespace.
Definition api_keys.h:36
Minimal Configuration
You can also create an instance with default settings:
Accessing services (DI)
Reach auth, entities, and database APIs through your owned app instance:
mb::json claims = {{
"id",
"user123"}, {
"table",
"users"}};
std::string jwt = app->auth().createToken(claims);
auto key = app->auth().apiKey().create("users", "user123", "Desktop client");
app->auth().oauth().enableProviderForEntity("users", provider_id);
auto users = app->entity("users");
auto sql = app->db().session();
Inside custom route handlers, use req.mbApp():
});
MbEntity entity(const std::string &entity_name) const
Fetch a table schema encapsulated by an MbEntity object from given the table name....
Definition mantisbase.cpp:414
const MantisBase & mbApp() const
Application that owns this service or request context.
Definition types.cpp:8
int countRecords(const json &filter=json::object()) const
Count records in the entity table, optionally matching a filter.
Definition entity_crud.cpp:480
HTTP request wrapper bound to a MantisBase instance.
Definition http.h:66
HTTP response wrapper bound to a MantisBase instance.
Definition http.h:213
void sendJSON(int statusCode=200, const json &data=json::object()) const
Definition http_response.cpp:126
Per-request data (auth, verification, etc.) is stored on MbRequest via set() / get(), not a global singleton.
Configuration Options
The JSON configuration supports the following options:
{
"db": "sqlite3",
"db_url": "",
"data-dir": "./data",
"public-dir": "./public",
"scripts-dir": "./scripts",
"migrations-dir": "./migrations",
"dev": true,
"serve": {
"port": 7070,
"host": "127.0.0.1",
"pool-size": 4,
"skip-admin-setup": false
},
"admins": {
"add": ["admin@example.com", "password"],
"ls": false,
"rm": "admin@example.com"
},
"migrations": {
"up": true
},
"schema": {
"ls": true
}
}
All options are optional and will use sensible defaults if omitted.
Adding Custom Routes
You can add custom API endpoints using the router:
{
auto& router = app->router();
res.
sendJSON(200, {{
"message",
"Custom endpoint"}});
});
mb::json stats = {{
"users", 100}, {
"posts", 500}};
auto auth = req.
get<
mb::json>(
"auth", mb::json::object());
std::string userId = auth["id"];
res.
sendJSON(200, {{
"user_id", userId}});
router.redirect("/api/v2/legacy", "/api/v2/custom");
router.redirect("/api/v2/old-upload", "/api/v2/admin/stats", 301, {"GET", "POST"});
return app->run();
}
const T & get(const std::string &key, T default_value)
Definition http.h:193
Middleware functions for request processing.
MANTISBASE_API MbMiddlewareFn requireEntityAuth(const std::string &entity_name)
Require entity-specific authentication.
Definition middlewares.cpp:535
MANTISBASE_API MbMiddlewareFn requireAdminAuth()
Require admin authentication.
Definition middlewares.cpp:408
Accessing MbDatabase
You can access the database directly for custom operations:
#include <soci/soci.h>
{
auto sql = app->db().session();
soci::row row;
*sql << "SELECT * FROM users WHERE id = :id",
soci::use("user123"),
soci::into(row);
if (sql->got_data()) {
}
return app->run();
}
Working with Entities
You can interact with entities programmatically:
{
auto users = app->entity("users");
{"name", "John Doe"},
{"email", "john@example.com"}
};
auto created = users.create(newUser);
auto allUsers = users.list();
if (auto user = users.read("user123"); user.has_value()) {
}
mb::json updates = {{
"name",
"Jane Doe"}};
auto updated = users.update("user123", updates);
users.remove("user123");
return app->run();
}
Using as a Submodule
Add MantisBase as a git submodule:
git submodule add https://github.com/allankoechke/mantisbase.git
git submodule update --init --recursive
Then include it in your CMakeLists.txt:
add_subdirectory(mantisbase)
target_link_libraries(your_app PRIVATE mantisbase)
Testing Embedded APIs
Once your app is running, test the APIs:
# Test entity endpoints
curl http://localhost:7070/api/v1/entities/users
# Test custom endpoints
curl http://localhost:7070/api/v1/custom
# Test with JWT or API key
curl -H "Authorization: Bearer <token>" \
http://localhost:7070/api/v1/entities/posts
curl -H "Authorization: Bearer mb_sk_..." \
http://localhost:7070/api/v1/entities/posts
Notes
- MantisBase APIs respect all access rules and authentication even in embedded mode
- The run() method is blocking - use a separate thread if you need non-blocking behavior
- All entity endpoints follow the pattern /api/v1/entities/<entity_name>
- Token verification: GET /api/v1/auth/verify (JWT or API key)
- Authentication endpoints are at /api/v1/auth/<entity>/ (auth-type entities only)
- API keys and OAuth routes live under /api/v1/auth/<entity>/api-keys and /api/v1/auth/<entity>/oauth/
- Schema management endpoints are at /api/v1/schemas/* (admin only)
- File serving endpoints are at /api/v1/files/*
- System endpoints are at /api/v1/sys/* (logs, admins, settings, api-keys, oauth); health is at /api/v1/health
Complete Example
{
config["dev"] = true;
config["serve"] = {{"port", 8080}};
auto& router = app->router();
res.
sendJSON(200, {{
"message",
"Hello from embedded MantisBase!"}});
});
return app->run();
}
Summary
By embedding MantisBase, you gain powerful backend features including database storage, JWT and API-key authentication, OAuth, and REST APIs without requiring a separate server deployment. Own the MantisBase instance in your process, inject const MantisBase& (or use mbApp() in handlers), and integrate with minimal configuration.