API Reference Guide

Updated Mar 28, 2026
DataMagik Documents

API Reference Guide

Complete reference for the DataMagik Document Generation API with endpoints, parameters, and integration examples.

Table of Contents

  1. Authentication
  2. Base URL
  3. Endpoints
  4. Response Formats
  5. Error Handling
  6. Rate Limiting
  7. Best Practices
  8. 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-here

2. Base URL

Production: https://data-magik.com
Development: https://dev.data-magik.com

3. Endpoints

Generate Document

Generate a document from a template with dynamic data.

Endpoint: POST /api/document-designer/generate

Parameters:

ParameterTypeRequiredDescription
template_idinteger/stringYesID of the template to use
branchstringNoTemplate branch (default: "main")
formatstringYesOutput format: "html" or "pdf"
dataobjectYesDynamic data to inject into template
return_typestringYes"url" for download link or "binary" for content
document_settingsobjectNoPDF generation settings
file_namestringNoCustom filename without extension
prioritystringNoQueue priority: "urgent", "high", "normal", "low"

Document Settings:

SettingTypeDescription
page_sizestring"A4", "A3", "Letter", "Legal", etc.
orientationstring"portrait" or "landscape"
margin_top/right/bottom/leftfloatMargins in inches
show_page_numberbooleanShow page numbers
print_backgroundbooleanInclude background graphics
header_templatestringCustom header HTML
footer_templatestringCustom footer HTML
ttlOptionIdintegerTTL 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

ParameterTypeDescription
qstringSearch query
pageintegerPage number (default: 1)
sizeintegerItems 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

CodeMeaningDescription
200OKRequest successful
201CreatedResource created
400Bad RequestInvalid parameters
401UnauthorizedAuthentication required
403ForbiddenInsufficient permissions
404Not FoundResource not found
429Too Many RequestsRate limit exceeded
500Server ErrorInternal 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

  1. Always check the success field
  2. Implement retry logic for transient errors (500, 503)
  3. Handle rate limiting gracefully (429)

6. Rate Limiting

Rate Limit Headers

X-RateLimit-Limit: 60
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1632150000

Handling 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

PriorityUse Case
urgentUser waiting for result
normalStandard processing (default)
lowBulk operations, batch jobs

TTL Selection

TTLDurationUse Case
124 hoursSensitive documents
330 daysStandard documents
51 yearArchive documents
-1InfinitePermanent 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.

Was this page helpful?