API Reference Guide
API Reference Guide
Complete reference for the DataMagik Document Generation API with endpoints, parameters, and integration examples.
Table of Contents
- Authentication
- Base URL
- Endpoints
- Response Formats
- Error Handling
- Rate Limiting
- Best Practices
- Integration Examples
1. Authentication
All API requests require authentication using Bearer tokens or API keys.
Bearer Token (JWT)
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...API Key
X-API-Key: your-api-key-here2. Base URL
Production: https://data-magik.com
Development: https://dev.data-magik.com3. Endpoints
Generate Document
Generate a document from a template with dynamic data.
Endpoint: POST /api/document-designer/generate
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
template_id | integer/string | Yes | ID of the template to use |
branch | string | No | Template branch (default: "main") |
format | string | Yes | Output format: "html" or "pdf" |
data | object | Yes | Dynamic data to inject into template |
return_type | string | Yes | "url" for download link or "binary" for content |
document_settings | object | No | PDF generation settings |
file_name | string | No | Custom filename without extension |
priority | string | No | Queue priority: "urgent", "high", "normal", "low" |
Document Settings:
| Setting | Type | Description |
|---|---|---|
page_size | string | "A4", "A3", "Letter", "Legal", etc. |
orientation | string | "portrait" or "landscape" |
margin_top/right/bottom/left | float | Margins in inches |
show_page_number | boolean | Show page numbers |
print_background | boolean | Include background graphics |
header_template | string | Custom header HTML |
footer_template | string | Custom footer HTML |
ttlOptionId | integer | TTL option (1=24h, 2=7d, 3=30d, 4=90d, 5=1yr, -1=infinite) |
Get Generation Status
Endpoint: GET /api/document-designer/status/:request_id
List Templates
Endpoint: GET /api/document-designer/templates
| Parameter | Type | Description |
|---|---|---|
q | string | Search query |
page | integer | Page number (default: 1) |
size | integer | Items per page (default: 25, max: 100) |
Get Template Details
Endpoint: GET /api/document-designer/templates/:template_id
Get Template Categories
Endpoint: GET /api/document-designer/templates/categories
Create Template
Endpoint: POST /api/document-designer/templates
Update Template
Endpoint: PUT /api/document-designer/templates/:template_id
List Template Versions
Endpoint: GET /api/document-designer/templates/:template_id/versions
4. Response Formats
Success Response
{ "success": true, "data": { ... }, "message": "Operation completed successfully" }Error Response
{ "success": false, "error": "Error type", "message": "Detailed error message" }HTTP Status Codes
| Code | Meaning | Description |
|---|---|---|
| 200 | OK | Request successful |
| 201 | Created | Resource created |
| 400 | Bad Request | Invalid parameters |
| 401 | Unauthorized | Authentication required |
| 403 | Forbidden | Insufficient permissions |
| 404 | Not Found | Resource not found |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Server Error | Internal server error |
5. Error Handling
Common Error Types
// Template Not Found
{ "success": false, "error": "TemplateNotFound", "message": "Template with ID 123 does not exist" }
// Validation Error
{ "success": false, "error": "ValidationError", "details": { "template_id": "required" } }
// Quota Exceeded
{ "success": false, "error": "QuotaExceeded", "details": { "limit": 1000, "used": 1000 } }Error Handling Best Practices
- Always check the
successfield - Implement retry logic for transient errors (500, 503)
- Handle rate limiting gracefully (429)
6. Rate Limiting
Rate Limit Headers
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1632150000Handling Rate Limits
async function generateWithRetry(data, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try { return await generateDocument(data); }
catch (error) {
if (error.status === 429 && i < maxRetries - 1) {
await sleep(error.retry_after || Math.pow(2, i) * 1000);
continue;
}
throw error;
}
}
}7. Best Practices
Priority Selection
| Priority | Use Case |
|---|---|
urgent | User waiting for result |
normal | Standard processing (default) |
low | Bulk operations, batch jobs |
TTL Selection
| TTL | Duration | Use Case |
|---|---|---|
| 1 | 24 hours | Sensitive documents |
| 3 | 30 days | Standard documents |
| 5 | 1 year | Archive documents |
| -1 | Infinite | Permanent records |
Async Generation Pattern
async function generateAndWait(data) {
const response = await generateDocument(data);
if (response.status === 'queued' || response.status === 'processing') {
return await pollStatus(response.request_id);
}
return response;
}
async function pollStatus(requestId, maxAttempts = 60) {
for (let i = 0; i < maxAttempts; i++) {
const status = await getStatus(requestId);
if (status.status === 'completed') return status;
if (status.status === 'failed') throw new Error(status.error);
await sleep(2000);
}
throw new Error('Generation timeout');
}8. Integration Examples
Node.js Client
const axios = require('axios');
class DocumentClient {
constructor(baseURL, apiKey) {
this.client = axios.create({
baseURL,
headers: { 'X-API-Key': apiKey, 'Content-Type': 'application/json' }
});
}
async generate(templateId, data, options = {}) {
const response = await this.client.post('/api/document-designer/generate', {
template_id: templateId,
format: options.format || 'pdf',
data,
return_type: 'url',
document_settings: options.settings || { page_size: 'A4', ttlOptionId: 3 },
file_name: options.fileName,
priority: options.priority || 'normal'
});
if (response.data.status === 'queued') {
return await this.waitForCompletion(response.data.request_id);
}
return response.data;
}
async waitForCompletion(requestId, maxAttempts = 30) {
for (let i = 0; i < maxAttempts; i++) {
await new Promise(r => setTimeout(r, 2000));
const status = await this.client.get(`/api/document-designer/status/${requestId}`);
if (status.data.status === 'completed') return status.data;
if (status.data.status === 'failed') throw new Error(status.data.error);
}
throw new Error('Generation timeout');
}
}
const client = new DocumentClient('https://data-magik.com', 'your-api-key');
client.generate(123, { customer_name: 'Acme Corp', total: 1500 })
.then(r => console.log('URL:', r.download_url));For workflow automation, see the N8N Integration Guide. For template creation, see the Document Designer Guide.