Code Examples - Multi-Language Compression Code
Compression API code examples categorized by language and scenario, covering Python, Node.js, Java, Go, and curl, with best practices for AI data preprocessing, batch callbacks, encrypted compression, and more
Python Examples
Call the compression API using the requests library, supporting single-file, batch, and async modes
Single File Compression
import requests
resp = requests.post(
"https://api.uglypear.com/v1/compress",
headers={"Authorization": "Bearer YOUR_API_KEY"},
files={"file": open("input.pdf", "rb")},
data={"quality": "high"}
)
print(resp.json())
Batch Compression
import requests
files = [("files", open(f, "rb")) for f in ["a.pdf", "b.pdf", "c.pdf"]]
resp = requests.post(
"https://api.uglypear.com/v1/batch/compress",
headers={"Authorization": "Bearer YOUR_API_KEY"},
files=files,
data={"quality": "medium", "callback_url": "https://yourapp.com/callback"}
)
print(resp.json())
Async Compression
import asyncio
import aiohttp
async def compress(path):
async with aiohttp.ClientSession() as session:
with open(path, "rb") as f:
data = aiohttp.FormData()
data.add_field("file", f)
data.add_field("quality", "high")
async with session.post(
"https://api.uglypear.com/v1/compress",
headers={"Authorization": "Bearer YOUR_API_KEY"},
data=data
) as resp:
return await resp.json()
asyncio.run(compress("input.pdf"))
Node.js Examples
Stream uploads and batch processing using axios + form-data
Stream Compression
const fs = require("fs");
const FormData = require("form-data");
const axios = require("axios");
const form = new FormData();
form.append("file", fs.createReadStream("input.pdf"));
form.append("quality", "high");
axios.post("https://api.uglypear.com/v1/compress", form, {
headers: {
...form.getHeaders(),
Authorization: "Bearer YOUR_API_KEY"
}
}).then(res => console.log(res.data));
Batch Processing
const fs = require("fs");
const FormData = require("form-data");
const axios = require("axios");
const form = new FormData();
["a.pdf", "b.pdf", "c.pdf"].forEach(f =>
form.append("files", fs.createReadStream(f))
);
form.append("quality", "medium");
axios.post("https://api.uglypear.com/v1/batch/compress", form, {
headers: { ...form.getHeaders(), Authorization: "Bearer YOUR_API_KEY" }
}).then(res => console.log(res.data));
Java Examples
Multipart upload compression requests using OkHttp
OkHttpClient client = new OkHttpClient();
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "input.pdf",
RequestBody.create(new File("input.pdf"),
MediaType.parse("application/pdf")))
.addFormDataPart("quality", "high")
.build();
Request request = new Request.Builder()
.url("https://api.uglypear.com/v1/compress")
.header("Authorization", "Bearer YOUR_API_KEY")
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.body().string());
}
Go Examples
Build requests using the standard library net/http and mime/multipart
package main
import (
"bytes"
"io"
"mime/multipart"
"net/http"
"os"
)
func main() {
file, _ := os.Open("input.pdf")
defer file.Close()
var buf bytes.Buffer
writer := multipart.NewWriter(&buf)
part, _ := writer.CreateFormFile("file", "input.pdf")
io.Copy(part, file)
writer.WriteField("quality", "high")
writer.Close()
req, _ := http.NewRequest("POST",
"https://api.uglypear.com/v1/compress", &buf)
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", writer.FormDataContentType())
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
println(string(body))
}
curl Examples
Quickly call the compression API from the command line. Suitable for scripts and automated testing
curl -X POST https://api.uglypear.com/v1/compress \
-H "Authorization: Bearer YOUR_API_KEY" \
-F "file=@input.pdf" \
-F "quality=high"
Best Practices by Scenario
Recommended integration approaches for typical business scenarios
AI Data Preprocessing Pipeline Integration
Call the compression API to preprocess documents/images before data ingestion, reducing storage footprint. Decompress on demand for model training, accelerating the read pipeline.
# Pipeline integration: compress before ingestion
result = comp.compress_file("dataset/doc.pdf", quality="high")
upload_to_storage(result.output_path)
Batch Compression + Callback Notification
The batch API processes asynchronously. Results are pushed to the callback_url upon task completion, avoiding long connection waits.
resp = requests.post(
"https://api.uglypear.com/v1/batch/compress",
headers={"Authorization": "Bearer YOUR_API_KEY"},
files=files,
data={"callback_url": "https://yourapp.com/callback"}
)
Password-Protected Encrypted Compression
Append a password parameter to sensitive files. The server performs encrypted compression, ensuring transmission and storage security.
curl -X POST https://api.uglypear.com/v1/compress \
-H "Authorization: Bearer YOUR_API_KEY" \
-F "file=@input.pdf" \
-F "password=YourStrongPass"
Large File Chunked Upload Compression
Upload large files in chunks first, then trigger overall compression. This avoids single-request timeouts and improves success rates.
// Chunked upload + trigger compression
for (const chunk of chunks) {
await uploadChunk(chunk);
}
await axios.post("https://api.uglypear.com/v1/compress",
{ upload_id, quality: "high" }, { headers });
GitHub Repository
More complete example projects coming soon as open source
uglypear-compressor-examples
Includes complete runnable example projects for Python, Node.js, Java, Go, and curl. Coming soon as open source. Contact technical support for early access.
Contact UsView Full API Docs
Browse API parameters, error codes, and the online debugger to quickly master the full capabilities of the Compression API