ditinyAPI Reference

API Reference

The Ditiny API provides file storage, processing, delivery, and asynchronous AI image generation. Authenticate with JWT tokens (from login) or API keys (from settings). Most API responses are JSON; documented exceptions include the HTML share page, 204 responses, and 302 redirects. Proxy-generated errors may be plain text or HTML. Response examples below may be excerpts; treat the documented schemas as authoritative.

API key domain rules: when an API key has a non-empty allowed-domain list, every request must include an Origin or Referer whose host matches that list. Server-to-server requests without a matching header receive 403. An empty list applies no domain restriction; use an exact domain instead of * whenever possible. Because server clients can synthesize these headers, this is not a strong security boundary or a substitute for protecting the API key. Webhook URLs also require a configured matching allowed domain.
GETPOSTPATCHPUTDELETE

Public AI Images API · v1

Use Ditiny images from your own backend: acquire a reference, choose supported generation controls, queue extract/redesign/remockup, then read the original output, usage and actual USD cost. Provider credentials stay in Ditiny.

Download public AI OpenAPI JSON →
Availability: these routes are gated by AI_PUBLIC_API_ENABLED (off by default). API keys require the R1 scope release; job creation also requires the R3 wallet-hold release. Documentation is public even when the API is disabled. A 503 does not mean a job was accepted; inspect the error message.

Authentication and ownership

Send X-API-Key from your backend, or a Bearer JWT. Never embed a key in a browser, mobile bundle or public repository. Keys need ai scope for jobs/output/AI delivery history; wallet endpoints need wallet:read after R1. Reading or changing the shared webhook configuration requires files and ai together, or a JWT/legacy * key. Existing legacy keys retain their permissions. Upload uses the existing files scope. Public v1 is always owner-only, including for admin keys.

For server-to-server integration, use an API key configured without domain restrictions, or a deliberately configured wildcard. The current allowed-domain check rejects requests without matching Origin/Referer when an exact domain list is present; these headers are not authentication. Do not forge browser headers to work around key policy.

A shared key attributes all jobs and expenses to its Ditiny account. Keep the mapping between your external order/user and Ditiny job_id in your own system. No cross-user impersonation or provider administration is exposed.

MethodPathBehavior
GET/api/v1/ai/promptsVisible global and personal prompt templates: exact text, version, quantity metadata and SHA256. Initially seeded with five templates.
GET / POST/api/v1/ai/prompt-templatesList visible templates or create a personal template. Global creation requires admin authority.
PATCH/api/v1/ai/prompt-templates/{id}Edit an editable template with its expected version; scope is immutable. Stale version returns 409.
DELETE/api/v1/ai/prompt-templates/{id}?version=1Remove an editable template with its expected version. Saved job prompts remain unchanged.
GET/api/v1/ai/modelsEnabled models, provider names, supported resolutions, capabilities, source size limit and required wallet holds by resolution. Check this catalog before building controls.
POST/api/v1/ai/sourcesImport a public HTTPS PNG/JPEG/WebP/GIF URL. Returns a private file_key (201).
POST/api/v1/ai/site-imagesDiscover image URLs on a public HTML page. Select a candidate, then import it.
POST/api/v1/ai/sources/{file_key}/transformCreate a private PNG reference with clockwise rotation and crop. Original stays unchanged (201).
POST/api/v1/ai/jobsQueue a job (202). Requires Idempotency-Key. Uses the same engine and wallet admission as the UI.
GET/api/v1/ai/jobs?limit=30&offset=0Own jobs only, including for admin keys. Optional status filter; response: items, limit, offset, has_more.
GET/api/v1/ai/jobs/{job_id}Read prompt/config, progress timestamps, errors, original output, public preview/download links and fee. Poll every 5–10 seconds.
POST/api/v1/ai/jobs/{job_id}/cancelCancel queued/preparing jobs only. A submitted provider call cannot be safely cancelled (409).
POST/api/v1/ai/jobs/{job_id}/refresh-feeLook up an existing provider fee without generating another image. May return 409 if no confirmed fee is available.
GET / HEAD/api/v1/ai/jobs/{job_id}/outputStream original with auth and correct MIME; inline by default, ?download=true for attachment. No redirect.
GET / PUT/api/v1/ai/webhookRead/update the shared user webhook: both files+ai scopes, JWT or legacy *. AI events opt in with ai_enabled=true; enabled is the shared master switch.
GET/api/v1/ai/webhook/deliveries?limit=30&offset=0Own AI delivery history: items and has_more, attempts/status/last error and retry times. No credentials.
GET/api/v1/walletOwn USD balance, spend and pending calls. Held/available values require the R3 wallet release.
GET/api/v1/wallet/transactionsOwn ledger, with limit/offset pagination. No public top-up endpoint.

Generation capabilities and exact request fields

GET /api/v1/ai/models is the authority for each enabled model. Read capabilities before offering reference, size, seed, negative prompt, mask or provider options controls. A false capability or an unlisted value means unavailable. For ratios, aspect_ratio describes native provider support; derived_aspect_ratio plus size_modes enables API conversion to custom dimensions. Verified Qwen Edit adapters enable seed, negative prompt, additional references where listed, and steps/CFGScale options; negative prompt requires CFGScale greater than one. Verified Seedream 5 Pro/Flash enable additional references and custom sizing. Other models retain their advertised square/default behavior. Mask and native provider aspect_ratio are currently unavailable on all adapters. On models with derived_aspect_ratio, the API can resolve a requested ratio to custom dimensions. Unsupported controls return 422 before paid submission. Cloud jobs are asynchronous and enter the queue; local devices and GPU pools are planned backend work, not available execution targets.

JSON fieldContract
model_idRequired positive model ID from GET models.
source_file_key / referencesFor generate, omit source_file_key and references. Other operations require an owned source UUID, or references: [{file_key: UUID}]. If both are present, the first reference must match source_file_key. No duplicates; the model max_references counts the primary image too.
operationRequired: generate (text to image), extract, redesign, remockup or flatten.
promptCustom nonblank text, up to 4,000 characters. Use this OR the template selection below.
prompt_template_id, prompt_template_version, variablesSelect a visible template UUID and exact positive version. variables supplies string values for {{name}} placeholders (same key/map limits as metadata). Do not also send prompt. The resolved prompt and template identity/version/hash are frozen for that job.
resolution1K default; 2K only when listed for the model.
sizeOptional object: mode (square default, original_ratio, aspect_ratio or custom), aspect_ratio, width, height. Native modes/values are listed in capabilities. Qwen 2.1 Turbo/Pro support native aspect_ratio, including 3:4; unavailable sizes/ratios fall back to square with green #00FF00 padding, as recorded in effective_config.fallback; custom width (64–4500) and height (64–5400) must satisfy model dimension/pixel/step limits. original_ratio requires known source dimensions. aspect_ratio takes a ratio string such as 3:4 only when derived_aspect_ratio is true and size_modes lists it. Both ratio modes resolve to validated custom dimensions; inspect effective_config for rounding.
postprocessOptional {resize: {width, height}} uses exact integer dimensions, width 1–4500 and height 1–5400. Conventional LANCZOS resize including upscale; outputs RGBA PNG. Can distort aspect ratio, preserves existing alpha, and does not create transparency or provide AI superresolution.
num_outputs1 only; omitted means 1. No batch output or automatic quantity expansion.
output{visibility: "public" | "private", background: "auto" | "transparent" | "opaque", format: "auto" | "png" | "webp" | "jpeg"}. Defaults: public/auto/auto. Transparent requires PNG/WebP (auto chooses PNG). Native transparency is used where supported; otherwise generate on green #00FF00 and chroma-key it to real alpha. Unsupported size uses a square canvas; supported ratios are retained. Opaque composites existing alpha over white unless green padding is required by a size fallback. Format conversion alone does not remove a background.
client_reference, metadataOptional client reference (up to 200 characters) and string map metadata (up to 20 entries / 8 KiB; keys are 1–64 letters, digits, underscore, dot, colon or dash). Keep credentials and sensitive data out of both.
generationOptional seed (integer 0–4294967295), negative_prompt (1–4000 characters), mask_file_key (UUID) and provider_options (object, max 8 KiB). These fields are accepted only when the selected model capability supports them; a provider marketing claim does not enable a control.
execution{target: "cloud"} is the available execution target. local and pool are unavailable; there is no automatic fallback.
billing{max_cost_usd: "0.10"} optionally limits admission against the required hold (positive decimal, maximum 1000000, at most 12 decimal places). This does not cap a provider’s eventual charge.
parent_job_idOptional owned parent UUID for an intentional new paid attempt after the parent is terminal and reconciled; use a new idempotency key.

Idempotency-Key is required: 1–100 letters, digits, underscore, dot, colon or dash. All other create fields are rejected. Existing v1 requests with source_file_key, model_id, operation, prompt and resolution remain valid. Job responses preserve the single output field and add outputs (zero or one item), effective_config, prompt_snapshot, client_reference and metadata so integrations can inspect what was accepted.

Authenticated curl: one private output

The sample ceiling is illustrative: compare it to wallet_holds_usd for the chosen model/resolution. The request receives 202 only after admission; it can receive 402 when the hold exceeds the ceiling (billing_ceiling_exceeded), or funds/budget are insufficient.

# Set these from your own account and GET /api/v1/ai/models.
# DITINY_API_KEY is read from your backend environment.
curl --fail-with-body https://i.ditiny.com/api/v1/ai/models \
  -H "X-API-Key: $DITINY_API_KEY"

# Save this JSON and key durably BEFORE the first POST.
# Replace source/model IDs with your owned file and enabled model.
cat > job.json <<'JSON'
{
  "source_file_key": "a63732f3-2c8f-412d-a8d2-f63188d548dc",
  "model_id": 1,
  "operation": "remockup",
  "prompt": "Place the reference artwork on one cream T-shirt. Preserve the lettering and colors.",
  "resolution": "1K",
  "size": {"mode": "square"},
  "num_outputs": 1,
  "output": {"visibility": "private"},
  "client_reference": "order-1042",
  "metadata": {"workflow": "product-preview"},
  "execution": {"target": "cloud"},
  "billing": {"max_cost_usd": "0.10"}
}
JSON
curl --fail-with-body https://i.ditiny.com/api/v1/ai/jobs \
  -H "X-API-Key: $DITINY_API_KEY" \
  -H "Idempotency-Key: order-1042-preview-v1" \
  -H "Content-Type: application/json" --data-binary @job.json

# Replace with the returned job ID; poll every 5–10 seconds.
curl --fail-with-body https://i.ditiny.com/api/v1/ai/jobs/JOB_ID \
  -H "X-API-Key: $DITINY_API_KEY"

Freeze a template version

Read /api/v1/ai/prompt-templates, choose a visible template requesting one image with a matching operation and submit its exact version. Replace prompt in the creation JSON with these fields; variables must match all {{name}} placeholders exactly, with no missing or extra keys; use an empty object for text without placeholders. Template edits or deletion do not rewrite an accepted job. A stale version returns 409; refetch and review before submitting a changed request with a new key.

"prompt_template_id": "40f6dc47-6f4a-4235-b519-0f3cf79bd94d",
"prompt_template_version": 2,
"variables": {"product": "cream T-shirt"}

Python quickstart

Install requests in your integration environment. Replace the sample image URL. Handle non-2xx responses using the error envelope below; honor Retry-After on 429/503 for safe reads. Persist the creation body and key; reconcile uncertain submissions with the same key before considering a new paid job.

import os, time, uuid
import requests
from urllib.parse import urljoin

base = "https://i.ditiny.com"
session = requests.Session()
session.headers["X-API-Key"] = os.environ["DITINY_API_KEY"]

def call(method, path, **kwargs):
    r = session.request(method, base + path, timeout=60, **kwargs)
    r.raise_for_status()
    return r.json()

# 1. Choose a model enabled by your Ditiny admin.
models = call("GET", "/api/v1/ai/models")["items"]
model = models[0]

# Reuse the exact versioned prompt; metadata does not create paid jobs.
prompts = call("GET", "/api/v1/ai/prompts")["items"]
preset = next((item for item in prompts if item["operation"] == "extract" and item["requested_images"] == 1), None)
if preset is None:
    raise RuntimeError("Create an Extract prompt template first, or use your own prompt")
# Keep preset["id"], ["version"] and ["sha256"] in your own audit record.

# 2. Reuse an existing Ditiny file_key, or import a public image.
source = call("POST", "/api/v1/ai/sources", json={
    "url": "https://your-site.example/reference.png"
})

# 3. Persist this key with your order before the first request.
# Reuse exactly this key AND body after a network timeout.
key = str(uuid.uuid4())
job = call("POST", "/api/v1/ai/jobs",
    headers={"Idempotency-Key": key}, json={
        "source_file_key": source["file_key"],
        "model_id": model["id"],
        "operation": preset["operation"],
        "prompt_template_id": preset["id"],
        "prompt_template_version": preset["version"],
        "variables": {},
        "resolution": model["resolutions"][0],
        "output": {"visibility": "private"}
    })

# 4. Poll; a production client should persist job_id and bound retries.
for attempt in range(120):
    job = call("GET", "/api/v1/ai/jobs/" + job["id"])
    if job["status"] in ("succeeded", "failed", "cancelled", "needs_review"):
        break
    time.sleep(5)

if job["output"]:
    output = job["output"]
    if output.get("download_url"):
        # Public original: no API key, signed URL or expiring redirect needed.
        # This URL can also be fetched directly by a third-party service.
        response = requests.get(urljoin(base, output["download_url"]),
                                stream=True, timeout=60)
    else:
        # Private outputs require the owner credentials.
        response = session.get(urljoin(base, output["url"]),
                               stream=True, timeout=60)
    with response as r:
        r.raise_for_status()
        with open("result.png", "wb") as f:
            for chunk in r.iter_content(65536):
                f.write(chunk)
print(job["status"], job["error"], job["fee"])
# A pending actual_cost_usd is None, not a free call.
# Save job_id and check again later for fee confirmation.

Inputs and transforms

Already on Ditiny: pass source_file_key directly, without downloading and re-uploading. Local file or clipboard: use the upload/init → signed PUT → upload/complete flow below, with is_public=false at init. General uploads allow 100 MiB, but AI references allow at most 20 MiB. PNG/JPEG/WebP are direct inputs; PSD/TIFF/GIF may be converted by the worker. AI/PostScript/SVG storage support does not imply AI generation support.

For URL input, POST a JSON object with url to /api/v1/ai/sources. Site discovery returns candidates only; import the chosen URL separately. Only public HTTPS pages are supported; login, JavaScript rendering and anti-bot bypass are not provided. Imports share the existing 20/user/minute and 60/global/minute quotas and two concurrent slots per API process.

Transforms accept PNG/JPEG/WebP/GIF up to 4 MP and 20 MiB. EXIF orientation is applied first, the working image is bounded to 2048px, then clockwise rotation and crop are applied. Crop coordinates are fractions of the entire expanded rotated frame (0–1); crop must fit inside it. Output is private PNG, longest edge ≤2048px, with alpha preserved. Animated GIF becomes its first frame. Large sources can be transformed locally or used unchanged. Server transforms run one at a time across all API workers in a supervised subprocess; busy returns 429 with Retry-After, and a limiter outage returns 503.

POST /api/v1/ai/sources/{file_key}/transform
{
  "rotation_degrees": 12.5,
  "crop": {"left": 0.1, "top": 0.2, "width": 0.7, "height": 0.6}
}

GET /api/v1/ai/prompts returns visible database templates with UUID id, integer version, operation, name, prompt, requested_images, sha256, scope (global/personal), and editable. The five defaults are Extract, Redesign, and Remockup for different products, the same product and seasonal designs. All request exactly one image. Migration021 converts only untouched original multi-image defaults; saved edits, personal copies and deleted templates are preserved. They are seeded once: edits and removals persist across restart. The list can grow or shrink; do not hardcode five entries or seed IDs. Use the template selection contract above to freeze a specific version into a job, or send its exact text as a custom prompt.

Manage templates at /ai-prompts or with the CRUD endpoints below. Every user can see global templates plus their own personal templates. Personal edit/remove is owner-only; global edit/remove/create requires an admin user and, for scoped API keys, both ai and admin scopes (JWT or legacy * follows the same role checks). Honor editable; an admin cannot use this API to edit another user's personal template. Copying a global template creates a new personal draft without changing the global original. Scope cannot change on PATCH; create a new copy instead.

POST /api/v1/ai/prompt-templates
{
  "name": "My product prompt",
  "operation": "remockup",
  "prompt": "Place the reference artwork on one cream T-shirt. Preserve its lettering and colors.",
  "requested_images": 1,
  "scope": "personal"
}

PATCH /api/v1/ai/prompt-templates/{id}
{
  "version": 1,
  "name": "My updated product prompt",
  "prompt": "Place the reference artwork on one navy T-shirt. Preserve its lettering and colors."
}

DELETE /api/v1/ai/prompt-templates/{id}?version=2

Creation defaults to personal scope. PATCH sends the current expected version and only changed editable fields; DELETE also requires its expected version. A 409 means the template changed: refetch and review the new version before retrying, while retaining unsaved text. Do not blindly retry with the latest version or overwrite someone else's edit. UI conflicts refresh the list without replacing the editor draft. Job history stores its complete original prompt/configuration independently of later template edits/removals.

Template text stays editable up to 4,000 characters. requested_images is metadata from 1 to 10 and changing it does not rewrite instructions. Listing, copying, saving or applying templates never generates images. The service currently creates one image per job; a multi-image template needs quantity configuration or an explicit edit of its requested quantity to one before creating a single-image job. The UI pauses creation for an unchanged multi-image template. Do not send an unchanged 10-image instruction to obtain a collage; no batch generation is implied by requested_images.

Creation accepts only documented fields. Model IDs come from the catalog. resolution is 1K or 2K when supported by the chosen model; size defaults to square, with custom/original_ratio/derived aspect_ratio only where capabilities enable them. Operations are generate (prompt-only, omit references), flatten (flat raster illustration), extract (reconstruct a standalone design), redesign (change the artwork) and remockup (preserve the reference design while changing its product, scene or presentation). For remockup, describe the target product, material, color and lighting. Preservation is a generative goal: exact pixels, lettering and transparent backgrounds are not guaranteed.

Text to image and output controls

Use operation=generate with model_id, prompt and resolution, omitting source_file_key, references and masks. No uploaded file is required and no editing preset is added. A frozen output instruction is appended when chroma key or size fallback is needed. source_file_key is null in the resulting job. Original-ratio sizing requires an image and is rejected for text to image. Check capabilities.text_to_image and operations in the model catalog.

{
  "operation": "generate",
  "model_id": 1,
  "prompt": "A cheerful red panda astronaut, clean illustration",
  "resolution": "1K",
  "size": {"mode": "aspect_ratio", "aspect_ratio": "3:4"},
  "output": {"visibility": "private", "background": "transparent", "format": "png"}
}

Use a Qwen 2.1 model_id from the catalog for the 3:4 example above. Check capabilities.aspect_ratios and size_modes for native sizes; transparent_background describes native alpha, while transparent_output.chroma_key describes postprocessing support. For Qwen transparency, the provider generates on pure green #00FF00, then Ditiny learns the green background from perimeter colors, removes matching shaded green and enclosed holes completely, and uses a foreground/background trimap and nearest outline colors to apply soft alpha only within a narrow artwork boundary before storing PNG or lossless WebP. Broad residual green, narrow key-colored contour fragments or an ambiguous key field fails output processing rather than returning a translucent background. Avoid green artwork: matching colors can also be removed. This is chroma keying, not semantic segmentation. A supported 3:4 ratio stays 3:4; only an unavailable size/ratio becomes square. effective_config.fallback records requested controls, reasons, actual canvas dimensions and whether background removal ran. In fallback mode, rectangular postprocess.resize is replaced by aspect-preserving containment and retained in fallback.requested. Missing usable foreground/background fails saving, retains provider fees under the existing policy and never automatically repeats the paid generation. Green matting accepts up to 8,388,608 input pixels; ordinary resize/format conversion accepts up to 24.3 MP. Both enforce the configured encoded output byte limit.

Progress, reruns and public outputs

Stages are queued → preparing → running → saving → succeeded, with failed/cancelled/needs_review alternatives. progress contains stage timestamps; percent is null because providers do not report reliable percentage progress. Output is available once the original is saved, without waiting for thumbnails. Poll every 5–10 seconds; GET job returns Retry-After: 5.

output.visibility defaults to public for v1 compatibility; choose private explicitly to keep a generated result owner-authenticated. output.public_url opens the original inline; output.download_url downloads it as an attachment. Both can be fetched by a third-party service without auth, signed URLs or a 900-second expiration. Links remain valid while the file exists and is public; making it private or deleting it revokes public access. Source sharing settings and existing outputs are unchanged. output.url remains the stable owner-authenticated API endpoint, including for private results: send your API key/JWT there; HEAD reads headers and ?download=true requests an attachment. No Range/resume support.

Private AI results have no share token and skip public Cloudflare thumbnails and generic file.processed callbacks. They are ready after original storage verification; use the authenticated original to preview them. Library thumbnails are unavailable for these private results. Explicitly publishing the file later allocates a share token.

effective_config.model_snapshot records provider kind, exact remote model ID and Ditiny adapter/capability schema versions. prompt_snapshot records template and preset versions and prompt hashes; this cannot pin the provider's internal model weights. Prepared reference text is limited to 32 MiB in aggregate before provider submission.

Persist the exact request JSON and Idempotency-Key before submission. Replaying that same key and body returns the same job, including after a timeout; do this only to recover the existing job identity. A changed body with the same key returns 409. To rerun with a new prompt/config, send POST jobs with parent_job_id and a new key. An active or needs_review parent blocks rerun. Never switch keys, providers, or execution modes automatically after an uncertain paid submission. A needs_review job requires reconciliation; refresh-fee only looks up billing and never generates a replacement image.

Limits per user: job/catalog/wallet/webhook reads and delivery history share 120/minute; webhook updates 6/minute; create and cancel each 20/minute; output 60/minute; fee lookup 6/minute plus once per job per 30 seconds. The existing active-job limit also applies. Import limits are separate from output reads. Redis limiter failures return 503. AI webhooks below provide asynchronous notifications; keep polling as a fallback. The existing file.processed event still waits for required processing (for images: attributes and all thumbnails), independently of AI job/output readiness and fee confirmation.

Wallet reservations and actual fees

Available USD = wallet balance − open holds. Creation/rerun requires sufficient available funds, including for admins. The catalog wallet_holds_usd reports the required hold for each resolution; job reservation_usd records its actual hold. Inspect the returned hold before choosing a request ceiling. These holds are not sale prices or actual charges. billing.max_cost_usd is an admission ceiling on that hold: a higher required hold returns 402 before a job is queued. It is not a guaranteed final bill or a provider-side spending limit; the actual charge can exceed it. A pending fee or needs_review keeps its hold until settled. Provider budget is an additional limit. Only admins can top up.

fee.actual_cost_usd and charged_usd are decimal strings, never floating-point values. Unknown actual fees stay null; do not interpret them as zero or substitute the reservation. Costs can be confirmed after the image is available, including for failed jobs that incurred provider charges. provider_confirmed distinguishes provider billing from admin reconciliation; source identifies provider_response, provider_lookup or admin_reconciliation. Keep checking the job, subscribe to ai.fee.updated, or use refresh-fee where supported.

If the provider charges more than the hold, the ledger records the actual amount. An overrun may make balance negative; new jobs stay blocked until an admin adds enough funds. Held/available fields are null until the R3 wallet implementation is present, and public job creation remains blocked before that release.

"fee": {
  "currency": "USD",
  "status": "reported",
  "actual_cost_usd": "0.031250000000",
  "charged_usd": "0.031250000000",
  "provider_confirmed": true,
  "source": "provider_response",
  "provider_request_id": "gen-example"
}

Provider usage and token counts

Job responses and webhook snapshots include nullable usage: input_tokens, output_tokens, total_tokens, cached_tokens, reasoning_tokens, image_tokens, input_image_tokens, output_image_tokens and images. Only counts explicitly reported by the provider are returned. Missing counts stay null; Ditiny does not calculate tokens from image dimensions, price or other counters. provider_metrics contains only bounded, allowlisted numeric provider metrics, with fractional values preserved as decimal strings, never raw provider responses. Availability varies by provider/model.

"usage": {
  "input_tokens": null,
  "output_tokens": null,
  "total_tokens": null,
  "cached_tokens": null,
  "reasoning_tokens": null,
  "image_tokens": null,
  "input_image_tokens": null,
  "output_image_tokens": null,
  "images": null,
  "provider_metrics": {}
}

Read actual USD cost from fee, independently of token availability. An image model may report a confirmed cost without reporting any token counts. Neither the wallet hold nor a token estimate is an actual provider charge.

AI webhooks: setup and delivery history

Configure one shared endpoint in Settings or GET/PUT /api/v1/ai/webhook. AI events are opt-in (ai_enabled defaults to false); omitting ai_enabled on an update preserves its current value. Enabling AI events additionally requires the R1 scope and R3 wallet-hold implementations. Existing file.processed subscriptions are unchanged. enabled is the shared master switch: both enabled and ai_enabled must be true for AI notifications. The same URL, HMAC secret and optional Bearer token serve both event families. GET and PUT /api/v1/ai/webhook require files+ai scopes together (or JWT/legacy *), since the shared URL may contain receiver credentials for the file feed. An ai-only key can read its jobs, outputs and AI delivery history, but cannot read or redirect this shared configuration. The internal /api/auth/me/webhook permits files-only configuration reads/updates only while AI events are off; when AI is on, both scopes are required. URL must be HTTPS, pass SSRF checks and match an API-key allowed domain. No per-job callback URL is accepted.

PUT /api/v1/ai/webhook
{
  "url": "https://your-site.example/ditiny-webhook",
  "enabled": true,
  "ai_enabled": true,
  "bearer_token": "optional-receiver-token",
  "rotate_secret": false
}

// GET/PUT response (signing_secret appears only on creation/rotation):
{
  "url": "https://your-site.example/ditiny-webhook",
  "enabled": true,
  "ai_enabled": true,
  "has_secret": true,
  "has_bearer_token": true,
  "signing_secret": null,
  "updated_at": "2026-10-18T12:00:00Z"
}

Events: ai.job.queued, ai.job.preparing, ai.job.running, ai.job.saving, ai.job.succeeded, ai.job.failed, ai.job.cancelled, ai.job.needs_review and ai.fee.updated. The job transition and event are written in the same transaction. Succeeded means the verified original was saved; notification creation does not wait for thumbnails. Delivery is asynchronous and has no immediate-delivery guarantee. Fee updates can arrive after a successful or failed image job and do not generate another image.

Each envelope contains id (stable UUID), event, created_at, sequence (globally increasing event ID), a job snapshot with status/configuration/timestamps and error information, plus output, fee and usage. Snapshots omit raw prompts and template variables, provider API keys, internal storage paths and raw billing payloads. Template audit data is limited to identity/version/hash. Client references and metadata are integration data; keep them free of secrets. Output includes public preview/download links when public, plus an owner-authenticated original URL. Public links stop working if a file is made private or removed; private output requires your Ditiny credentials.

// Selected fields from an AI event; GET job returns full current details.
{
  "id": "40f6dc47-6f4a-4235-b519-0f3cf79bd94d",
  "event": "ai.job.succeeded",
  "created_at": "2026-10-18T12:00:00Z",
  "sequence": 124,
  "job": {"id": "38b6a064-469e-4e1a-8cb3-ea81a7cf73c6", "status": "succeeded"},
  "output": {
    "file_key": "a63732f3-2c8f-412d-a8d2-f63188d548dc",
    "filename": "result.png",
    "url": "/api/v1/ai/jobs/38b6a064-469e-4e1a-8cb3-ea81a7cf73c6/output",
    "requires_auth": true,
    "is_public": true,
    "public_url": "https://i.ditiny.com/s/example-token/view/result.png",
    "download_url": "https://i.ditiny.com/s/example-token/original/result.png"
  },
  "fee": {"currency": "USD", "status": "reported", "actual_cost_usd": "0.031250000000"},
  "usage": {"input_tokens": null, "output_tokens": null, "total_tokens": null}
}

Delivery is at least once and can be out of order. Use id/X-Ditiny-Event-ID for durable deduplication; sequence is not a contiguous per-job progress counter or a delivery-order guarantee. Refetch the job when you need canonical current state. There are at most six delivery attempts: initial attempt, then delays of 60, 300, 900, 3600 and 21600 seconds. A stale processing lease is recovered after a worker interruption. Keep polling for recovery; there is no public manual-retry endpoint.

GET /api/v1/ai/webhook/deliveries?limit=30&offset=0
{
  "items": [{
    "id": "40f6dc47-6f4a-4235-b519-0f3cf79bd94d",
    "event": "ai.job.succeeded",
    "job_id": "38b6a064-469e-4e1a-8cb3-ea81a7cf73c6",
    "status": "succeeded",
    "attempts": 1,
    "last_http_status": 202,
    "last_error": null,
    "created_at": "2026-10-18T12:00:00Z",
    "next_attempt_at": "2026-10-18T12:00:00Z",
    "finished_at": "2026-10-18T12:00:02Z"
  }],
  "has_more": false
}

History is owner-only, including for admin keys. Delivery status is pending, processing, succeeded or failed, independently of the job status. Errors are sanitized and history never exposes receiver credentials. next_attempt_at schedules pending deliveries; it may retain the previous schedule after completion, so use status/finished_at to determine completion. Keep the signing secret only on your backend; it is shown once on creation or rotation.

Verify AI webhooks and queue work durably

Read the exact raw HTTP body before JSON parsing or reserialization. Verify X-Ditiny-Signature as sha256= + HMAC-SHA256(secret, X-Ditiny-Timestamp + "." + raw body), using a constant-time comparison and a 300-second clock tolerance. Verify your endpoint's optional Bearer token too when configured. X-Ditiny-Event-ID must match envelope id. Retry requests get a fresh timestamp/signature but keep the same event id. Commit the event ID and queued work together before returning 2xx; process business work in a separate worker.

The Python function below is the AI-event part of your HTTPS receiver and uses a durable SQLite inbox. Route existing file.processed events through your existing verifier: their legacy signing contract canonicalizes JSON and differs from AI's exact-raw-body contract. Do not change JSON formatting before verifying AI signatures. Use durable storage and idempotent background processing in production.

import hashlib, hmac, json, os, sqlite3, time, uuid

SECRET = os.environ["DITINY_WEBHOOK_SECRET"].encode()
INBOX = "ditiny-webhook-inbox.sqlite3"  # Persistent disk; back up this queue.
EVENTS = {"ai.job." + state for state in (
    "queued", "preparing", "running", "saving", "succeeded",
    "failed", "cancelled", "needs_review")}
EVENTS.add("ai.fee.updated")

with sqlite3.connect(INBOX) as db:
    db.execute("PRAGMA journal_mode=WAL")
    db.execute("CREATE TABLE IF NOT EXISTS inbox ("
               "event_id TEXT PRIMARY KEY, body BLOB NOT NULL, "
               "received_at INTEGER NOT NULL, status TEXT NOT NULL)")

# Call from your HTTPS route with the EXACT request bytes and headers.
# Handle file.processed through your existing file webhook receiver separately.
# Return this HTTP status immediately; a separate worker processes queued rows.
def accept_ai_webhook(raw_body, headers):
    if len(raw_body) > 2 * 1024 * 1024:
        return 413
    timestamp = headers.get("X-Ditiny-Timestamp", "")
    signature = headers.get("X-Ditiny-Signature", "")
    try:
        if abs(int(time.time()) - int(timestamp)) > 300:
            return 401  # Keep receiver and sender clocks synchronized.
    except ValueError:
        return 401
    expected = "sha256=" + hmac.new(
        SECRET, timestamp.encode() + b"." + raw_body, hashlib.sha256
    ).hexdigest()
    if not hmac.compare_digest(expected.encode("ascii"), signature.encode("utf-8")):
        return 401
    try:
        event = json.loads(raw_body)
        event_id = str(uuid.UUID(event["id"]))
        if (event_id != headers.get("X-Ditiny-Event-ID") or
                event["event"] not in EVENTS):
            return 400
    except (ValueError, TypeError, KeyError):
        return 400
    # Commit deduplication AND durable queued work in the same transaction.
    # Database errors must produce non-2xx so Ditiny retries the delivery.
    with sqlite3.connect(INBOX) as db:
        db.execute("PRAGMA synchronous=FULL")
        db.execute("INSERT INTO inbox VALUES (?, ?, ?, 'queued') "
                   "ON CONFLICT(event_id) DO NOTHING",
                   (event_id, raw_body, int(time.time())))
    return 202

# A separate durable worker claims inbox rows, applies changes idempotently,
# and marks them done. Keep event IDs after completion to deduplicate retries.
# Delivery is unordered: refetch GET job for canonical state when needed.
# Never repeat a paid generation because a webhook arrived twice.

Error contract

{
  "error": {
    "code": "insufficient_funds",
    "message": "Insufficient wallet funds",
    "request_id": "example",
    "retryable": false
  }
}

401 unauthenticated; 403 forbidden/scope; 404 missing or not owned; 402 insufficient_funds, provider_budget_exhausted or billing_ceiling_exceeded; 409 conflicting key/state; 413 too large; 415 unsupported format; 422 invalid request, unsupported controls, non-one output count or invalid template variables; 429 rate limit; 503 disabled, rollout prerequisite or capacity/dependency unavailable. Retrying a create request always requires the original idempotency key. Validation errors include field/message details and omit rejected input. Include X-Request-ID when contacting support. Proxy errors may use a different content type.

Health

GET/healthNone

Basic database and Redis health snapshot. Use GET: curl -I sends HEAD, which is not implemented and returns 405. HTTP 200 can still contain status=degraded, so inspect the JSON fields.

Request example / body

curl https://i.ditiny.com/health

Response example / excerpt

{
  "status": "ok",
  "version": "0.1.0",
  "db": "ok",
  "redis": "ok"
}

Authentication

POST/api/auth/loginNone

Sign in and get JWT token

Request example / body

{
  "email": "user@example.com",
  "password": "password"
}

Response example / excerpt

{
  "access_token": "eyJhbGciOiJIUzI...",
  "token_type": "bearer"
}

Upload

GET/api/upload/modesBearer / API Key

Discover the account-assigned upload mode, enabled transports, maximum size, endpoint, upload host, and connection requirement. Call this before choosing an upload flow.

Response example / excerpt

{
  "preferred_mode": "ditiny_gateway",
  "fallback_mode": "multipart",
  "max_file_size_bytes": 104857600,
  "modes": [
    { "mode": "multipart", "enabled": true, "upload_host": "i.ditiny.com" },
    { "mode": "native_presigned", "enabled": false, "upload_host": "<account-id>.r2.cloudflarestorage.com" },
    { "mode": "ditiny_gateway", "enabled": true, "upload_host": "uploads.i.ditiny.com" }
  ]
}
POST/api/upload/initBearer / API Key

Initialize native_presigned or ditiny_gateway upload. For an API key, mode must match the administrator-assigned mode. Set chunked:true to opt into resumable gateway parts for files larger than part_size (default 8 MiB). Inspect part_count: null means use the existing whole-file upload_url; otherwise use part_upload_url with {part_number} replaced, numbered from 1. Sessions expire after 30 minutes without extension. When direct parts are enabled, chunked sessions also return part_presign_url; null means use the gateway.

Request example / body

{
  "original_name": "photo.jpg",
  "mime_type": "image/jpeg",
  "size_bytes": 1048576,
  "mode": "ditiny_gateway"
}

Response example / excerpt

{
  "file_key": "uuid-string",
  "upload_mode": "ditiny_gateway",
  "upload_url": "https://uploads.i.ditiny.com/v1/files/uuid?token=<opaque>",
  "upload_host": "uploads.i.ditiny.com",
  "upload_headers": { "Content-Type": "image/jpeg" },
  "complete_url": "https://i.ditiny.com/api/upload/complete",
  "processing_status_url": "https://i.ditiny.com/api/files/uuid/processing-status",
  "status": "initialized",
  "expires_in": 1800
}
PUT{upload_url}Opaque upload URL only

Upload raw bytes to the exact URL returned by /init with every returned upload header. Never send the Ditiny API key or JWT. Gateway mode requires exact Content-Length and returns 201; native mode sends directly to R2.

Request example / body

curl -X PUT "<upload_url>" \
  -H "Content-Type: image/jpeg" \
  --data-binary "@photo.jpg"
POST/api/upload/parts/presignBearer / API Key

Optional direct R2 transport for an existing chunked ditiny_gateway session. Requires owner authentication with files scope and the server feature flag. Returns a signed URL for one exact part (up to 300 seconds), expected byte length and unchanged session expiry. Re-sign on retry if needed. PUT raw bytes directly to that URL without Ditiny credentials; R2 returns 200 with ETag, not gateway JSON. Gateway fallback can reuse the same session and part numbers.

Request example / body

{
  "file_key": "uuid-string",
  "part_number": 1
}

Response example / excerpt

{
  "file_key": "uuid-string",
  "part_number": 1,
  "upload_url": "https://<account>.r2.cloudflarestorage.com/<bucket>/<key>?<signature>",
  "upload_host": "<account>.r2.cloudflarestorage.com",
  "upload_headers": {},
  "size_bytes": 8388608,
  "expires_in": 300,
  "session_expires_at": "2026-10-27T14:00:00Z"
}
POST/api/upload/completeBearer / API Key

Finalize a native or gateway session after PUT. Ditiny verifies the R2 object and returns status=ready without waiting for thumbnail or attribute processing. Use processing-status.ready or file.processed for derived content readiness. Repeating complete for an already-finalized file is safe.

Request example / body

{
  "file_key": "uuid-string"
}

Response example / excerpt

{
  "status": "ready",
  "file_key": "uuid-string",
  "original_url": "https://i.ditiny.com/s/token/original",
  "original_expires_in": null,
  "preview_url": "https://<account-id>.r2.cloudflarestorage.com/<bucket>/<key>?<signature>",
  "preview_expires_in": 900,
  "processing_status_url": "https://i.ditiny.com/api/files/uuid-string/processing-status",
  "thumbnails": [{ "size_name": "md", "status": "pending", "url": null }]
}
POST/api/uploadBearer / API Key

Multipart compatibility flow. Send multipart/form-data with field file, up to 100 MiB. Ditiny streams the file through the API server to R2 and returns original/preview links after upload finalization; processing remains asynchronous.

Request example / body

curl -X POST https://i.ditiny.com/api/upload \
  -H "X-API-Key: <key>" \
  -H "Origin: https://your-configured-domain.example" \
  -F "file=@design.dst"

Response example / excerpt

{
  "file_key": "uuid-string",
  "upload_mode": "multipart",
  "upload_status": "uploaded",
  "share_token": "xYz1234abc",
  "is_public": true,
  "original_name": "design.dst",
  "file_category": "emb",
  "size_bytes": 245760,
  "storage_tier": "hot",
  "thumbnails": [],
  "stitch_count": null,
  "color_count": null,
  "file_attributes": {}
}

Upload Workflow

Start with GET /api/upload/modes and follow its enabledpreferred_mode. The API-key allowed-domain list checksOrigin/Referer on Ditiny API calls; it is separate from your company's outbound firewall allowlist. Never forward a Ditiny API key or JWT to the returned upload URL.
MODE 1 / FALLBACK

Multipart API Upload

Send the file directly to POST /api/upload as multipart form data. This compatibility mode accepts files up to 100 MiB and streams the file through the Ditiny API server to R2. Allow outbound HTTPS to i.ditiny.com. Do not call /initwhen your assigned mode is multipart.

# Multipart API upload
curl -X POST https://i.ditiny.com/api/upload \
  -H "X-API-Key: <your-api-key>" \
  -F "file=@design.dst"

# Response: complete file record
{
  "file_key": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "upload_status": "uploaded",
  "original_name": "design.dst",
  "file_category": "emb",
  "size_bytes": 245760,
  "storage_tier": "hot",
  "share_token": "xYz1234abc",
  "is_public": true,
  "thumbnails": [],
  "stitch_count": null,
  "color_count": null,
  "file_attributes": {}
}
Visibility warning: uploads are public by default. If a file must be private, immediately callPATCH /api/files/{file_key}with { "is_public": false }. This does not eliminate the public window between upload finalization and a successful PATCH. Do not upload secrets or data that must be private-at-create through the current API. The returned share token and thumbnail URLs are capability secrets; do not expose them unintentionally.

Python

import requests

r = requests.post(
    "https://i.ditiny.com/api/upload",
    headers={"X-API-Key": "<key>"},
    files={"file": open("design.dst", "rb")},
)
print(r.json()["file_key"])

Node.js

const form = new FormData();
form.append("file", fs.createReadStream("design.dst"));

const r = await fetch(
  "https://i.ditiny.com/api/upload",
  {
    method: "POST",
    headers: { "X-API-Key": "<key>" },
    body: form,
  }
);
const data = await r.json();

PHP

$ch = curl_init();
curl_setopt_array($ch, [
  CURLOPT_URL => "https://i.ditiny.com/api/upload",
  CURLOPT_POST => true,
  CURLOPT_HTTPHEADER => ["X-API-Key: <key>"],
  CURLOPT_POSTFIELDS => [
    "file" => new CURLFile("design.dst")
  ],
  CURLOPT_RETURNTRANSFER => true,
]);
$result = json_decode(curl_exec($ch));

Upload returns as soon as the file is finalized in R2. Call POST /api/files/{file_key}/processto dispatch thumbnail and attribute jobs immediately. A configured user webhook is sent after the required processing for that file category is ready. Prefer wait=false and poll the lightweight status endpoint. If you use wait=true through the public host, keep timeout_seconds at 55 or less.

Dispatch Processing After Multipart Upload

# Step 1: upload
upload = requests.post(
    "https://i.ditiny.com/api/upload",
    headers={"X-API-Key": "<key>"},
    files={"file": open("design.dst", "rb")},
).json()

# Step 2: process now
status = requests.post(
    f"https://i.ditiny.com/api/files/{upload['file_key']}/process",
    headers={"X-API-Key": "<key>"},
    json={"wait": False},
).json()

# Step 3: poll lightweight status
status = requests.get(
    f"https://i.ditiny.com/api/files/{upload['file_key']}/processing-status",
    headers={"X-API-Key": "<key>"},
).json()
MODE 2

Native Presigned R2

Fastest path: bytes never cross the Ditiny app server. Allow HTTPS to i.ditiny.com and the exact upload_host returned by each /init response. Browser clients also need an R2 CORS rule allowing their origin, PUT, and Content-Type.

# 1. Initialize with your Ditiny API key
POST https://i.ditiny.com/api/upload/init
{"original_name":"photo.jpg","mime_type":"image/jpeg","size_bytes":1048576,"mode":"native_presigned"}

# 2. PUT raw bytes to the exact upload_url
curl -X PUT "<upload_url>" \
  -H "Content-Type: image/jpeg" \
  --data-binary "@photo.jpg"

# 3. POST complete_url with Ditiny auth
{"file_key":"<file_key>"}
MODE 3

Ditiny Upload Gateway

Use this when your firewall cannot allowlist R2. Allow HTTPS to i.ditiny.com and the fixed host uploads.i.ditiny.com. The gateway validates the short-lived URL and streams bytes into R2; send exact Content-Type and Content-Length. Browser CORS is handled by the gateway.

# 1. Initialize
POST https://i.ditiny.com/api/upload/init
{"original_name":"photo.jpg","mime_type":"image/jpeg","size_bytes":1048576,"mode":"ditiny_gateway"}

# 2. PUT raw bytes; no Ditiny auth header
curl -X PUT "<upload_url>" \
  -H "Content-Type: image/jpeg" \
  --data-binary "@photo.jpg"

# 3. POST complete_url, then poll processing_status_url
{"file_key":"<file_key>"}

Opt-in resumable gateway parts

Send chunked: true at init. Only gateway sessions larger than the configured part size use parts; other sessions return null for part_size, part_count and part_upload_url. Never mix whole-file PUT and part PUT. Part authorization returns 403 if the owner account is disabled, and may return 429 when a session retries too quickly. Back off and retry the same part; a storage/authorization 503 is temporary. A gateway 410 means the session or multipart upload no longer exists. Keep the same file_key when retrying complete after a temporary error; a valid complete started before expiry can finish after its deadline. Keep the returned session, URL template, geometry and successful part numbers to resume within the original 30-minute expiry. There is no sliding expiry or server-side resume-list endpoint in this version.

# 1. Initialize (Ditiny auth required)
POST https://i.ditiny.com/api/upload/init
{"original_name":"artwork.png","mime_type":"image/png","size_bytes":16777339,"mode":"ditiny_gateway","chunked":true}

# Extra response fields; upload_url is still present for compatibility:
{"part_size":8388608,"part_count":3,"part_upload_url":"https://uploads.i.ditiny.com/v1/files/<file_key>/parts/{part_number}?token=<opaque>"}

# 2. Replace {part_number} with 1, 2, 3; PUT each Blob.slice range.
# Part lengths: 8388608, 8388608, 123 bytes. No Content-Type required.
# Browser supplies Content-Length; never set that forbidden header manually.
# No Ditiny API key/JWT on PUT. ETag and CF-Ray are exposed via CORS.
# Successful PUT: HTTP 201 {"status":"uploaded","file_key":"...","part_number":1}
# Retry a failed/uncertain part using the SAME URL and exact bytes.
# Limit to two active PUTs across ALL files in the tab.
# Retry with bounded backoff; separate idle timeout from total session budget.

# 3. Complete (Ditiny auth required); no client ETag list is needed:
POST https://i.ditiny.com/api/upload/complete
{"file_key":"<file_key>"}
# Missing/incorrect stored parts: 409 "Uploaded object not found..."
# Part PUT expires at 30 min; complete has 15 min recovery grace.
# Past completion grace: 410. Retrying complete after success is safe.

Gateway URLs contain a temporary bearer token; keep them out of logs. Each part is authorized separately. Complete lists and validates stored parts, then verifies the final object before returning original/preview links. An initialized chunked session has 15 minutes of completion grace after upload expiry; no new part PUTs are permitted during grace. Enable client chunking only after both the API migration and gateway Worker release are verified.

Optional direct R2 parts

If init returns a non-null part_presign_url, your backend may POST the file_key and part_number there using the same Ditiny credentials. Send only the returned signed URL and upload_headers to the browser. PUT the exact Blob slice directly to R2 with credentials omitted; do not attach API keys, JWTs or gateway tokens. R2 success is HTTP 200 with an ETag header and an empty body, not gateway JSON. Each selected bucket must allow the browser origin and PUT through CORS, and expose ETag.

# After the existing chunked init:
POST <part_presign_url>  # Ditiny authentication required, files scope
{"file_key":"<file_key>","part_number":1}
# Response: upload_url, upload_host, upload_headers={}, size_bytes,
# expires_in (at most 300 seconds), session_expires_at (unchanged).

# Browser: PUT the exact part bytes to the signed upload_url.
# Use the URL unchanged. Browser sets Content-Length. Do not parse success as JSON.
# On expired URL, request a fresh signature for the SAME part.
# If direct transport fails, retry the SAME part via the original gateway template.
# Re-uploading a part replaces it; never upload different bytes for that part number.
# Complete via Ditiny exactly as before. No client-supplied ETag list.

# 401: missing/invalid authentication. 403: key scope/domain restriction.
# 404: unknown/non-owned/deleted session or wrong upload mode.
# 409: whole-file session, invalid part number for this file, or terminal state.
# 410: session expired. 422: malformed request. 429: signing rate limit.
# 503: direct parts disabled; fall back to gateway on the same session.

Direct URLs do not extend the 30-minute session. Disabling direct signing leaves gateway uploads available; issued signatures remain valid until their expiry. Do not log signed URLs. Record attempt IDs, file_key, part number, transport, bytes sent, timings, active PUT count, HTTP status and cancellation reason for comparisons.

Database contention/timeouts return HTTP 503 with Retry-After: 2. For completion, retry the same file_key rather than uploading a duplicate. Pool checkout, connection and query limits apply per operation; they are not a guaranteed end-to-end HTTP deadline and do not include all storage work. Ditizy uploads continue through the gateway.

Deferred Processing Expectations

Raster uploads accept image/jpeg, image/png, image/webp, image/avif, image/bmp, image/tiff, image/gif and image/svg+xml (AVIF and BMP added 2026-10-21). PSD uploads accept image/vnd.adobe.photoshop and common Photoshop MIME aliases. AI uploads accept application/postscript, application/illustrator, application/x-illustrator and application/vnd.adobe.illustrator. PDF-compatible AI files can use application/pdf; application/octet-stream is also accepted. Uploading these formats does not guarantee browser preview or thumbnail generation.

File TypeThumbnailsAttributes
Raster imagesm, md, lgDeferred queue
PSD / AINot guaranteed; depends on encodingNot guaranteed
SVGNot guaranteedNot guaranteed
Embroiderysm, md, lgDeferred queue
PDFsm, md, lgDeferred queue
Office (DOC/XLS/PPT)sm, md, lgN/A
VideoN/ADeferred queue; attributes may be empty
OtherN/AN/A

Upload success does not wait for post-processing. A thumbnail-capable file is ready only after sm, md, and lg are ready and all required jobs have succeeded.

Embroidery Metadata

Processed Wilcom EMB response

Metadata extraction is asynchronous. Wait for attributes_status=succeeded, then read GET /api/files/{file_key} or the file.processed webhook.

Image and embroidery files also carry file_attributes.tone once their thumbnails are ready: Version 2 weights visible pixels by alpha, including sparse and translucent lettering. Prefer background_color (validated hex) or background (light/dark/neutral), independent of the app theme. Keep the thumbnail alpha channel. Missing metadata should use a neutral gray backdrop (#777777).

{
  "version": 2,
  "class": "light",
  "luma": 0.9,
  "opaque_ratio": 0.1,
  "contrast": 0.03,
  "has_transparency": true,
  "background": "dark",
  "background_color": "#30343b",
  "content_bounds": {
    "x": 0.1,
    "y": 0.05,
    "width": 0.8,
    "height": 0.4
  },
  "empty": false
}

content_bounds describes visible ink in normalized canvas coordinates (x/y/width/height, 0–1). For transparent artwork, fit that region with a small margin in your preview, preserving the original aspect ratio. This is display metadata: originals and stored thumbnails remain unchanged. Old files can lack these fields until an administrator runs a bounded metadata backfill.

{
  "width": 52,
  "height": 14,
  "stitch_count": 1770,
  "color_count": 1,
  "file_attributes": {
    "source_format": ".emb",
    "container_type": "wilcom_emb",
    "width_mm": 52.19,
    "height_mm": 13.8,
    "dim_source": "wilcom_props",
    "stitch_count": 1770,
    "color_count": 1,
    "thread_changes": 0,
    "trim_count": 7,
    "object_count": 1,
    "machine_type": "Tajima",
    "design_type": "Native design",
    "has_embedded_preview": true,
    "thread_palette": [
      {
        "index": 1,
        "stitches": 1770,
        "name": "Black",
        "brand": "Default",
        "hex": "#000000"
      }
    ]
  }
}

Dimension semantics

For Wilcom EMB, Ditiny reads width and height directly from design properties in 1/180 mm units. Use the floating-point file_attributes.width_mm and height_mm values for hoop checks or costing. Top-level width and height are rounded millimetres kept for compatibility.

SourceMeaning
wilcom_propsDimensions stored in the Wilcom EMB metadata.
thumbnail_estApproximate fallback when the Wilcom properties are absent.
key omittedDST/PES/JEF and similar formats use the stitch bounding box.
All embroidery keys are optional and source-format dependent. Ditiny can also return thread_changes, trim_count, object_count, machine_type, design_type, and thread_palette when present. Full multiple colorways, ordered stop-sequence records, catalog codes/thread lengths, EMB version/grade, appliqué, sequin, bling/bead, and lettering/monogram/order metadata are not currently returned.

Files

GET/api/filesBearer / API Key

List files (own files for users, all for admin). Owner can see initialized/expired uploads with upload_status for retry or diagnosis.

Response example / excerpt

{
  "items": [
    {
      "file_key": "uuid-string",
      "upload_status": "uploaded",
      "share_token": "xYz1234abc",
      "thumbnails": []
    }
  ],
  "total": 100,
  "page": 1,
  "limit": 50,
  "pages": 2
}
GET/api/files/{file_key}Bearer / API Key

Get file details with upload_status, thumbnails, attributes, and share info. For embroidery, prefer file_attributes.width_mm and height_mm over the rounded legacy width and height fields. share_token is null until upload complete.

GET/api/files/{file_key}/processing-statusBearer / API Key

Lightweight polling endpoint for thumbnail and attribute status. Does not write view access logs.

Response example / excerpt

{
  "file_key": "uuid-string",
  "upload_status": "uploaded",
  "attributes_status": "succeeded",
  "thumbnail_status": "processing",
  "thumbnails": { "sm": "ready", "md": "processing", "lg": "queued" },
  "ready": false,
  "webhook_status": null,
  "status": "processing"
}
POST/api/files/{file_key}/processBearer / API Key

Dispatch required thumbnail and attribute jobs immediately. Prefer wait=false and poll processing-status. For a synchronous public request, use wait=true with timeout_seconds no greater than 55 seconds to stay below the 60-second proxy timeout.

Request example / body

{
  "wait": true,
  "timeout_seconds": 55
}

Response example / excerpt

{
  "file_key": "uuid-string",
  "upload_status": "uploaded",
  "attributes_status": "queued",
  "thumbnail_status": "queued",
  "thumbnails": { "sm": "queued", "md": "queued", "lg": "queued" },
  "ready": false,
  "webhook_status": null,
  "status": "queued"
}
PATCH/api/files/{file_key}Bearer / API Key

Update file (name, visibility)

Request example / body

{
  "original_name": "new-name.jpg",
  "is_public": true
}
DELETE/api/files/{file_key}Bearer / API Key

Delete an owned file using an API key with files scope, or Bearer token; admins can delete any file. Returns 204 with no body; repeating normally returns 404. This is soft delete: original storage is not purged immediately. Fresh share and thumbnail gateway requests then return 404/410, and a background job revokes Cloudflare Images thumbnails (provider errors or queue backlog can delay this). Previously issued signed storage URLs may remain usable until expiry. The public API has no restore endpoint.

GET/api/files/{file_key}/downloadBearer / API Key

Get presigned download URL (302 redirect)

GET/api/files/{file_key}/download-urlBearer / API Key

Return a fresh private presigned GET URL (900 seconds, Cache-Control: private, no-store). Ditiny resolves each file’s storage account and bucket. Browser downloads must omit credentials; every storage bucket needs GET/HEAD CORS for the client origin.

Response example / excerpt

{
  "url": "https://r2-presigned-url...",
  "expires_in": 900
}
GET/api/dashboard/statsBearer / API Key

Dashboard statistics (files, storage, categories)

Tags

GET/api/tagsBearer / API Key

List all tags

POST/api/tagsAdmin Bearer / API Key

Create a tag. The authenticated account must have the admin role.

Request example / body

{
  "name": "important",
  "color": "#FF0000"
}
DELETE/api/tags/{tag_id}Admin Bearer / API Key

Delete a tag. The authenticated account must have the admin role.

POST/api/files/{file_key}/tagsBearer / API Key

Add tag to file

Request example / body

{
  "tag_id": 1
}
DELETE/api/files/{file_key}/tags/{tag_id}Bearer / API Key

Remove tag from file

Share Links

GET/s/{share_token}None (public HTML)

Browser-facing HTML preview page. No API authentication is required, but the file must be public and not deleted. Server-to-server clients that need JSON must use the /json route.

GET/s/{share_token}/jsonNone (share token)

Public JSON metadata for server-to-server clients. Available only when the file is public and not deleted. preview_url, when present, is a temporary presigned URL.

Response example / excerpt

{
  "file_key": "uuid",
  "original_name": "photo.jpg",
  "mime_type": "image/jpeg",
  "file_category": "image",
  "size_bytes": 1048576,
  "file_attributes": {},
  "preview_url": "https://temporary-presigned-url.example",
  "thumbnails": [
    { "size_name": "sm", "status": "pending", "url": null, "width_px": 300, "height_px": 300 },
    { "size_name": "md", "status": "ready", "url": "https://i.ditiny.com/s/{share_token}/thumb/md", "width_px": 600, "height_px": 600 }
  ],
  "is_downloadable": true
}
GET/s/{share_token}/view/{filename}None (public file)

Permanent public original URL. Streams the original bytes with Content-Disposition: inline so supported images open directly in the browser; no redirect, API token or URL expiry. Also supports HEAD. URL-encode filename; the stored filename and MIME type remain authoritative. Returns 404 for private or invalid tokens, 410 for deleted files, 409 for unfinished uploads. No Range/resume support.

Thumbnails

GET/s/{share_token}/thumb/{sm|md|lg}share_token (URL secret)

Stable capability URL that redirects to a ready thumbnail in Cloudflare Images. Sizes are sm=300px, md=600px, and lg=1200px. New files use three variants of one shared preview; URLs and webhook payloads are unchanged. Thumbnails keep the source alpha channel (since 2026-10-22): transparent PNG/WebP/AVIF/GIF/SVG sources yield transparent WebP, so draw your own backdrop; use file_attributes.tone to pick a contrasting one. Anyone holding the URL can access the thumbnail even when is_public=false; keep share_token secret. After upload completion, requests fall back to a temporary signed original URL with no-store until the thumbnail is ready. Soft-deleted files return 404 immediately; their Cloudflare Images copies are deleted by a background job within minutes, so cached redirects and copied direct URLs stop working shortly after.

Webhooks

GET/api/auth/me/webhookBearer / API Key

Get your shared webhook setting, including ai_enabled (false by default). See Public AI Images API for AI events.

PUT/api/auth/me/webhookBearer / API Key

Configure one shared user webhook. file.processed behavior is preserved; ai_enabled opts into AI job and fee events (see Public AI Images API). The URL must use HTTPS; literal localhost/private/reserved IP hosts are rejected, but this is not complete DNS-rebinding protection. Its host must match a configured API-key allowed domain.

Request example / body

{
  "url": "https://example.com/ditiny-webhook",
  "enabled": true,
  "ai_enabled": false,
  "bearer_token": "optional-receiver-token",
  "rotate_secret": false
}

Response example / excerpt

{
  "url": "https://example.com/ditiny-webhook",
  "enabled": true,
  "ai_enabled": false,
  "has_secret": true,
  "has_bearer_token": true,
  "signing_secret": "shown-on-create-or-rotate"
}
POSTUser webhook URLHMAC / optional Bearer

Ditiny sends file.processed after required jobs succeed. Category other emits no event, and configuring a webhook after a file is already ready does not backfill it. The current HMAC signs timestamp plus Python canonical JSON (json.dumps(parsed_body, separators=(",", ":"), sort_keys=True)), which may differ from the raw HTTP body; hashing raw bytes can fail. A private file payload can still contain a share URL that returns 403.

Response example / excerpt

{
  "event": "file.processed",
  "status": "succeeded",
  "file_key": "uuid-string",
  "share_token": "xYz1234abc",
  "file_category": "emb",
  "attributes": { "stitch_count": 22258, "color_count": 6 },
  "share": { "path": "/s/xYz1234abc", "url": "https://i.ditiny.com/s/xYz1234abc" },
  "thumbnails": [
    { "size_name": "sm", "path": "/s/xYz1234abc/thumb/sm", "url": "https://i.ditiny.com/s/xYz1234abc/thumb/sm", "width_px": 300, "height_px": 240 }
  ]
}
GET/api/files/{file_key}/webhook-deliveriesBearer / API Key

List webhook delivery history for a file owned by the current user. Admins can also inspect any file.

Response example / excerpt

[
  {
    "id": 123,
    "file_key": "uuid-string",
    "event_type": "file.processed",
    "status": "succeeded",
    "attempts": 1,
    "next_attempt_at": "2026-05-23T00:00:00Z",
    "last_status_code": 200,
    "last_error": null,
    "created_at": "2026-05-23T00:00:00Z",
    "updated_at": "2026-05-23T00:00:03Z"
  }
]

Rate Limits

EndpointLimit
POST /api/upload600 req/min per IP and per user/API key; global application cap 60,000 req/min; max 50 concurrent per API process
POST /api/upload/init, /complete1,200 req/min per user (also part presign); global application cap 12,000 req/min across all users through Redis
POST /api/upload/internal/gateway/authorizeNo per-IP proxy limit (Worker secret plus a per-session limiter of max(16, 4 × part_count) req/min)
GET /api/files/*/download*600 req/min per IP on the canonical host
GET /s/{token}, /json600 req/min per IP
GET /s/{token}/thumb/*3,000 req/min per IP, burst 300 (since 2026-10-28)
All other /api/*600 req/min per IP

These are sustained proxy ceilings; burst and application-level controls also apply. Since 2026-10-28 every proxy rate-limit response is a JSON 429 with Retry-After (previously some paths returned 503). On 429 or a transient 503, honorRetry-Afterwhen present, otherwise use bounded exponential backoff and jitter for safe reads. For paid AI job creation, preserve the original Idempotency-Key and exact body; reconcile an uncertain submission before starting a new job.

Common Errors

StatusMeaning and action
400 / 422Invalid request or validation error; correct the request before retrying.
402AI wallet funds, provider budget, or request cost ceiling prevents admission; inspect the Public AI error code and message.
401Missing or invalid JWT/API key.
403Inactive account, insufficient role, private share, or API-key domain mismatch.
429Honor Retry-After before retrying the same request. Rate-limit advice uses remaining window time, rounded up to at least one second.
404 / 410Resource not found, thumbnail not ready, or share file deleted.
409Upload state/object validation conflict; inspect detail before retrying.
413 / 415File is too large or its MIME type is unsupported; do not retry unchanged.
503Disabled flow or temporary capacity issue; apply bounded backoff and honor Retry-After when provided.

File API errors normally use { "detail": ... }. Public AI v1 uses the error envelope documented above. Proxy-generated errors may use another content type. Include the X-Request-ID response header when contacting support, when present.

Supported File Formats

Images

JPEG, PNG, WebP, TIFF, GIF, SVG

Videos

MP4, MOV, AVI, MKV, WebM

Documents

PDF, DOC/DOCX, XLS/XLSX, PPT/PPTX

Embroidery

EMB, DST, PES, JEF, VP3, HUS, EXP