Python Examples¶
A Python-first walkthrough of the Image Toolkit. Every example below was checked against the live FastAPI routes — the HTTP method, parameter style, and response shape match what the service actually accepts.
Two response shapes you must not confuse¶
The Image Toolkit mixes two contracts, and this is the single biggest source of broken integrations:
| Shape | Endpoints | Input | Output |
|---|---|---|---|
| GET + query string | /v1/image/resize, /crop, /rotate, /flip, plus filters |
url= required (no base64) |
JSON with base64 in image |
| POST + JSON body | /v1/image/convert, /extract/metadata, /extract/colors, templates |
url= or image= (base64), never both |
JSON with base64 / structured data |
⚠️
resize,crop,rotate, andflipareGETwith query parameters and do not accept base64 input. APOST /v1/image/resizewith a JSON body returns405 Method Not Allowed. If you need to process local bytes, upload them to a URL you control, or use a POST endpoint (/convert) instead.
Install and set up¶
pip install toolkitapi httpx
import base64
import os
from toolkitapi import Image
api_key = os.environ["TOOLKIT_API_KEY"] # e.g. "tk_..."
image = Image(api_key=api_key)
The SDK object is also usable as a context manager (with Image(api_key=...) as
image:), which closes the underlying HTTP session cleanly. Both styles work;
below we use the plain form and rely on interpreter shutdown.
Decoding a response¶
Nearly every endpoint returns base64. Write one helper and reuse it:
import base64
from pathlib import Path
def save_b64(payload: dict, path: str, *, key: str = "image") -> Path:
"""Write a base64 payload field to disk and return the path."""
raw = base64.b64decode(payload[key])
out = Path(path)
out.write_bytes(raw)
return out
/v1/image/convert uses a different field name — see its section below.
Resize¶
result = image.resize(
url="https://toolkitapi.io/static/samples/sample-image.png",
width=800,
maintain_aspect=True,
format="webp",
quality=85,
)
print(result["original_size"], "→", result["new_size"])
save_b64(result, "resized.webp")
Raw equivalent, so you can see exactly what goes on the wire:
import httpx
resp = httpx.get(
"https://image.toolkitapi.io/v1/image/resize",
params={
"url": "https://toolkitapi.io/static/samples/sample-image.png",
"width": 800,
"maintain_aspect": "true",
"format": "webp",
"quality": 85,
},
headers={"X-API-Key": api_key},
timeout=30,
)
resp.raise_for_status()
data = resp.json()
# {"image": "<base64>", "format": "webp",
# "original_size": {"width": 272, "height": 92},
# "new_size": {"width": 800, "height": 270}}
Behaviour worth internalising:
- Only
width→ height scales proportionally. Onlyheight→ width scales. - Both with
maintain_aspect=true→ the image fits inside the box (PIL.thumbnail), so at least one dimension is smaller than requested. - Both with
maintain_aspect=false→ exact dimensions, aspect distorted. - Neither →
400 Provide at least width or height. - Output formats here are limited to
png,jpeg,webp.
Convert between formats¶
/v1/image/convert is the POST endpoint — it takes base64 or a URL, and it can
also go raster → SVG and raster → PDF.
result = image.convert(
"png", # from_format
"webp", # to_format
url="https://toolkitapi.io/static/samples/sample-image.png",
quality=85,
)
print(result["content_type"]) # "image/webp"
print(result["file_size_bytes"])
Path("logo.webp").write_bytes(base64.b64decode(result["result"]))
Note the field is result, not image. The response also carries
success, from_format, to_format, file_size_bytes, optional width /
height (null for SVG/PDF output), and a ready-made data_uri if you want to
drop it straight into HTML:
html = f'<img src="{result["data_uri"]}" alt="logo">'
There is also a GET variant that streams a file instead of returning base64:
resp = httpx.get(
"https://image.toolkitapi.io/v1/image/convert",
params={
"url": "https://example.com/photo.jpg",
"from_format": "jpeg",
"to_format": "png",
"width": 1200,
},
headers={"X-API-Key": api_key},
)
Path("photo.png").write_bytes(resp.content) # binary, not JSON
Extract metadata (EXIF)¶
meta = image.extract_metadata(url="https://toolkitapi.io/static/samples/sample-image.png")
print(meta["format"], meta["mode"], meta["size"], meta["megapixels"])
print("animated:", meta["is_animated"], "frames:", meta.get("frames"))
print("exif keys:", list(meta["exif"])[:5])
POST with base64 works too — useful for camera uploads you never want to host:
with open("shot.jpg", "rb") as fh:
b64 = base64.b64encode(fh.read()).decode()
resp = httpx.post(
"https://image.toolkitapi.io/v1/image/extract/metadata",
json={"image": b64},
headers={"X-API-Key": api_key},
timeout=30,
)
meta = resp.json()
Every EXIF tag is stringified (str(value)), so numeric fields like FNumber
arrive as "2.8". Parse them yourself if you need numbers. If the file has no
EXIF block you get "exif": {} — not an error.
Extract dominant colours¶
palette = image.extract_colors(
url="https://toolkitapi.io/static/samples/sample-image.png",
count=5,
)
for c in palette["colors"]:
print(c["hex"], c["rgb"]) # #3a7bd5 {'r': 58, 'g': 123, 'b': 213}
count is clamped 1–20 server-side (default 6). Composition:
def contrast_text(hex_color: str) -> str:
"""Pick black or white text for a background, WCAG-ish."""
r, g, b = (int(hex_color[i:i + 2], 16) for i in (1, 3, 5))
luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b
return "#000000" if luminance > 140 else "#ffffff"
primary = palette["colors"][0]["hex"]
badge_html = f'<span style="background:{primary};color:{contrast_text(primary)}">New</span>'
Generate a QR code¶
qr = image.qr("https://toolkitapi.io", format="png", size=400)
save_b64(qr, "qr.png")
The QR endpoint returns raw image bytes on the wire; the SDK gives you the
decoded payload. For SVG output pass format="svg" (the response is then an
SVG document rather than base64 PNG data).
Render a Liquid template¶
card = image.from_template(
template="<html><body><h1>{{ title }}</h1><p>{{ subtitle }}</p></body></html>",
variables={"title": "Launch day", "subtitle": "We shipped it."},
width=1200,
height=630,
)
print(card["width"], card["height"])
Path("og-card.png").write_bytes(base64.b64decode(card["image"]))
Template rendering is a POST with a JSON body (template, variables,
width, height, format). See
Template Rendering for the full
variable and layout reference.
Error handling that actually helps¶
Image calls fail in a handful of predictable ways. Handle the categories, not individual messages:
import httpx
RETRYABLE = {429, 502, 503, 504}
def call_image(fn, *args, **kwargs):
try:
return fn(*args, **kwargs)
except httpx.HTTPStatusError as exc:
status = exc.response.status_code
detail = exc.response.json().get("detail", exc.response.text)
if status == 400:
# Bad input: unreachable URL, not an image, bad dimensions.
raise ValueError(f"image request rejected: {detail}") from exc
if status == 404:
raise ValueError(f"source image not found: {detail}") from exc
if status in RETRYABLE:
raise RuntimeError(f"temporary image service failure ({status})") from exc
raise
| Status | Typical detail |
Meaning |
|---|---|---|
400 |
Invalid image data: cannot identify image file ... |
URL responded but the body is not an image |
400 |
Provide at least width or height |
Resize called with no dimensions |
400 |
Provide either 'image' (base64) or 'url' |
POST body had neither field |
400 |
Provide either 'image' or 'url', not both |
POST body had both — ambiguous |
404 |
No such object |
/v1/image/download/... key expired or wrong |
405 |
Method Not Allowed |
Used POST on a GET-only transform |
413 |
payload too large | Base64 body above the ~20 MB image field cap |
422 |
Pydantic array | Missing required query param, or quality outside 1–100 |
Other limits to keep in mind:
image(base64) is capped at 20,971,520 characters (≈20 MB encoded, so roughly 15.7 MB of source bytes).urlis capped at 2048 characters.- Remote fetches are SSRF-protected: private, loopback, and reserved addresses are rejected before any request is made.
width/heighton transforms are capped at 10,000 px; the GET convert variant caps at 8,192 px andscaleat 0.1–10.0.
Batch pattern: resize a list without hammering the API¶
import concurrent.futures as cf
urls = [f"https://example.com/gallery/{i}.jpg" for i in range(1, 21)]
failures: list[tuple[str, str]] = []
def one(url: str) -> tuple[str, dict]:
return url, image.resize(url=url, width=1200, format="jpeg", quality=82)
with cf.ThreadPoolExecutor(max_workers=4) as pool:
for url, payload in pool.map(one, urls):
try:
save_b64(payload, f"out/{url.rsplit('/', 1)[-1]}")
except Exception as exc: # noqa: BLE001
failures.append((url, str(exc)))
print(f"{len(urls) - len(failures)} ok, {len(failures)} failed")
Keep concurrency modest (3–5 workers). Each call fetches the source image,
decodes it, and re-encodes the result, so the service is CPU-bound per request —
parallelism beyond that starts producing 429s rather than extra throughput.
Tips¶
- Prefer
urlover base64 where you can. Base64 inflates payloads by ~33% and puts the whole image in the query/body; a URL keeps the request small. webpbeatsjpegfor size at equal quality, but check your client support before standardising on it — older Safari and some email clients still need ajpegfallback.maintain_aspect=truewith both dimensions fits inside the box. If you need an exact 1200×630 OG card, either pass only the constrained dimension or setmaintain_aspect=Falseand accept the distortion — or use the template endpoint, which lays out text at exact size.qualityis ignored forpng. It only applies tojpeg/webp.- EXIF values are strings.
"ExposureTime": "0.005"— cast before arithmetic. - Animated GIFs report
is_animatedandframes, but transforms operate on the first frame. Do not expect animation-preserving resize. file_size_bytesis the decoded size, not the base64 string length — divide base64 length by ~1.33 to predict it.- Don't log base64. A single 1200px JPEG will blow up your log volume;
log
new_sizeandfile_size_bytesinstead. - Cache by source URL + transform params. Repeated identical transforms are the most common source of wasted quota in image pipelines.
Related¶
- Image Processing & Filters — full transform parameter tables
- Extraction & Conversion — metadata, colours, format matrix
- Template Rendering — Liquid templates for OG cards
- QR Generate — styling options and logo embedding
- Image Toolkit Overview — every endpoint at a glance