Code Examples
Complete, copy-pasteable examples in multiple languages. Replace fft_your_api_key with your actual API key from the dashboard.
JavaScript / Node.js -- Image Compress
Compress an image using the Fetch API in Node.js. This example reads a local file and saves the compressed result.
const fs = require("fs");
const path = require("path");
const API_KEY = process.env.FFT_API_KEY || "fft_your_api_key";
const API_URL = "https://freefiletools.io/api/image-compress";
async function compressImage(inputPath, outputPath, quality = 75) {
// Read the file
const fileBuffer = fs.readFileSync(inputPath);
const fileName = path.basename(inputPath);
// Create form data
const formData = new FormData();
formData.append("file", new Blob([fileBuffer]), fileName);
formData.append("quality", String(quality));
// Make the request
const response = await fetch(API_URL, {
method: "POST",
headers: {
"x-api-key": API_KEY,
},
body: formData,
});
if (!response.ok) {
const error = await response.text();
throw new Error(`API error (${response.status}): ${error}`);
}
// Check rate limit headers
const remaining = response.headers.get("X-RateLimit-Remaining");
console.log(`Requests remaining: ${remaining}`);
// Save the result
const buffer = Buffer.from(await response.arrayBuffer());
fs.writeFileSync(outputPath, buffer);
const inputSize = fs.statSync(inputPath).size;
const outputSize = buffer.length;
const savings = ((1 - outputSize / inputSize) * 100).toFixed(1);
console.log(`Compressed: ${inputSize} -> ${outputSize} bytes (${savings}% smaller)`);
}
// Usage
compressImage("photo.jpg", "photo-compressed.jpg", 80)
.then(() => console.log("Done!"))
.catch((err) => console.error(err));Python -- PDF Merge
Merge multiple PDF files using Python and the requests library. Install with: pip install requests
import requests
import os
API_KEY = os.environ.get("FFT_API_KEY", "fft_your_api_key")
API_URL = "https://freefiletools.io/api/pdf-merge"
def merge_pdfs(file_paths, output_path):
"""Merge multiple PDF files into one."""
headers = {
"x-api-key": API_KEY
}
# Prepare files for upload
files = []
for path in file_paths:
files.append(
("files", (os.path.basename(path), open(path, "rb"), "application/pdf"))
)
# Make the request
response = requests.post(API_URL, headers=headers, files=files)
# Close file handles
for _, file_tuple in files:
file_tuple[1].close()
if response.status_code != 200:
raise Exception(f"API error ({response.status_code}): {response.text}")
# Check rate limit
remaining = response.headers.get("X-RateLimit-Remaining", "?")
print(f"Requests remaining: {remaining}")
# Save the merged PDF
with open(output_path, "wb") as f:
f.write(response.content)
size_kb = len(response.content) / 1024
print(f"Merged PDF saved: {output_path} ({size_kb:.1f} KB)")
# Usage
merge_pdfs(
["document1.pdf", "document2.pdf", "document3.pdf"],
"merged.pdf"
)
print("Done!")cURL -- QR Code Generation
Generate a QR code using cURL. Note that this endpoint uses JSON instead of form data.
#!/bin/bash
API_KEY="fft_your_api_key"
# Generate a QR code for a URL
curl -X POST "https://freefiletools.io/api/qr-generate" \
-H "x-api-key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "https://freefiletools.io",
"size": 400,
"errorCorrection": "H",
"fgColor": "#000000",
"bgColor": "#ffffff"
}' \
-o qrcode.png
echo "QR code saved as qrcode.png"
# Generate a WiFi QR code
curl -X POST "https://freefiletools.io/api/qr-generate" \
-H "x-api-key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "WIFI:T:WPA;S:MyNetwork;P:MyPassword;;",
"size": 300,
"errorCorrection": "M"
}' \
-o wifi-qr.png
echo "WiFi QR code saved as wifi-qr.png"PHP -- Image Resize
Resize an image using PHP and cURL. This example works with PHP 7.4+.
<?php
$apiKey = getenv("FFT_API_KEY") ?: "fft_your_api_key";
$apiUrl = "https://freefiletools.io/api/image-resize";
function resizeImage($inputPath, $outputPath, $width, $height = null) {
global $apiKey, $apiUrl;
// Prepare the file
$cfile = new CURLFile($inputPath, mime_content_type($inputPath), basename($inputPath));
// Build form data
$postData = [
"file" => $cfile,
"width" => $width,
];
if ($height !== null) {
$postData["height"] = $height;
}
// Make the request
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $apiUrl,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => [
"x-api-key: " . $apiKey,
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$body = substr($response, $headerSize);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception("API error ($httpCode): $body");
}
// Save the result
file_put_contents($outputPath, $body);
$inputSize = filesize($inputPath);
$outputSize = strlen($body);
echo "Resized: " . basename($inputPath) . " ({$inputSize} -> {$outputSize} bytes)\n";
}
// Usage: resize to 800px width (height auto-calculated)
try {
resizeImage("photo.jpg", "photo-resized.jpg", 800);
echo "Done!\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
?>More Resources
Image Tools API Reference -- All image endpoints with parameters and cURL examples.
PDF Tools API Reference -- All PDF endpoints with parameters and cURL examples.
Generate Tools API Reference -- QR codes, favicons, screenshots, and URL-to-PDF.
Rate Limits -- Understand limits and implement retry logic.