🛠️ Developer Guides
Complete integration guides for the Grim Reaper API in multiple programming languages
🐍 Python Integration Guide
Installation
pip install grim-reaper-sdk
Quick Start
from grim_reaper import GrimReaperAPI
# Initialize the API client
api = GrimReaperAPI(
api_key="your_api_key",
base_url="https://api.grim.so"
)
# Create a backup
backup = api.create_backup([
{
"type": "database",
"connection": {
"host": "localhost",
"database": "myapp",
"username": "user",
"password": "password"
}
}
])
print(f"Backup ID: {backup['backup_id']}")
Complete Example
import asyncio
from grim_reaper import GrimReaperAPI, BackupSource, BackupOptions
class BackupManager:
def __init__(self, api_key):
self.api = GrimReaperAPI(api_key)
async def create_database_backup(self, db_config):
"""Create a database backup with progress monitoring"""
source = BackupSource.database(
host=db_config['host'],
port=db_config.get('port', 5432),
database=db_config['database'],
username=db_config['username'],
password=db_config['password']
)
options = BackupOptions(
compression='gzip',
encryption=True,
retention_days=30,
notify_on_completion=True
)
# Create backup
backup = await self.api.create_backup([source], options)
backup_id = backup['backup_id']
# Monitor progress
while True:
status = await self.api.get_backup_status(backup_id)
print(f"Progress: {status['progress']}%")
if status['status'] in ['completed', 'failed']:
break
await asyncio.sleep(10)
return status
async def restore_backup(self, backup_id, target_config):
"""Restore a backup to a target location"""
restore = await self.api.create_restore(
backup_id=backup_id,
targets=[{
"type": "database",
"connection": target_config,
"options": {
"drop_existing": True,
"preserve_permissions": True
}
}]
)
return restore
# Usage example
async def main():
manager = BackupManager("your_api_key")
# Create backup
db_config = {
"host": "localhost",
"database": "production_db",
"username": "backup_user",
"password": "secure_password"
}
result = await manager.create_database_backup(db_config)
print(f"Backup completed: {result['status']}")
if __name__ == "__main__":
asyncio.run(main())
Error Handling
from grim_reaper import GrimReaperAPI, GrimReaperError
try:
api = GrimReaperAPI("invalid_key")
backup = api.create_backup([])
except GrimReaperError as e:
print(f"API Error: {e.message}")
print(f"Error Code: {e.code}")
print(f"Request ID: {e.request_id}")
except Exception as e:
print(f"Unexpected error: {e}")
Webhook Integration
from flask import Flask, request
from grim_reaper import WebhookVerifier
app = Flask(__name__)
verifier = WebhookVerifier("your_webhook_secret")
@app.route('/webhook', methods=['POST'])
def webhook_handler():
# Verify webhook signature
if not verifier.verify(request.headers, request.data):
return "Invalid signature", 401
event = request.json
if event['type'] == 'backup.completed':
print(f"Backup {event['data']['backup_id']} completed")
# Handle backup completion
elif event['type'] == 'backup.failed':
print(f"Backup {event['data']['backup_id']} failed")
# Handle backup failure
return "OK", 200
🟨 JavaScript/Node.js Integration Guide
Installation
npm install grim-reaper-sdk
Quick Start
const { GrimReaperAPI } = require('grim-reaper-sdk');
// Initialize the API client
const api = new GrimReaperAPI({
apiKey: 'your_api_key',
baseUrl: 'https://api.grim.so'
});
// Create a backup
async function createBackup() {
try {
const backup = await api.createBackup([
{
type: 'database',
connection: {
host: 'localhost',
database: 'myapp',
username: 'user',
password: 'password'
}
}
]);
console.log(`Backup ID: ${backup.backup_id}`);
} catch (error) {
console.error('Backup failed:', error.message);
}
}
createBackup();
Complete Example
const { GrimReaperAPI, BackupSource, BackupOptions } = require('grim-reaper-sdk');
class BackupManager {
constructor(apiKey) {
this.api = new GrimReaperAPI({ apiKey });
}
async createDatabaseBackup(dbConfig) {
const source = new BackupSource.Database({
host: dbConfig.host,
port: dbConfig.port || 5432,
database: dbConfig.database,
username: dbConfig.username,
password: dbConfig.password
});
const options = new BackupOptions({
compression: 'gzip',
encryption: true,
retentionDays: 30,
notifyOnCompletion: true
});
// Create backup
const backup = await this.api.createBackup([source], options);
const backupId = backup.backup_id;
// Monitor progress
while (true) {
const status = await this.api.getBackupStatus(backupId);
console.log(`Progress: ${status.progress}%`);
if (['completed', 'failed'].includes(status.status)) {
break;
}
await new Promise(resolve => setTimeout(resolve, 10000));
}
return status;
}
async restoreBackup(backupId, targetConfig) {
const restore = await this.api.createRestore({
backupId,
targets: [{
type: 'database',
connection: targetConfig,
options: {
dropExisting: true,
preservePermissions: true
}
}]
});
return restore;
}
}
// Usage example
async function main() {
const manager = new BackupManager('your_api_key');
const dbConfig = {
host: 'localhost',
database: 'production_db',
username: 'backup_user',
password: 'secure_password'
};
try {
const result = await manager.createDatabaseBackup(dbConfig);
console.log(`Backup completed: ${result.status}`);
} catch (error) {
console.error('Backup failed:', error);
}
}
main();
Express.js Webhook Handler
const express = require('express');
const { WebhookVerifier } = require('grim-reaper-sdk');
const app = express();
const verifier = new WebhookVerifier('your_webhook_secret');
app.use(express.json());
app.post('/webhook', (req, res) => {
// Verify webhook signature
if (!verifier.verify(req.headers, req.body)) {
return res.status(401).send('Invalid signature');
}
const event = req.body;
switch (event.type) {
case 'backup.completed':
console.log(`Backup ${event.data.backup_id} completed`);
// Handle backup completion
break;
case 'backup.failed':
console.log(`Backup ${event.data.backup_id} failed`);
// Handle backup failure
break;
default:
console.log(`Unknown event type: ${event.type}`);
}
res.status(200).send('OK');
});
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});
🐘 PHP Integration Guide
Installation
composer require grim-reaper/php-sdk
Quick Start
<?php
require_once 'vendor/autoload.php';
use GrimReaper\GrimReaperAPI;
// Initialize the API client
$api = new GrimReaperAPI([
'api_key' => 'your_api_key',
'base_url' => 'https://api.grim.so'
]);
// Create a backup
try {
$backup = $api->createBackup([
[
'type' => 'database',
'connection' => [
'host' => 'localhost',
'database' => 'myapp',
'username' => 'user',
'password' => 'password'
]
]
]);
echo "Backup ID: " . $backup['backup_id'] . "\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Complete Example
<?php
require_once 'vendor/autoload.php';
use GrimReaper\GrimReaperAPI;
use GrimReaper\BackupSource;
use GrimReaper\BackupOptions;
class BackupManager {
private $api;
public function __construct($apiKey) {
$this->api = new GrimReaperAPI(['api_key' => $apiKey]);
}
public function createDatabaseBackup($dbConfig) {
$source = BackupSource::database([
'host' => $dbConfig['host'],
'port' => $dbConfig['port'] ?? 5432,
'database' => $dbConfig['database'],
'username' => $dbConfig['username'],
'password' => $dbConfig['password']
]);
$options = new BackupOptions([
'compression' => 'gzip',
'encryption' => true,
'retention_days' => 30,
'notify_on_completion' => true
]);
// Create backup
$backup = $this->api->createBackup([$source], $options);
$backupId = $backup['backup_id'];
// Monitor progress
do {
$status = $this->api->getBackupStatus($backupId);
echo "Progress: {$status['progress']}%\n";
if (in_array($status['status'], ['completed', 'failed'])) {
break;
}
sleep(10);
} while (true);
return $status;
}
public function restoreBackup($backupId, $targetConfig) {
$restore = $this->api->createRestore([
'backup_id' => $backupId,
'targets' => [
[
'type' => 'database',
'connection' => $targetConfig,
'options' => [
'drop_existing' => true,
'preserve_permissions' => true
]
]
]
]);
return $restore;
}
}
// Usage example
$manager = new BackupManager('your_api_key');
$dbConfig = [
'host' => 'localhost',
'database' => 'production_db',
'username' => 'backup_user',
'password' => 'secure_password'
];
try {
$result = $manager->createDatabaseBackup($dbConfig);
echo "Backup completed: {$result['status']}\n";
} catch (Exception $e) {
echo "Backup failed: " . $e->getMessage() . "\n";
}
Laravel Integration
<?php
namespace App\Services;
use GrimReaper\GrimReaperAPI;
use Illuminate\Support\Facades\Log;
class GrimReaperService {
private $api;
public function __construct() {
$this->api = new GrimReaperAPI([
'api_key' => config('grim.api_key'),
'base_url' => config('grim.base_url')
]);
}
public function createBackup($sources, $options = []) {
try {
return $this->api->createBackup($sources, $options);
} catch (Exception $e) {
Log::error('Grim Reaper backup failed', [
'error' => $e->getMessage(),
'sources' => $sources
]);
throw $e;
}
}
public function getBackupStatus($backupId) {
return $this->api->getBackupStatus($backupId);
}
}
// In your controller
class BackupController extends Controller {
private $grimService;
public function __construct(GrimReaperService $grimService) {
$this->grimService = $grimService;
}
public function create(Request ) {
$backup = $this->grimService->createBackup(
->input('sources'),
->input('options', [])
);
return response()->json($backup);
}
}
☕ Java Integration Guide
Maven Dependency
<dependency>
<groupId>com.grimreaper</groupId>
<artifactId>grim-reaper-sdk</artifactId>
<version>1.0.0</version>
</dependency>
Quick Start
import com.grimreaper.GrimReaperAPI;
import com.grimreaper.models.BackupSource;
import com.grimreaper.models.BackupOptions;
public class BackupExample {
public static void main(String[] args) {
// Initialize the API client
GrimReaperAPI api = new GrimReaperAPI.Builder()
.apiKey("your_api_key")
.baseUrl("https://api.grim.so")
.build();
// Create backup source
BackupSource source = BackupSource.database()
.host("localhost")
.database("myapp")
.username("user")
.password("password")
.build();
// Create backup options
BackupOptions options = BackupOptions.builder()
.compression("gzip")
.encryption(true)
.retentionDays(30)
.notifyOnCompletion(true)
.build();
try {
// Create backup
BackupResponse backup = api.createBackup(Arrays.asList(source), options);
System.out.println("Backup ID: " + backup.getBackupId());
} catch (GrimReaperException e) {
System.err.println("Backup failed: " + e.getMessage());
}
}
}
Complete Example
import com.grimreaper.GrimReaperAPI;
import com.grimreaper.models.*;
import java.util.concurrent.CompletableFuture;
public class BackupManager {
private final GrimReaperAPI api;
public BackupManager(String apiKey) {
this.api = new GrimReaperAPI.Builder()
.apiKey(apiKey)
.build();
}
public CompletableFuture<BackupStatus> createDatabaseBackup(DatabaseConfig dbConfig) {
BackupSource source = BackupSource.database()
.host(dbConfig.getHost())
.port(dbConfig.getPort())
.database(dbConfig.getDatabase())
.username(dbConfig.getUsername())
.password(dbConfig.getPassword())
.build();
BackupOptions options = BackupOptions.builder()
.compression("gzip")
.encryption(true)
.retentionDays(30)
.notifyOnCompletion(true)
.build();
return CompletableFuture.supplyAsync(() -> {
try {
// Create backup
BackupResponse backup = api.createBackup(Arrays.asList(source), options);
String backupId = backup.getBackupId();
// Monitor progress
while (true) {
BackupStatus status = api.getBackupStatus(backupId);
System.out.println("Progress: " + status.getProgress() + "%");
if (status.getStatus() == BackupStatus.Status.COMPLETED ||
status.getStatus() == BackupStatus.Status.FAILED) {
return status;
}
Thread.sleep(10000);
}
} catch (Exception e) {
throw new RuntimeException("Backup failed", e);
}
});
}
public CompletableFuture<RestoreResponse> restoreBackup(String backupId, DatabaseConfig targetConfig) {
RestoreTarget target = RestoreTarget.database()
.connection(targetConfig)
.options(RestoreOptions.builder()
.dropExisting(true)
.preservePermissions(true)
.build())
.build();
return CompletableFuture.supplyAsync(() -> {
try {
return api.createRestore(backupId, Arrays.asList(target));
} catch (GrimReaperException e) {
throw new RuntimeException("Restore failed", e);
}
});
}
}
// Usage example
public class Main {
public static void main(String[] args) {
BackupManager manager = new BackupManager("your_api_key");
DatabaseConfig dbConfig = DatabaseConfig.builder()
.host("localhost")
.database("production_db")
.username("backup_user")
.password("secure_password")
.build();
manager.createDatabaseBackup(dbConfig)
.thenAccept(status -> {
System.out.println("Backup completed: " + status.getStatus());
})
.exceptionally(throwable -> {
System.err.println("Backup failed: " + throwable.getMessage());
return null;
});
}
}
🔷 C# Integration Guide
NuGet Package
Install-Package GrimReaper.SDK
Quick Start
using GrimReaper.SDK;
using GrimReaper.SDK.Models;
class Program {
static async Task Main(string[] args) {
// Initialize the API client
var api = new GrimReaperAPI(new GrimReaperConfig {
ApiKey = "your_api_key",
BaseUrl = "https://api.grim.so"
});
// Create backup source
var source = new DatabaseBackupSource {
Host = "localhost",
Database = "myapp",
Username = "user",
Password = "password"
};
// Create backup options
var options = new BackupOptions {
Compression = CompressionType.Gzip,
Encryption = true,
RetentionDays = 30,
NotifyOnCompletion = true
};
try {
// Create backup
var backup = await api.CreateBackupAsync(new[] { source }, options);
Console.WriteLine($"Backup ID: {backup.BackupId}");
} catch (GrimReaperException ex) {
Console.WriteLine($"Backup failed: {ex.Message}");
}
}
}
Complete Example
using GrimReaper.SDK;
using GrimReaper.SDK.Models;
using System;
using System.Threading.Tasks;
public class BackupManager {
private readonly GrimReaperAPI _api;
public BackupManager(string apiKey) {
_api = new GrimReaperAPI(new GrimReaperConfig {
ApiKey = apiKey
});
}
public async Task<BackupStatus> CreateDatabaseBackupAsync(DatabaseConfig dbConfig) {
var source = new DatabaseBackupSource {
Host = dbConfig.Host,
Port = dbConfig.Port,
Database = dbConfig.Database,
Username = dbConfig.Username,
Password = dbConfig.Password
};
var options = new BackupOptions {
Compression = CompressionType.Gzip,
Encryption = true,
RetentionDays = 30,
NotifyOnCompletion = true
};
// Create backup
var backup = await _api.CreateBackupAsync(new[] { source }, options);
var backupId = backup.BackupId;
// Monitor progress
while (true) {
var status = await _api.GetBackupStatusAsync(backupId);
Console.WriteLine($"Progress: {status.Progress}%");
if (status.Status == BackupStatusType.Completed ||
status.Status == BackupStatusType.Failed) {
return status;
}
await Task.Delay(10000);
}
}
public async Task<RestoreResponse> RestoreBackupAsync(string backupId, DatabaseConfig targetConfig) {
var target = new DatabaseRestoreTarget {
Connection = targetConfig,
Options = new RestoreOptions {
DropExisting = true,
PreservePermissions = true
}
};
return await _api.CreateRestoreAsync(backupId, new[] { target });
}
}
// Usage example
class Program {
static async Task Main(string[] args) {
var manager = new BackupManager("your_api_key");
var dbConfig = new DatabaseConfig {
Host = "localhost",
Database = "production_db",
Username = "backup_user",
Password = "secure_password"
};
try {
var result = await manager.CreateDatabaseBackupAsync(dbConfig);
Console.WriteLine($"Backup completed: {result.Status}");
} catch (Exception ex) {
Console.WriteLine($"Backup failed: {ex.Message}");
}
}
}
🐹 Go Integration Guide
Installation
go get github.com/grim-reaper/go-sdk
Quick Start
package main
import (
"fmt"
"log"
"github.com/grim-reaper/go-sdk"
)
func main() {
// Initialize the API client
client := grimreaper.NewClient(&grimreaper.Config{
APIKey: "your_api_key",
BaseURL: "https://api.grim.so",
})
// Create backup source
source := &grimreaper.DatabaseSource{
Host: "localhost",
Database: "myapp",
Username: "user",
Password: "password",
}
// Create backup options
options := &grimreaper.BackupOptions{
Compression: "gzip",
Encryption: true,
RetentionDays: 30,
NotifyOnCompletion: true,
}
// Create backup
backup, err := client.CreateBackup([]grimreaper.Source{source}, options)
if err != nil {
log.Fatalf("Backup failed: %v", err)
}
fmt.Printf("Backup ID: %s\n", backup.BackupID)
}
Complete Example
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/grim-reaper/go-sdk"
)
type BackupManager struct {
client *grimreaper.Client
}
func NewBackupManager(apiKey string) *BackupManager {
return &BackupManager{
client: grimreaper.NewClient(&grimreaper.Config{
APIKey: apiKey,
}),
}
}
func (bm *BackupManager) CreateDatabaseBackup(ctx context.Context, dbConfig *DatabaseConfig) (*grimreaper.BackupStatus, error) {
source := &grimreaper.DatabaseSource{
Host: dbConfig.Host,
Port: dbConfig.Port,
Database: dbConfig.Database,
Username: dbConfig.Username,
Password: dbConfig.Password,
}
options := &grimreaper.BackupOptions{
Compression: "gzip",
Encryption: true,
RetentionDays: 30,
NotifyOnCompletion: true,
}
// Create backup
backup, err := bm.client.CreateBackup([]grimreaper.Source{source}, options)
if err != nil {
return nil, fmt.Errorf("failed to create backup: %w", err)
}
backupID := backup.BackupID
// Monitor progress
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-ticker.C:
status, err := bm.client.GetBackupStatus(backupID)
if err != nil {
return nil, fmt.Errorf("failed to get backup status: %w", err)
}
fmt.Printf("Progress: %d%%\n", status.Progress)
if status.Status == grimreaper.StatusCompleted ||
status.Status == grimreaper.StatusFailed {
return status, nil
}
}
}
}
func (bm *BackupManager) RestoreBackup(ctx context.Context, backupID string, targetConfig *DatabaseConfig) (*grimreaper.RestoreResponse, error) {
target := &grimreaper.DatabaseTarget{
Connection: targetConfig,
Options: &grimreaper.RestoreOptions{
DropExisting: true,
PreservePermissions: true,
},
}
return bm.client.CreateRestore(backupID, []grimreaper.Target{target})
}
type DatabaseConfig struct {
Host string
Port int
Database string
Username string
Password string
}
func main() {
manager := NewBackupManager("your_api_key")
dbConfig := &DatabaseConfig{
Host: "localhost",
Database: "production_db",
Username: "backup_user",
Password: "secure_password",
}
ctx := context.Background()
result, err := manager.CreateDatabaseBackup(ctx, dbConfig)
if err != nil {
log.Fatalf("Backup failed: %v", err)
}
fmt.Printf("Backup completed: %s\n", result.Status)
}
📋 Best Practices
🔐 Security
- Store API keys securely using environment variables or secure key management systems
- Never hardcode API keys in source code
- Use HTTPS for all API communications
- Implement proper error handling to avoid exposing sensitive information
- Rotate API keys regularly
⚡ Performance
- Use async/await patterns for non-blocking operations
- Implement proper retry logic with exponential backoff
- Monitor rate limits and implement appropriate throttling
- Use connection pooling for database operations
- Cache frequently accessed data when appropriate
🛡️ Error Handling
- Always handle API errors gracefully
- Implement proper logging for debugging
- Use specific exception types for different error scenarios
- Provide meaningful error messages to users
- Implement circuit breakers for critical operations
📊 Monitoring
- Implement comprehensive logging
- Monitor API response times and success rates
- Set up alerts for failed operations
- Track backup and restore metrics
- Monitor storage usage and costs