Back

How to Use the Deflato API: Developer Tutorial

Why Use an Image Compression API?

Manual image compression doesn't scale. If your application handles user uploads, generates thumbnails, processes product catalogs, or builds static sites with hundreds of pages, you need programmatic image optimization. An API lets you compress, resize, and convert images as part of your automated workflow — whether that's a CI/CD pipeline, a serverless function, a CMS webhook, or a background job.

The Deflato API provides a simple REST interface for image compression and format conversion. It supports JPEG, PNG, WebP, AVIF, HEIC, TIFF, and PDF input, with JPEG, WebP, and AVIF output. This tutorial covers everything you need to get started.

Getting Your API Key

  1. Create an account at deflato.com if you don't have one.
  2. Navigate to Settings → API in your dashboard.
  3. Click Generate API Key. Copy the key — it will only be shown once.
  4. Store the key securely. Use environment variables (DEFLATO_API_KEY) rather than hardcoding it in your source code.

API keys are scoped to your account and inherit your plan's rate limits and quotas. The free tier includes 100 API compressions per month. Pro and Team plans offer higher limits.

API Basics: cURL Examples

The Deflato API exposes a single endpoint for image compression:

POST https://deflato.com/api/v1/compress

It accepts multipart/form-data with the image file and optional parameters.

Basic Compression

# Compress a JPEG with default settings
curl -X POST https://deflato.com/api/v1/compress   -H "Authorization: Bearer $DEFLATO_API_KEY"   -F "file=@photo.jpg"   --output compressed.jpg

Without additional parameters, the API applies sensible defaults: same output format as input, quality 80, no resizing, EXIF stripped.

Format Conversion

# Convert JPEG to WebP
curl -X POST https://deflato.com/api/v1/compress   -H "Authorization: Bearer $DEFLATO_API_KEY"   -F "file=@photo.jpg"   -F "output_format=WEBP"   -F "quality=80"   --output photo.webp

Resize and Compress

# Resize to max 1920px, convert to AVIF at quality 70
curl -X POST https://deflato.com/api/v1/compress   -H "Authorization: Bearer $DEFLATO_API_KEY"   -F "file=@photo.jpg"   -F "output_format=AVIF"   -F "quality=70"   -F "max_dimension=1920"   --output photo.avif

HEIC to JPEG Conversion

# Convert iPhone HEIC photo to JPEG
curl -X POST https://deflato.com/api/v1/compress   -H "Authorization: Bearer $DEFLATO_API_KEY"   -F "file=@IMG_1234.heic"   -F "output_format=JPEG"   -F "quality=85"   --output photo.jpg

API Parameters Reference

Parameter Type Default Description
file File required The image file to compress (JPEG, PNG, WebP, AVIF, HEIC, TIFF, or PDF)
output_format String Same as input Output format: JPEG, WEBP, or AVIF
quality Integer 80 Compression quality (1–100). Lower = smaller file, more artifacts
max_dimension Integer 0 (no resize) Maximum width or height in pixels. The image is scaled proportionally
strip_exif Boolean true Remove EXIF/metadata from the output

Python SDK

The Deflato Python SDK wraps the REST API with a clean Pythonic interface. Install it via pip:

pip install deflato

Basic Usage

import deflato

client = deflato.Client(api_key="YOUR_API_KEY")

# Compress a single image
result = client.compress(
    "photo.jpg",
    output_format="WEBP",
    quality=80,
    max_dimension=1920
)
result.save("photo.webp")

print(f"Original: {result.original_size / 1024:.0f} KB")
print(f"Compressed: {result.compressed_size / 1024:.0f} KB")
print(f"Savings: {result.savings_percent:.1f}%")

Batch Processing

import deflato
from pathlib import Path

client = deflato.Client(api_key="YOUR_API_KEY")

input_dir = Path("./images")
output_dir = Path("./optimized")
output_dir.mkdir(exist_ok=True)

for image_path in input_dir.glob("*.jpg"):
    result = client.compress(
        str(image_path),
        output_format="WEBP",
        quality=80
    )
    result.save(output_dir / f"{image_path.stem}.webp")
    print(f"{image_path.name}: {result.savings_percent:.1f}% saved")

Using with Django

# In your Django view or signal handler
import deflato
from django.core.files.base import ContentFile

client = deflato.Client(api_key=settings.DEFLATO_API_KEY)

def optimize_upload(instance, **kwargs):
    if instance.image:
        result = client.compress(
            instance.image.path,
            output_format="WEBP",
            quality=80,
            max_dimension=1600
        )
        # Save optimized version
        instance.image.save(
            f"{instance.image.name.rsplit('.', 1)[0]}.webp",
            ContentFile(result.content),
            save=False
        )

Node.js SDK

Install the Node.js SDK via npm:

npm install deflato

Basic Usage

const Deflato = require('deflato');
const fs = require('fs');

const client = new Deflato({ apiKey: process.env.DEFLATO_API_KEY });

async function compressImage() {
  const result = await client.compress('./photo.jpg', {
    outputFormat: 'WEBP',
    quality: 80,
    maxDimension: 1920
  });

  fs.writeFileSync('./photo.webp', result.buffer);

  console.log(`Original: ${(result.originalSize / 1024).toFixed(0)} KB`);
  console.log(`Compressed: ${(result.compressedSize / 1024).toFixed(0)} KB`);
  console.log(`Savings: ${result.savingsPercent.toFixed(1)}%`);
}

compressImage();

Batch Processing with Concurrency Control

const Deflato = require('deflato');
const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const glob = promisify(require('glob'));

const client = new Deflato({ apiKey: process.env.DEFLATO_API_KEY });

async function batchCompress(inputDir, outputDir, concurrency = 5) {
  const files = await glob(`${inputDir}/*.{jpg,png,jpeg}`);
  fs.mkdirSync(outputDir, { recursive: true });

  // Process in batches to respect rate limits
  for (let i = 0; i < files.length; i += concurrency) {
    const batch = files.slice(i, i + concurrency);
    const results = await Promise.all(
      batch.map(async (file) => {
        const result = await client.compress(file, {
          outputFormat: 'WEBP',
          quality: 80
        });
        const outPath = path.join(
          outputDir,
          path.basename(file, path.extname(file)) + '.webp'
        );
        fs.writeFileSync(outPath, result.buffer);
        return { file: path.basename(file), savings: result.savingsPercent };
      })
    );
    results.forEach(r =>
      console.log(`${r.file}: ${r.savings.toFixed(1)}% saved`)
    );
  }
}

batchCompress('./images', './optimized');

MCP Server Integration

Deflato provides an MCP (Model Context Protocol) server that lets AI assistants and LLM-powered tools compress images directly. This is useful for AI-driven workflows where an agent needs to optimize images as part of a larger task.

Setup

Add the Deflato MCP server to your MCP client configuration:

{
  "mcpServers": {
    "deflato": {
      "command": "npx",
      "args": ["-y", "deflato-mcp-server"],
      "env": {
        "DEFLATO_API_KEY": "YOUR_API_KEY"
      }
    }
  }
}

Once configured, your AI assistant can call Deflato tools to compress, convert, and resize images as part of its workflow — no manual API calls needed.

Error Handling

The API returns standard HTTP status codes:

  • 200 — Success. The response body is the compressed image.
  • 400 — Bad request. Check your parameters (invalid format, quality out of range, etc.).
  • 401 — Unauthorized. Your API key is missing, invalid, or revoked.
  • 413 — File too large. The input file exceeds the maximum upload size (50 MB for Pro plans).
  • 429 — Rate limited. You've exceeded your plan's requests-per-minute limit. Wait and retry with exponential backoff.
  • 500 — Server error. Retry the request. If it persists, contact support.

In Python:

import deflato

client = deflato.Client(api_key="YOUR_API_KEY")

try:
    result = client.compress("photo.jpg", output_format="WEBP", quality=80)
    result.save("photo.webp")
except deflato.AuthenticationError:
    print("Invalid API key")
except deflato.RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except deflato.FileTooLargeError:
    print("File exceeds the maximum upload size")
except deflato.APIError as e:
    print(f"API error: {e.message}")

Rate Limits and Pricing

Plan API Compressions / Month Max File Size Rate Limit
Free 100 10 MB 10 req/min
Pro 10,000 50 MB 60 req/min
Team 100,000 100 MB 300 req/min
Enterprise Custom Custom Custom

Check your current usage at any time via the API:

curl https://deflato.com/api/v1/usage   -H "Authorization: Bearer $DEFLATO_API_KEY"
{
  "plan": "pro",
  "compressions_used": 1847,
  "compressions_limit": 10000,
  "period_ends": "2026-04-01T00:00:00Z"
}

Best Practices

  • Cache results — Don't re-compress the same image twice. Store compressed versions and skip files that haven't changed.
  • Use environment variables for your API key. Never commit keys to version control.
  • Implement retry logic with exponential backoff for 429 and 500 responses.
  • Set a timeout — Large images may take a few seconds. Set a reasonable timeout (30s) and retry if it expires.
  • Compress on upload, not on request — Optimize images when they're first uploaded to your system, not when a user requests them. This avoids per-request latency.
  • Monitor usage — Use the /usage endpoint to track consumption and alert before hitting your plan's limit.

Conclusion

The Deflato API turns image optimization from a manual task into an automated pipeline step. Whether you're processing user uploads in a web app, building a static site with thousands of images, or integrating compression into an AI workflow via MCP, the API provides a consistent interface: upload an image, specify your parameters, and get an optimized result. Start with the cURL examples to validate your workflow, then integrate the Python or Node.js SDK for production use.

Start compressing

Free online tool for photos and documents. AVIF, WEBP, JPEG, PNG, HEIC. No watermarks. No signup required.

Start compressing