Skip to content

HeliosDB REST - Automatic REST API Generator

HeliosDB REST - Automatic REST API Generator

Automatically generate REST APIs for your HeliosDB databases with OpenAPI/Swagger documentation, authentication, rate limiting, and more.

Features

  • Automatic CRUD Endpoints: Generate REST endpoints for all database tables
  • OpenAPI 3.0 Specification: Auto-generated API documentation
  • Swagger UI Integration: Interactive API documentation
  • Multiple Authentication Methods:
    • JWT (JSON Web Tokens)
    • API Key authentication
  • Rate Limiting: Token bucket algorithm with per-user limits
  • Query Features:
    • Filtering with multiple operators
    • Sorting by multiple columns
    • Pagination support
  • Request Validation: Schema-based validation with SQL injection protection
  • CORS Support: Cross-origin resource sharing
  • Error Handling: Proper HTTP status codes and error messages

Installation

Add to your Cargo.toml:

[dependencies]
heliosdb-rest = "3.0.0"
tokio = { version = "1.35", features = ["full"] }

Quick Start

use heliosdb_rest::*;
use std::sync::Arc;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Configure the REST API server
let config = RestApiConfig {
host: "127.0.0.1".to_string(),
port: 8080,
jwt_secret: Some("your_secret_key".to_string()),
api_keys: vec!["api_key_123".to_string()],
rate_limit: RateLimitConfig {
requests_per_minute: 60,
burst: 10,
},
enable_swagger: true,
};
// Create database handle (implement DatabaseHandle trait)
let db: Arc<dyn DatabaseHandle> = /* your database */;
// Create and start server
let server = RestApiServer::new(config, db).await?;
server.serve().await?;
Ok(())
}

Automatic Endpoints

For each table in your database, the following endpoints are automatically generated:

List Records

GET /api/v1/{table}?filter=column:op:value&sort=column:dir&limit=N&offset=N

Query Parameters:

  • filter: Filter conditions (format: column:operator:value)
  • sort: Sort fields (format: column:direction)
  • limit: Maximum records to return (default: 100, max: 1000)
  • offset: Number of records to skip (default: 0)

Filter Operators:

  • eq: Equal to
  • ne: Not equal to
  • gt: Greater than
  • gte: Greater than or equal to
  • lt: Less than
  • lte: Less than or equal to
  • like: Pattern matching
  • in: In list (value must be JSON array)

Sort Directions:

  • asc: Ascending
  • desc: Descending

Example:

Terminal window
curl "http://localhost:8080/api/v1/users?filter=age:gt:25&sort=name:asc&limit=10"

Get Single Record

GET /api/v1/{table}/{id}

Example:

Terminal window
curl http://localhost:8080/api/v1/users/1

Create Record

POST /api/v1/{table}
Content-Type: application/json
{
"column1": "value1",
"column2": "value2"
}

Example:

Terminal window
curl -X POST http://localhost:8080/api/v1/users \
-H "Content-Type: application/json" \
-d '{"name": "Alice", "email": "alice@example.com", "age": 30}'

Update Record

PUT /api/v1/{table}/{id}
Content-Type: application/json
{
"column1": "new_value1",
"column2": "new_value2"
}

Example:

Terminal window
curl -X PUT http://localhost:8080/api/v1/users/1 \
-H "Content-Type: application/json" \
-d '{"name": "Alice Smith", "age": 31}'

Partial Update

PATCH /api/v1/{table}/{id}
Content-Type: application/json
{
"column1": "new_value"
}

Example:

Terminal window
curl -X PATCH http://localhost:8080/api/v1/users/1 \
-H "Content-Type: application/json" \
-d '{"age": 32}'

Delete Record

DELETE /api/v1/{table}/{id}

Example:

Terminal window
curl -X DELETE http://localhost:8080/api/v1/users/1

Authentication

JWT Authentication

Generate a token:

use heliosdb_rest::auth::JwtAuth;
let jwt = JwtAuth::new("your_secret_key".to_string());
let token = jwt.generate_token("user123", vec!["admin".to_string()])?;

Use the token in requests:

Terminal window
curl -H "Authorization: Bearer YOUR_TOKEN" \
http://localhost:8080/api/v1/users

API Key Authentication

Configure API keys in the server config and use them in requests:

Terminal window
curl -H "X-API-Key: api_key_123" \
http://localhost:8080/api/v1/users

Rate Limiting

Rate limiting is automatically applied based on the authentication method:

  • JWT: Limited by user ID
  • API Key: Limited by API key
  • No auth: Limited by IP address

Configure rate limits in the server config:

rate_limit: RateLimitConfig {
requests_per_minute: 60, // Max requests per minute
burst: 10, // Burst capacity
}

Response Format

All responses follow this format:

Success Response:

{
"success": true,
"data": { /* your data */ },
"metadata": {
"total": 100,
"limit": 10,
"offset": 0,
"page": 1
}
}

Error Response:

{
"success": false,
"error": "Error message",
"code": "ERROR_CODE"
}

OpenAPI/Swagger Documentation

When enable_swagger is true, Swagger UI is available at:

http://localhost:8080/swagger-ui

The OpenAPI specification is available at:

http://localhost:8080/api-docs/openapi.json

Database Handle Implementation

Implement the DatabaseHandle trait for your database:

use heliosdb_rest::*;
use async_trait::async_trait;
struct MyDatabase {
// Your database connection
}
#[async_trait]
impl DatabaseHandle for MyDatabase {
async fn get_tables(&self) -> RestResult<Vec<String>> {
// Return list of table names
}
async fn get_table_schema(&self, table: &str) -> RestResult<TableSchema> {
// Return table schema
}
async fn execute_query(
&self,
query: &str,
params: Vec<QueryValue>
) -> RestResult<Vec<serde_json::Value>> {
// Execute SQL query and return results
}
async fn insert(&self, table: &str, data: serde_json::Value) -> RestResult<serde_json::Value> {
// Insert record and return it with ID
}
async fn update(
&self,
table: &str,
id: &str,
data: serde_json::Value
) -> RestResult<serde_json::Value> {
// Update record and return updated data
}
async fn delete(&self, table: &str, id: &str) -> RestResult<()> {
// Delete record
}
async fn get_by_id(&self, table: &str, id: &str) -> RestResult<Option<serde_json::Value>> {
// Get single record by ID
}
async fn count(&self, table: &str, filter: Option<&str>) -> RestResult<u64> {
// Count records with optional filter
}
}

Examples

Run the Example Server

Terminal window
cargo run --example api_server

This starts a server with in-memory sample data on http://localhost:8080.

Complex Query Example

Terminal window
# Get users older than 25, sorted by name, with pagination
curl "http://localhost:8080/api/v1/users?filter=age:gt:25&sort=name:asc&limit=10&offset=0"
# Get users with specific statuses
curl "http://localhost:8080/api/v1/users?filter=status:in:[\"active\",\"pending\"]"
# Multiple filters
curl "http://localhost:8080/api/v1/users?filter=age:gt:25&filter=status:eq:active"
# Multiple sort fields
curl "http://localhost:8080/api/v1/users?sort=age:desc&sort=name:asc"

Security Features

  • SQL Injection Protection: Input validation and parameterized queries
  • Schema Validation: Requests are validated against table schemas
  • Rate Limiting: Prevents abuse
  • Authentication: JWT and API key support
  • CORS Configuration: Controlled cross-origin access

Error Handling

The API returns appropriate HTTP status codes:

  • 200 OK: Successful GET/PUT/PATCH
  • 201 Created: Successful POST
  • 204 No Content: Successful DELETE
  • 400 Bad Request: Invalid request or validation error
  • 401 Unauthorized: Authentication failed
  • 403 Forbidden: Authorization failed
  • 404 Not Found: Table or record not found
  • 429 Too Many Requests: Rate limit exceeded
  • 500 Internal Server Error: Server error

Performance

  • Asynchronous operation using Tokio
  • Efficient rate limiting with token bucket algorithm
  • Connection pooling support through DatabaseHandle
  • Minimal overhead for request processing

Testing

Run the comprehensive test suite:

Terminal window
# Run all tests
cargo test
# Run with output
cargo test -- --nocapture
# Run integration tests only
cargo test --test integration_test

The package includes:

  • 30+ unit tests
  • 15+ integration tests
  • 80% code coverage

License

MIT OR Apache-2.0

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.