JavaScript (Node.js)

Integrate the Flimpa API into your JavaScript applications.

Installation

For modern Node.js (v18+), you can use the native fetch and FormData APIs. No external dependencies are required.

Initialization

Set up your API key and base URL.

javascript
const API_KEY = 'your_api_key';
const BASE_URL = 'https://api.flimpa.com/api/v1';

Authentication

Authenticate your requests using the X-API-Key header for task creation, and the X-Task-Access-Token header for status and download requests.

Usage Example

This example demonstrates how to create a task, poll for its status, and download the result. Operations supported are compress-pdf and image-to-webp.

javascript
import { openAsBlob } from 'node:fs';

const API_KEY = 'your_api_key';
const BASE_URL = 'https://api.flimpa.com/api/v1';

async function processFile(filePath, operation) {
  // 1. Create Task (Upload)
  const formData = new FormData();
  formData.append('operation', operation);
  formData.append('file', await openAsBlob(filePath));

  const createRes = await fetch(`${BASE_URL}/tasks`, {
    method: 'POST',
    headers: { 'X-API-Key': API_KEY },
    body: formData
  });
  
  if (!createRes.ok) {
    const errorData = await createRes.json();
    throw new Error(`Failed to create task: ${errorData.error} (${errorData.code})`);
  }
  const { taskId, accessToken } = await createRes.json();

  // 2. Poll Status
  let delay = 1000;
  while (true) {
    const statusRes = await fetch(`${BASE_URL}/tasks/${taskId}`, {
      headers: { 'X-Task-Access-Token': accessToken }
    });
    const statusData = await statusRes.json();

    if (statusData.status === 'COMPLETED') break;
    if (statusData.status === 'FAILED') {
      throw new Error(`Task failed: ${statusData.error} (${statusData.code})`);
    }

    await new Promise(resolve => setTimeout(resolve, delay));
    delay = Math.min(delay * 2, 10000);
  }

  // 3. Download Result
  const downloadRes = await fetch(`${BASE_URL}/tasks/${taskId}/download`, {
    headers: { 'X-Task-Access-Token': accessToken }
  });
  
  if (!downloadRes.ok) {
    throw new Error('Failed to download result');
  }
  
  const arrayBuffer = await downloadRes.arrayBuffer();
  return Buffer.from(arrayBuffer);
}

// Usage
processFile('./input.pdf', 'compress-pdf')
  .then(buffer => console.log('Success! Size:', buffer.length))
  .catch(console.error);

Error Handling

Always check the response status and handle potential errors. The API returns JSON with error and code fields when a request fails.

Best Practices

  • Implement exponential backoff for polling (as shown in the example).
  • Files are limited to 20MB.
  • Tasks have a TTL of 1 hour. Download your results promptly.
  • Do not expose your API key in client-side code.

Webhooks

Webhooks for task completion are Coming Soon. For now, please use polling.