API Reference Guide

Last updated: October 6, 2025

API Reference Guide

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

Table of Contents

Authentication

All API requests require authentication using Bearer tokens or API keys.

Bearer Token (JWT)

Include in request headers:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

API Key

Include in request headers:

X-API-Key: your-api-key-here

Base URL

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

Endpoints

Generate Document

Generate a document from a template with dynamic data.

Endpoint: POST /api/document-designer/generate

Request Headers:

Authorization: Bearer YOUR_JWT_TOKEN
Content-Type: application/json

Request Body:

{
  "template_id": 123,
  "branch": "main",
  "version": "1.0.0",
  "format": "pdf",
  "data": {
    "customer_name": "John Doe",
    "invoice_number": "INV-2025-001",
    "amount": 1500.0,
    "items": [
      {
        "description": "Consulting Services",
        "quantity": 10,
        "rate": 150.0
      }
    ]
  },
  "return_type": "url",
  "document_settings": {
    "page_size": "A4",
    "orientation": "portrait",
    "margin_top": 1.0,
    "margin_right": 1.0,
    "margin_bottom": 1.0,
    "margin_left": 1.0,
    "show_page_number": true,
    "show_timestamp": true,
    "print_background": true,
    "header_template": "<div style='font-size: 10px;'>{{company_name}}</div>",
    "footer_template": "<div style='font-size: 10px;'>Page {{page}}</div>",
    "ttlOptionId": 3
  },
  "file_name": "invoice_2025_001",
  "force_regenerate": false,
  "priority": "normal"
}

Parameters:

ParameterTypeRequiredDescriptiontemplate_idinteger/stringYesID of the template to usebranchstringNoTemplate branch (default: "main")versionstringNoSpecific version (uses latest if not specified)formatstringYesOutput format: "html" or "pdf"dataobjectYesDynamic data to inject into templatereturn_typestringYes"url" for download link or "binary" for contentdocument_settingsobjectNoPDF generation settingsfile_namestringNoCustom filename without extensionforce_regeneratebooleanNoForce regeneration (skip cache)prioritystringNoQueue priority: "urgent", "high", "normal", "low"

Document Settings:

SettingTypeDescriptionpage_sizestring"A4", "A3", "Letter", "Legal", etc.orientationstring"portrait" or "landscape"margin_topfloatTop margin in inchesmargin_rightfloatRight margin in inchesmargin_bottomfloatBottom margin in inchesmargin_leftfloatLeft margin in inchesshow_page_numberbooleanShow page numbersshow_timestampbooleanShow generation timestampprint_backgroundbooleanInclude background graphicsheader_templatestringCustom header HTMLfooter_templatestringCustom footer HTMLttlOptionIdintegerTTL option (1=24h, 2=7d, 3=30d, 4=90d, 5=1yr, -1=infinite)

Response (Success):

{
  "success": true,
  "request_id": "req_abc123def456",
  "document_id": 456,
  "download_url": "https://s3.amazonaws.com/bucket/documents/abc123.pdf",
  "filename": "invoice_2025_001.pdf",
  "format": "pdf",
  "storage_key": "documents/abc123.pdf",
  "status": "completed",
  "metadata": {
    "generated_at": "2025-09-21T15:30:00Z",
    "template_version": "1.0.0",
    "expires_at": "2025-10-21T15:30:00Z",
    "file_size": 245680
  }
}

Response (Queued):

{
  "success": true,
  "request_id": "req_abc123def456",
  "status": "queued",
  "message": "Document generation queued",
  "estimated_wait_time_seconds": 30
}

Status Values:

  • queued - Request received, waiting for processing
  • processing - Currently generating document
  • completed - Document generated successfully
  • failed - Generation failed (check error message)

Get Generation Status

Check the status of a queued document generation request.

Endpoint: GET /api/document-designer/status/:request_id

Request Headers:

Authorization: Bearer YOUR_JWT_TOKEN

Response (Completed):

{
  "success": true,
  "request_id": "req_abc123def456",
  "status": "completed",
  "document_id": 456,
  "download_url": "https://s3.amazonaws.com/bucket/documents/abc123.pdf",
  "filename": "invoice_2025_001.pdf"
}

Response (Processing):

{
  "success": true,
  "request_id": "req_abc123def456",
  "status": "processing",
  "progress": 45,
  "message": "Generating PDF..."
}

Response (Failed):

{
  "success": false,
  "request_id": "req_abc123def456",
  "status": "failed",
  "error": "Template rendering failed: invalid syntax at line 45"
}

List Templates

Get all available templates for the authenticated company.

Endpoint: GET /api/document-designer/templates

Query Parameters:

ParameterTypeDescriptionqstringSearch query (searches name, description, category)deletedstringInclude deleted: "true", "false", or "all" (default: "false")pageintegerPage number (default: 1)sizeintegerItems per page (default: 25, max: 100)

Example Request:

GET /api/document-designer/templates?q=invoice&page=1&size=10
Authorization: Bearer YOUR_JWT_TOKEN

Response:

{
  "items": [
    {
      "templateId": "123",
      "companyId": 456,
      "name": "Invoice Template",
      "description": "Standard invoice template for customer billing",
      "category": "Invoices",
      "templateType": "report_body",
      "isActive": true,
      "createdBy": 789,
      "createdAt": "2025-09-01T10:00:00Z",
      "updatedAt": "2025-09-15T14:30:00Z",
      "ttlDays": 30,
      "categoryName": "Invoices",
      "categoryIcon": "<svg>...</svg>"
    }
  ],
  "page": 1,
  "size": 10,
  "total": 1
}

Get Template Details

Retrieve complete details for a specific template including HTML, CSS, and schema.

Endpoint: GET /api/document-designer/templates/:template_id

Response:

{
  "templateId": "123",
  "companyId": 456,
  "name": "Invoice Template",
  "description": "Standard invoice template for customer billing",
  "category": "Invoices",
  "templateType": "report_body",
  "isActive": true,
  "createdBy": 789,
  "createdAt": "2025-09-01T10:00:00Z",
  "updatedAt": "2025-09-15T14:30:00Z",
  "htmlContent": "<!DOCTYPE html><html>...</html>",
  "cssContent": "body { font-family: Arial, sans-serif; }",
  "jsonSchema": {
    "type": "object",
    "properties": {
      "customer_name": {
        "type": "string",
        "title": "Customer Name"
      },
      "invoice_number": {
        "type": "string",
        "title": "Invoice Number"
      }
    },
    "required": ["customer_name", "invoice_number"]
  },
  "sampleData": {
    "customer_name": "John Doe",
    "invoice_number": "INV-001"
  }
}

Get Template Categories

Get list of all available template categories.

Endpoint: GET /api/document-designer/templates/categories

Response:

{
  "categories": [
    "Invoices",
    "Receipts",
    "Reports",
    "Contracts",
    "Letters",
    "Proposals",
    "Labels",
    "Certificates"
  ]
}

Create Template

Create a new document template.

Endpoint: POST /api/document-designer/templates

Request Body:

{
  "name": "New Invoice Template",
  "description": "Custom invoice template for premium clients",
  "category": "Invoices",
  "templateType": "report_body"
}

Response:

{
  "success": true,
  "template_id": 789,
  "message": "Template created successfully"
}

Update Template

Update an existing template's metadata.

Endpoint: PUT /api/document-designer/templates/:template_id

Request Body:

{
  "name": "Updated Invoice Template",
  "description": "Updated description",
  "category": "Invoices",
  "isActive": true
}

Response:

{
  "success": true,
  "message": "Template updated successfully"
}

List Template Versions

Get version history for a template.

Endpoint: GET /api/document-designer/templates/:template_id/versions

Response:

{
  "versions": [
    {
      "versionId": "101",
      "templateId": "123",
      "versionNumber": "1.2.0",
      "branchName": "main",
      "parentVersionId": 100,
      "commitMessage": "Updated styling and layout",
      "committedBy": 789,
      "committedAt": "2025-09-15T14:30:00Z",
      "isApproved": true,
      "approvedBy": 456,
      "approvalDate": "2025-09-15T15:00:00Z",
      "isActive": true
    }
  ]
}

Response Formats

Success Response

{
  "success": true,
  "data": { /* response data */ },
  "message": "Operation completed successfully"
}

Error Response

{
  "success": false,
  "error": "Error type",
  "message": "Detailed error message",
  "details": {
    "field": "Additional error context"
  }
}

HTTP Status Codes

CodeMeaningDescription200OKRequest successful201CreatedResource created successfully204No ContentRequest successful, no content to return400Bad RequestInvalid request parameters401UnauthorizedAuthentication required or invalid403ForbiddenInsufficient permissions404Not FoundResource not found409ConflictResource conflict (e.g., duplicate)422Unprocessable EntityValidation errors429Too Many RequestsRate limit exceeded500Internal Server ErrorServer error503Service UnavailableService temporarily unavailable

Error Handling

Common Error Types

Template Not Found:

{
  "success": false,
  "error": "TemplateNotFound",
  "message": "Template with ID 123 does not exist or is not accessible"
}

Validation Error:

{
  "success": false,
  "error": "ValidationError",
  "message": "Invalid request parameters",
  "details": {
    "template_id": "required field missing",
    "format": "must be 'html' or 'pdf'"
  }
}

Quota Exceeded:

{
  "success": false,
  "error": "QuotaExceeded",
  "message": "Monthly document generation quota exceeded",
  "details": {
    "limit": 1000,
    "used": 1000,
    "reset_date": "2025-10-01T00:00:00Z"
  }
}

Generation Failed:

{
  "success": false,
  "error": "GenerationFailed",
  "message": "Document generation failed",
  "details": {
    "reason": "Template syntax error at line 45",
    "line": 45,
    "column": 12
  }
}

Error Handling Best Practices

  1. Always check success field
  2. Log error details for debugging
  3. Implement retry logic for transient errors (500, 503)
  4. Display user-friendly messages
  5. Handle rate limiting gracefully (429)

Example Error Handler:

async function generateDocument(data) {
  try {
    const response = await fetch('/api/document-designer/generate', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    });

    const result = await response.json();

    if (!result.success) {
      switch (result.error) {
        case 'QuotaExceeded':
          throw new Error('Monthly quota exceeded. Please upgrade your plan.');
        case 'TemplateNotFound':
          throw new Error('Template not found. Please check template ID.');
        case 'ValidationError':
          throw new Error(`Validation error: ${Object.values(result.details).join(', ')}`);
        default:
          throw new Error(result.message || 'Document generation failed');
      }
    }

    return result;
  } catch (error) {
    console.error('Document generation error:', error);
    throw error;
  }
}

Rate Limiting

Limits

  • Free Tier: 60 requests/minute, 1,000 documents/month
  • Pro Tier: 120 requests/minute, 10,000 documents/month
  • Enterprise: Custom limits

Rate Limit Headers

Response includes rate limit information:

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

Handling Rate Limits

When rate limit is exceeded (429 status):

{
  "success": false,
  "error": "RateLimitExceeded",
  "message": "Rate limit exceeded. Please try again later.",
  "retry_after": 30
}

Retry Logic:

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) {
        const retryAfter = error.retry_after || Math.pow(2, i) * 1000;
        await sleep(retryAfter);
        continue;
      }
      throw error;
    }
  }
}

Best Practices

1. Use Appropriate Priority

// Urgent - user waiting (highest priority)
priority: "urgent"

// Normal - background processing (default)
priority: "normal"

// Low - bulk operations
priority: "low"

2. Cache When Possible

Use force_regenerate: false for repeated requests with same data:

{
  "template_id": 123,
  "data": sameData,
  "force_regenerate": false  // Use cached version if available
}

3. Set Appropriate TTL

Choose TTL based on document sensitivity:

{
  "document_settings": {
    "ttlOptionId": 1  // 24 hours for sensitive documents
    "ttlOptionId": 3  // 30 days for standard documents
    "ttlOptionId": -1 // Infinite for permanent records
  }
}

4. Handle Async Generation

For large documents, poll status endpoint:

async function generateAndWait(data) {
  // Start generation
  const response = await generateDocument(data);
  
  if (response.status === 'queued' || response.status === 'processing') {
    // Poll for completion
    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); // Wait 2 seconds
  }
  
  throw new Error('Generation timeout');
}

5. Validate Data Before Sending

function validateInvoiceData(data) {
  if (!data.invoice_number) {
    throw new Error('Invoice number is required');
  }
  
  if (!Array.isArray(data.items) || data.items.length === 0) {
    throw new Error('At least one line item is required');
  }
  
  if (data.total <= 0) {
    throw new Error('Total must be greater than zero');
  }
  
  return true;
}

6. Use Descriptive Filenames

{
  "file_name": `invoice_${customerName}_${invoiceNumber}_${date}`
}

7. Include Metadata

Track generation context:

{
  "data": {
    // ... your data
    "_metadata": {
      "generated_by": userId,
      "source_system": "CRM",
      "batch_id": batchId
    }
  }
}

Integration Examples

Complete Node.js Example

const axios = require('axios');

class DocumentGenerationClient {
  constructor(baseURL, apiKey) {
    this.client = axios.create({
      baseURL,
      headers: {
        'X-API-Key': apiKey,
        'Content-Type': 'application/json'
      }
    });
  }

  async generateInvoice(invoiceData) {
    try {
      const response = await this.client.post('/api/document-designer/generate', {
        template_id: 123,
        format: 'pdf',
        data: invoiceData,
        return_type: 'url',
        document_settings: {
          page_size: 'A4',
          orientation: 'portrait',
          show_page_number: true,
          ttlOptionId: 3
        },
        file_name: `invoice_${invoiceData.invoice_number}`,
        priority: 'normal'
      });

      if (response.data.status === 'queued') {
        return await this.waitForCompletion(response.data.request_id);
      }

      return response.data;
    } catch (error) {
      console.error('Invoice generation failed:', error.response?.data || error.message);
      throw error;
    }
  }

  async waitForCompletion(requestId, maxAttempts = 30) {
    for (let i = 0; i < maxAttempts; i++) {
      await new Promise(resolve => setTimeout(resolve, 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');
  }
}

// Usage
const client = new DocumentGenerationClient(
  'https://data-magik.com',
  'your-api-key'
);

const invoiceData = {
  invoice_number: 'INV-2025-001',
  customer_name: 'Acme Corp',
  items: [
    { description: 'Consulting', quantity: 10, price: 150 }
  ],
  total: 1500
};

client.generateInvoice(invoiceData)
  .then(result => console.log('Invoice URL:', result.download_url))
  .catch(error => console.error('Error:', error));

Next Steps

Need Help? Contact support or check the documentation for detailed examples and troubleshooting guides.

Was this page helpful?