Skip to content

How to Automate PDF Generation with the REST API

Trigger PDF mail merge jobs programmatically using the Mergram REST API. Authenticate with API keys, send merge requests, and download generated PDFs.

Automating PDF Generation with the REST API

Manual merge operations work well for occasional use, but production workflows often need programmatic access — generating invoices from your CRM, producing reports on a schedule, or integrating document generation into your application. The Mergram REST API lets you trigger PDF merges, monitor progress, and download results from any backend system.

Prerequisites

To use the REST API, you need:

API keys vs. session authentication

The REST API uses API key authentication (Bearer token), not browser session cookies. This is designed for server-to-server communication where no browser is involved. API keys are independent of user sessions and don’t expire unless revoked.

Authentication

All API requests require an API key sent as a Bearer token in the Authorization header:

Authorization: Bearer mg_your_api_key_here

Creating an API Key

  1. Navigate to Developer → API Keys in the Mergram dashboard
  2. Click Generate New Key
  3. Give it a descriptive name (e.g., “Production CRM Integration”)
  4. Copy the key immediately — it is shown only once
  5. Store it securely (environment variable, secrets manager)

API keys are team-scoped — they inherit the permissions of the team they belong to. Revoke a key at any time from the same settings page.


API Endpoints

The base URL for all API v1 endpoints is:

https://mergram.com/api/v1

Core Endpoints

MethodEndpointDescription
POST/mergeSubmit a new merge job
POST/emailSubmit a new email send job
GET/jobs/:idCheck job status and progress
GET/jobs/:id/outputGet download URLs for completed files
GET/templatesList available templates
GET/templates/:idGet template details

Submit a Merge Job

Send a POST request to /api/v1/merge with the following body:

{
  "templateId": "abc123-def456",
  "data": [
    { "InvoiceNumber": "INV-001", "ClientName": "Acme Corp", "Total": "$2,700.00" },
    { "InvoiceNumber": "INV-002", "ClientName": "Globex Inc", "Total": "$5,400.00" }
  ],
  "outputConfig": {
    "combinePdf": false,
    "filenameTemplate": "Invoice_[[InvoiceNumber]]"
  }
}
ParameterRequiredDescription
templateIdYesID of the saved template
dataYesArray of row objects. Keys must match the spreadsheet column headers used to create the template
outputConfigNoOutput settings: combinePdf (boolean), filenameTemplate (string with merge fields), passwordTemplate (string for per-PDF encryption)

Response (201 Created):

{
  "jobId": "abc123-def456-789",
  "status": "pending",
  "total": 2,
  "message": "Merge job enqueued. 2 rows will be processed."
}

Prepare your template with a spreadsheet first

Before using the API, create and save your template in the Mergram editor with a spreadsheet attached. The API uses the column headers from that spreadsheet to map your inline data. The template must have a PDF file and a configured data source.

Check Job Status

Poll GET /api/v1/jobs/:id to track progress:

curl -H "Authorization: Bearer mg_your_api_key" \
  https://mergram.com/api/v1/jobs/abc123-def456-789

Response:

{
  "id": "abc123-def456-789",
  "type": "pdf_merge",
  "status": "completed",
  "total": 2,
  "progress": 2,
  "progressMessage": "Completed",
  "output": {
    "files": [
      {
        "filename": "Invoice_INV-001.pdf",
        "downloadUrl": "https://mergram.com/api/v1/files/...",
        "size": 245678
      },
      {
        "filename": "Invoice_INV-002.pdf",
        "downloadUrl": "https://mergram.com/api/v1/files/...",
        "size": 251024
      }
    ]
  },
  "items": [
    { "id": "...", "itemIndex": 0, "status": "completed", "processedAt": "..." },
    { "id": "...", "itemIndex": 1, "status": "completed", "processedAt": "..." }
  ],
  "createdAt": "2025-01-28T10:30:00Z",
  "completedAt": "2025-01-28T10:30:45Z"
}

Job Status Values

StatusMeaning
pendingJob is queued, waiting for a worker
runningJob is actively processing
completedAll rows processed successfully
failedJob encountered an unrecoverable error
pausedJob was manually paused
cancelledJob was cancelled

Download Results

Fetch download URLs for all generated files:

# Get download URLs for all output files
curl -H "Authorization: Bearer mg_your_api_key" \
  https://mergram.com/api/v1/jobs/abc123-def456-789/output

# Download a specific file using the signed URL from the response
curl -o Invoice_INV-001.pdf \
  "https://mergram.com/api/v1/files/..."

The /output endpoint returns { files: [{ filename, downloadUrl, size }] } with signed URLs for each generated PDF.


Complete End-to-End Example

Here is a full workflow using curl:

# Step 1: Submit merge job
JOB_RESPONSE=$(curl -s -X POST \
  -H "Authorization: Bearer mg_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "templateId": "abc123-def456",
    "data": [
      { "InvoiceNumber": "INV-001", "ClientName": "Acme Corp", "Total": "$2,700.00" },
      { "InvoiceNumber": "INV-002", "ClientName": "Globex Inc", "Total": "$5,400.00" }
    ],
    "outputConfig": {
      "combinePdf": false,
      "filenameTemplate": "Invoice_[[InvoiceNumber]]"
    }
  }' \
  https://mergram.com/api/v1/merge)

# Step 2: Extract job ID
JOB_ID=$(echo $JOB_RESPONSE | jq -r '.jobId')
echo "Job submitted: $JOB_ID"

# Step 3: Poll for completion (every 5 seconds)
while true; do
  STATUS=$(curl -s -H "Authorization: Bearer mg_your_api_key" \
    https://mergram.com/api/v1/jobs/$JOB_ID | jq -r '.status')
  echo "Status: $STATUS"
  if [ "$STATUS" = "completed" ] || [ "$STATUS" = "failed" ]; then
    break
  fi
  sleep 5
done

# Step 4: Get download URLs
curl -s -H "Authorization: Bearer mg_your_api_key" \
  https://mergram.com/api/v1/jobs/$JOB_ID/output | jq '.files[]'

echo "Done. Download files using the URLs above."

Integration with Automation Platforms

Zapier Integration

Configure a custom webhook action in Zapier:

  1. Trigger: Any Zapier trigger (new CRM deal, form submission, scheduled time)
  2. Action: Webhooks by Zapier → Custom Request
    • Method: POST
    • URL: https://mergram.com/api/v1/merge
    • Headers: Authorization: Bearer mg_your_api_key
    • Payload: JSON body with templateId and data array
  3. Follow-up action: Use the response jobId to poll status

Make.com Integration

Use the HTTP module in Make.com:

  1. Add an HTTP module
  2. Set method to POST
  3. URL: https://mergram.com/api/v1/merge
  4. Add header: Authorization = Bearer mg_your_api_key
  5. Body type: application/json
  6. Map your scenario data to the request fields

Async processing model

The API processes merge jobs asynchronously. Your request returns immediately with a job ID, and the actual PDF generation happens in the background. This design handles large datasets (thousands of rows) without timeout issues. Poll the status endpoint until the job completes.

Error Handling

HTTP StatusMeaningAction
201Job created successfullyPoll for status
400Invalid request body or data formatCheck parameters and retry
401Missing or invalid API keyVerify your API key
402Insufficient creditsPurchase credits or check your balance
404Template not foundCheck the template ID
429Rate limit exceededWait and retry with backoff
500Server errorRetry after a short delay
{
  "error": "Template not found"
}

Best Practices for API Integration

  1. Store API keys in environment variables — Never hardcode keys in source code. Use a secrets manager or .env file (not committed to git)
  2. Implement exponential backoff — If polling returns running, increase the interval between checks (5s, 10s, 20s, etc.)
  3. Handle partial failures gracefully — A completed job may have some failed rows. Check the failed count in the progress object
  4. Cache template IDs — List templates once and cache the IDs rather than querying on every request
  5. Use webhooks for large jobs — For jobs processing thousands of rows, consider using automation platform webhooks instead of polling
  6. Validate data before submitting — Ensure your data array keys match the template’s column headers exactly and that all rows have the expected fields

Common Issues and Troubleshooting

401 Unauthorized errors: Verify the API key is correct and hasn’t been revoked. Check that the header format is exactly Authorization: Bearer mg_your_key (note the space after “Bearer”).

Job stuck in “pending” status: This may indicate all workers are busy. Large jobs may queue briefly during peak usage. Continue polling — the job will start when a worker becomes available.

Data validation errors: Ensure your data array keys exactly match the column headers used when the template was created. Column matching is case-sensitive. Check for extra whitespace or typos in key names.

Template ID not found: The template must be saved and belong to the same team as the API key. Create the template in the editor first, then retrieve its ID from the templates list endpoint.

Get Started

Generate an API key in Developer → API Keys, create a template in the editor, and submit your first merge job via curl or your preferred HTTP client. The API documentation in the playground provides an interactive reference for all endpoints.

Step-by-step guide

  1. 1

    Create API Key

    Go to Developer → API Keys and generate a new key. Copy and store it securely — it won't be shown again.

  2. 2

    Prepare Template

    Create and save a template in the Mergram editor. Note the template ID from the URL or API response.

  3. 3

    Submit Merge Job

    Send a POST request to /api/v1/merge with your template ID and data as a JSON array.

  4. 4

    Poll for Status

    Check job status via GET /api/v1/jobs/:id. When status is 'completed', retrieve download URLs.

  5. 5

    Download Results

    Fetch generated PDFs from the /api/v1/jobs/:id/output endpoint using the returned download URLs.

Frequently asked questions

How do I authenticate API requests?
Generate an API key in Developer → API Keys, then include it as a Bearer token in the Authorization header of every request. API keys are team-scoped and can be revoked at any time.
Can I trigger merges from Zapier or Make.com?
Yes. Both Zapier and Make.com support custom HTTP requests. Configure a webhook or HTTP action to call the Mergram merge endpoint with your API key, template ID, and data array.
Is there a rate limit on API requests?
API rate limits depend on your plan. The merge endpoint processes jobs asynchronously — you submit a job and poll for status rather than waiting for a synchronous response. This means you can submit multiple jobs in quick succession.
How do I provide data to the API?
The API accepts data as a JSON array of objects in the request body. Each object represents one row, with keys matching the column headers from your original spreadsheet. Export your data from any CRM, database, or spreadsheet and pass it directly as inline JSON.
Can I download generated PDFs programmatically?
Yes. After a merge job completes, the API returns download URLs for each generated PDF. Use these URLs to download files directly to your server or cloud storage. Downloads are available for 1 hour after job completion (configurable by your deployment).

Ready to try it yourself?

Start merging PDFs in minutes — free account required, no credit card needed.

Related articles