SmallPict Rust SDK
Official Rust SDK for the SmallPict Image Optimization API — high-performance next-gen image transcoding (AVIF, WebP), smart compression, Edge CDN delivery, and cache purging.
⚡ Features
- 🦀 Pure Rust TLS Stack: Uses
rustls-tlsby default to avoid OpenSSL C-runtime issues. - ⚡ Dual Asynchronous & Blocking Modes: High-concurrency
tokioasync client and optional syncBlockingClient. - 🛡️ HMAC-SHA256 request signing: every request is signed with your secret key; both
api_keyandsecret_keyare required. - ✨ 4 Core Unified Methods:
optimize()(uploads the image and waits for the finished job),get_quota(),purge_cdn(), andvalidate_key(). - 🔄 Resilience & Fault Tolerance: Automatic
Idempotency-KeyUUID injection, 30s timeouts, and exponential backoff with jitter on HTTP 429/5xx. - 🔒 Zero-Leak Privacy: API keys and credentials are automatically wrapped in
SecretRedactedand masked inDisplay,Debug, and error logs.
📥 Installation
In your Cargo.toml:
[]
= "0.1"
To enable synchronous / blocking mode:
[]
= { = "0.1", = ["blocking"] }
🚀 Quick Start
1. Asynchronous Example (Tokio)
use ;
use fs;
async
2. Synchronous / Blocking Example
Do not create or call a BlockingClient inside a tokio runtime (an axum or tonic handler, a #[tokio::main] function): reqwest::blocking panics there. Use Client from async code, or run the blocking call with tokio::task::spawn_blocking.
use BlockingClient;
use ;
use fs;
What optimize() does
POST /v1/optimize only queues a job. optimize() then uploads your bytes to the pre-signed upload_url the API returns (a plain PUT with Content-Type and Content-Length, no API headers), polls the job status every poll_interval (default 1 s) and returns once the job is completed, so result.status is always "completed" and url, format, bytes_saved, mode_applied, quality_applied and folder come from the finished job.
- A failed job returns
SmallPictError::Optimizewithcode()Some("job_failed"), the server's message anddetails()["job_id"]. A refused upload returns the same variant with codeupload_failedand the storage's HTTP status. - A job still running after
wait_timeout(default 120 s) returnsSmallPictError::Timeoutwith the job id in the message; it keeps running on the server, so callget_job_status(job_id)later. - Pass the image bytes. The API does not fetch URLs:
optimize_file("https://...")returnsSmallPictError::Validationwithout a request; download the image yourself first.
use Duration;
let client = builder
.api_key
.poll_interval
.wait_timeout
.build?;
match client.optimize.await
3. Compression Mode
mode picks the compression: Lossy (server default), Extreme, Lossless or Auto. Auto picks, per image, the lowest quality that keeps the visual score (SSIMULACRA 2) at or above 70, and ignores quality; it is on WP Pro and Business, Velocity, Momentum and sandbox keys (5 auto jobs per minute per sandbox key), and where it cannot search (PNG or GIF output, animation, time limit) the job is lossy and mode_applied says so. The server checks it against your plan and answers HTTP 403 mode_not_in_plan (SmallPictError::Forbidden, with details.allowed_modes) when the plan does not include it. Extreme gives the smallest files on every plan; leave quality out so the server uses its default for the output format, and a quality you set is kept or raised to the format floor. Mode comparison: https://smallpict.app/en/docs/image-settings . The old lossless(true) option is deprecated; use .mode(CompressionMode::Lossless).
use ;
let options = builder
.mode
.build;
match client.optimize.await
// Extreme without a quality: the server uses its default for the output format.
let options = builder
.mode
.build;
let result = client.optimize.await?;
// The job status reports what the server applied (absent for older jobs).
let status = client.get_job_status.await?;
println!;
4. Upload Folder
folder stores the optimized file under a folder of your account (1-3 segments such as products/shoes). The server lower-cases it and answers HTTP 400 invalid_folder (SmallPictError::Validation) for a malformed value; the SDK rejects empty segments, .. and more than 3 segments before sending.
let options = builder.folder.build;
let result = client.optimize.await?;
// The job status reports the stored folder (absent without one).
let status = client.get_job_status.await?;
println!;
📊 Account Quota & Edge CDN Purge
// 1. Check real-time quota usage
let quota = client.get_quota.await?;
println!;
// 2. Invalidate Edge CDN cache
let purge = client.purge_cdn.await?;
println!;
// 3. Purge every file delivered under one upload folder
client.purge_folder.await?;
Folder purges (10 per hour) and PurgeType::All purges (2 per hour) are limited per account. Past the limit the server answers HTTP 429 purge_rate_limited (SmallPictError::RateLimit), which the SDK does not retry automatically.
Capacity and upgrade links
get_quota() returns capacity (read-only): storage, CDN, booster balances with the lot that expires first, the unpaid-account state, period_end and manage_url of the key's product. Members that do not apply are None; capacity is None when the server could not read it and on older servers. Capacity is bought only in the dashboard.
if let Some = client.get_quota.await?.capacity
match client.optimize.await
upgrade_url() reads details.upgrade_url of 402 errors and of the 409 capacity codes (SmallPictError::Server with status 409; e.code() gives the code). The SDK never opens, fetches or builds manage_url or upgrade_url; show them to the user.
🧪 Testing
🔒 Security & Schema Compatibility (2026)
mime_type&content_typeDual Support:OptimizeOptionsandOptimizeOptionsBuildersupport bothmime_typeandcontent_typefields. Requests submitted via the asyncClientand theBlockingClientsend bothmime_typeandcontent_type, guaranteeing 100% backward and forward compatibility with all SmallPict API versions.
📄 License
MIT © SmallPict Engineering