Python

Integrate the Flimpa API into your Python applications.

Installation

We recommend using the popular requests library.

bash
pip install requests

Initialization

Set up your API key and base URL.

python
import requests
import time

API_KEY = 'your_api_key'
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.

python
import requests
import time

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

def process_file(file_path, operation):
    # 1. Create Task (Upload)
    with open(file_path, 'rb') as f:
        files = {'file': f}
        data = {'operation': operation}
        headers = {'X-API-Key': API_KEY}
        
        res = requests.post(f"{BASE_URL}/tasks", headers=headers, files=files, data=data)
        
        if not res.ok:
            error_data = res.json()
            raise Exception(f"Failed to create task: {error_data.get('error')} ({error_data.get('code')})")
            
        task_data = res.json()
        task_id = task_data['taskId']
        access_token = task_data['accessToken']

    # 2. Poll Status
    delay = 1
    headers = {'X-Task-Access-Token': access_token}
    
    while True:
        res = requests.get(f"{BASE_URL}/tasks/{task_id}", headers=headers)
        res.raise_for_status()
        status_data = res.json()
        
        if status_data['status'] == 'COMPLETED':
            break
        if status_data['status'] == 'FAILED':
            raise Exception(f"Task failed: {status_data.get('error')} ({status_data.get('code')})")
            
        time.sleep(delay)
        delay = min(delay * 2, 10)

    # 3. Download Result
    res = requests.get(f"{BASE_URL}/tasks/{task_id}/download", headers=headers)
    res.raise_for_status()
    
    return res.content

# Usage
try:
    result = process_file('input.pdf', 'compress-pdf')
    with open('output.pdf', 'wb') as f:
        f.write(result)
    print("Success!")
except Exception as e:
    print(f"Error: {e}")

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.