@slorenzot/memento-api
v2.1.0
Published
HTTP REST API for Memento memory system
Readme
@slorenzot/memento-api
RESTful HTTP API providing programmatic access to Memento memory system with endpoints for observations, sessions, and system management.
🚀 Installation
# Using Bun (recommended)
bun add @slorenzot/memento-api
# Using npm
npm install @slorenzot/memento-api💡 Basic Usage
TypeScript
import { APIServer } from '@slorenzot/memento-api';
// Initialize API server
const server = new APIServer(3000, './data/memento.db');
// Start HTTP server
await server.start();
// Server will be available at http://localhost:3000Shell/Bun
# Run API server
bunx @slorenzot/memento-api
# Or with custom configuration
API_PORT=8080 DATABASE_PATH=./custom.db bunx @slorenzot/memento-api🔧 Core API
Main Class
APIServer(port: number, dbPath: string)
HTTP API server constructor.
Parameters:
port: Port where the server will listen (e.g., 3000)dbPath: Path to the SQLite database file
Example:
const server = new APIServer(3000, './data/memento.db');Control Methods
start()
Starts the HTTP server and begins listening for requests.
Returns: Promise<void>
Example:
const server = new APIServer(3000, './data/memento.db');
await server.start();
console.log('Server started at http://localhost:3000');close()
Stops the HTTP server and closes the database connection.
Returns: void
Example:
const server = new APIServer(3000, './data/memento.db');
await server.start();
// On cleanup or shutdown
server.close();🌐 API Endpoints
System Health
GET /api/health
Checks the API system status.
Response:
{
"status": "healthy",
"version": "0.1.1",
"database": "connected",
"uptime": "2h 30m"
}Observation Management
GET /api/observations
Lists observations with optional filters.
Query Params:
query(string): Full-text search termtype(string): Filter by type (decision|bug|discovery|note)project_id(string): Filter by project IDtopic_key(string): Filter by topiclimit(number): Maximum number of resultsoffset(number): Pagination offset
Response:
{
"observations": [
{
"id": 1,
"uuid": "abc123",
"sessionId": 456,
"title": "Important decision",
"content": "Use PostgreSQL in production",
"type": "decision",
"topicKey": "architecture",
"projectId": "my-app",
"createdAt": "2024-04-04T10:30:00Z",
"metadata": {}
}
],
"total": 150,
"limit": 10,
"offset": 0
}cURL example:
curl "http://localhost:3000/api/observations?limit=10&offset=0"POST /api/observations
Creates a new observation.
Request Body:
{
"title": "string (required)",
"content": "string (required)",
"type": "decision|bug|discovery|note (optional, default: note)",
"topicKey": "string|null (optional)",
"projectId": "string (optional)",
"metadata": "object (optional)"
}Response:
{
"id": 151,
"uuid": "def456",
"sessionId": 456,
"title": "Important decision",
"content": "Use PostgreSQL in production",
"type": "decision",
"topicKey": "architecture",
"projectId": "my-app",
"createdAt": "2024-04-04T11:00:00Z",
"metadata": {}
}cURL example:
curl -X POST http://localhost:3000/api/observations \
-H "Content-Type: application/json" \
-d '{
"title": "Important decision",
"content": "Use PostgreSQL in production",
"type": "decision",
"projectId": "my-app"
}'GET /api/observations/:id
Gets a specific observation by ID.
URL Params:
id: Numeric ID of the observation
Response:
{
"id": 123,
"uuid": "abc123",
"sessionId": 456,
"title": "Important decision",
"content": "Use PostgreSQL in production",
"type": "decision",
"topicKey": "architecture",
"projectId": "my-app",
"createdAt": "2024-04-04T10:30:00Z",
"metadata": {}
}PUT /api/observations/:id
Updates an existing observation.
URL Params:
id: Numeric ID of the observation
Request Body:
{
"title": "string (optional)",
"content": "string (optional)",
"type": "decision|bug|discovery|note (optional)",
"topicKey": "string|null (optional)",
"metadata": "object (optional)"
}Response:
{
"id": 123,
"uuid": "abc123",
"title": "Updated title",
"content": "Updated content",
"type": "decision",
"topicKey": "architecture",
"projectId": "my-app",
"createdAt": "2024-04-04T10:30:00Z",
"metadata": {}
}DELETE /api/observations/:id
Deletes an observation.
URL Params:
id: Numeric ID of the observation
Response:
{
"success": true,
"message": "Observation deleted successfully"
}Session Management
POST /api/sessions
Creates a new session.
Request Body:
{
"projectId": "string (optional)",
"metadata": "object (optional)"
}Response:
{
"id": 457,
"uuid": "session-uuid-123",
"projectId": "my-app",
"startedAt": "2024-04-04T11:00:00Z",
"endedAt": null,
"metadata": {}
}PUT /api/sessions/:id/end
Ends a session.
URL Params:
id: Numeric ID of the session
Response:
{
"id": 457,
"uuid": "session-uuid-123",
"projectId": "my-app",
"startedAt": "2024-04-04T11:00:00Z",
"endedAt": "2024-04-04T12:00:00Z",
"metadata": {}
}GET /api/sessions
Lists sessions with filters.
Query Params:
project_id(string): Filter by project IDlimit(number): Maximum number of resultsoffset(number): Pagination
Utilities
GET /api/stats
Gets system statistics.
Response:
{
"totalObservations": 150,
"totalSessions": 45,
"byType": {
"decision": 45,
"bug": 30,
"discovery": 50,
"note": 25
},
"byProject": {
"my-app": 100,
"other-project": 50
}
}GET /api/timeline
Gets a chronological timeline of observations.
Query Params:
project_id(string): Filter by projectsession_id(number): Filter by sessionlimit(number): Number of results
⚡ Practical Examples
Example 1: Complete Server Initialization
import { APIServer } from '@slorenzot/memento-api';
// Configuration
const port = parseInt(process.env.API_PORT || '3000', 10);
const dbPath = process.env.DATABASE_PATH || './data/memento.db';
// Create and start server
const server = new APIServer(port, dbPath);
// Shutdown handling
process.on('SIGINT', () => {
console.log('Closing server...');
server.close();
process.exit(0);
});
// Start server
await server.start();
console.log(`API server started on port ${port}`);Example 2: Custom Express.js Integration
import { APIServer } from '@slorenzot/memento-api';
import express from 'express';
// Create Memento API server
const mementoAPI = new APIServer(3001, './data/memento.db');
// Create custom Express server
const app = express();
// Add CORS middleware
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
// Custom endpoint using Memento
app.get('/api/my-observations', async (req, res) => {
// You could use the memory engine internally
// for custom logic
res.json({ message: 'Custom endpoint' });
});
// Start servers
await mementoAPI.start();
app.listen(3000, () => {
console.log('Express server on port 3000');
console.log('Memento server on port 3001');
});Example 3: Frontend Integration
// In React/Vue/Next.js application
const API_BASE = 'http://localhost:3000/api';
// Function to search observations
async function searchObservations(query: string) {
const response = await fetch(
`${API_BASE}/observations?query=${encodeURIComponent(query)}`
);
return await response.json();
}
// Function to create observation
async function createObservation(data: {
title: string;
content: string;
type: string;
}) {
const response = await fetch(`${API_BASE}/observations`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
return await response.json();
}
// Usage in component
const results = await searchObservations('architecture');
console.log('Results:', results);Example 4: cURL Automation Script
#!/bin/bash
API_URL="http://localhost:3000/api"
# Create session
SESSION=$(curl -s -X POST "$API_URL/sessions" \
-H "Content-Type: application/json" \
-d '{"projectId":"automated-script","metadata":{"type":"automation"}}')
SESSION_ID=$(echo $SESSION | grep -o '"id":[0-9]*' | grep -o '[0-9]*')
echo "Session created: $SESSION_ID"
# Save observation
curl -s -X POST "$API_URL/observations" \
-H "Content-Type: application/json" \
-d "{
\"title\": \"Automation complete\",
\"content\": \"Script executed successfully\",
\"type\": \"note\",
\"projectId\": \"automated-script\"
}"
# End session
curl -s -X PUT "$API_URL/sessions/$SESSION_ID/end"
echo "Session ended"🔧 Configuration
Environment Variables
API_PORT: Server port (default: 3000)DATABASE_PATH: Database path (default: ./data/memento.db)JWT_SECRET: Secret for JWT authentication (if implemented)CORS_ORIGIN: Allowed origins for CORS (default: *)
Example:
# Configure port and database
export API_PORT=8080
export DATABASE_PATH=/custom/path/database.db
bunx @slorenzot/memento-api⚠️ Restrictive License
This package is under CC BY-NC-ND 4.0 License:
- ✅ Personal and educational use permitted
- ✅ Share with attribution to the author
- ❌ Commercial use NOT permitted
- ❌ Modifications or forks NOT permitted
Author: Soulberto Lorenzo ([email protected])
🔄 Dependencies
Main Dependencies
@slorenzot/memento-core- Memory engineexpress- HTTP server frameworkcors- CORS middlewarehelmet- HTTP security headersexpress-rate-limit- Rate limitingjsonwebtoken- JWT authenticationzod- Schema validationdotenv- Environment variable management
Peer Dependencies
bunv1.0+ (recommended)nodev20+ (compatible)
🛠️ Development
# Clone the project
git clone https://github.com/slorenzot/memento.git
cd memento/packages/api
# Install dependencies
bun install
# Development
bun run dev
# Build
bun run build
# Tests
bun test📋 Changelog
[0.1.1] - 2024-04-04
- Added: Basic API server with RESTful endpoints
- Added: Observation management endpoints
- Added: Session management endpoints
- Added: Utility endpoints (stats, timeline)
- Fixed: Core dependency updates
👤 Author
Soulberto Lorenzo
- GitHub: @slorenzot
- Email: [email protected]
📄 License
This package is licensed under Creative Commons Attribution-NonCommercial-NoDerivs 4.0 International.
⚠️ Important: This package has a restrictive license. Please respect the CC BY-NC-ND 4.0 license terms.
