logo

Artwork readiness API · Developer guide

Check artwork before it reaches the press

Send a PNG, JPEG or PDF and the size you plan to print it. The API measures effective DPI, transparency and proportions, and returns a report with findings and preview images.

Prelaunch / pilot. Public documentation is a preview, not a release announcement. Paid purchases and analysis depend on service configuration and launch approval; they may be unavailable. Check the dashboard for account availability and configured pricing.

Base URL
https://api.imagepresto.com
Authentication
Bearer API key (ip_art_...)
Formats
PNG, JPEG, PDF (up to 20 pages)
Cost
1 credit per image or PDF page

Quickstart

No Image Presto subscription required. You need an account, API credits and an API key; all three are in the API dashboard.

  1. Create an API key. The full key is shown once. Store it as ARTWORK_API_KEY on your server.
  2. Get a quote. Upload the file with its print size. You get back the credit cost and a quote_id. Nothing is charged.
  3. Submit the quote. This reserves the credits and queues the check.
  4. Poll for the report. Fetch the check every few seconds until it is completed.
# 1. Quote: upload once and see the cost. Nothing is charged.
curl https://api.imagepresto.com/api/v1/artwork-checks/quote \
  -H "Authorization: Bearer $ARTWORK_API_KEY" \
  -F "file=@artwork.png" \
  -F "width=10" \
  -F "height=5" \
  -F "unit=in"

# 2. Submit the quote. This reserves the credits.
curl https://api.imagepresto.com/api/v1/artwork-checks \
  -H "Authorization: Bearer $ARTWORK_API_KEY" \
  -H "Idempotency-Key: order-18422-front" \
  -H "Content-Type: application/json" \
  -d '{"quote_id": "7b1e6f0a-2c3d-4e5f-8a9b-0c1d2e3f4a5b"}'

# 3. Poll until processing_status is "completed" or "failed".
curl https://api.imagepresto.com/api/v1/artwork-checks/3d5c9a2e-7f41-4b8a-9c1d-5e6f7a8b9c0d \
  -H "Authorization: Bearer $ARTWORK_API_KEY"

Authentication

Send your API key in the Authorization header on every request, over HTTPS:

Header
Authorization: Bearer ip_art_your_key_here
  • Keys belong to one account. A key can only see that account's checks.
  • Call the API from your server. Never put a key in a browser, a mobile app, a URL or a repository. Keys in query strings are rejected.
  • To rotate, create a new key, switch your integration over, then revoke the old one. Revoking takes effect immediately and does not cancel checks already accepted.

Endpoints

Get a quote

POST/api/v1/artwork-checks/quote

Validates a file and tells you what it will cost. No credits are reserved and no report is produced. The uploaded file is kept for 30 minutes so you can submit it by quote_id without uploading again.

Form fields (multipart/form-data)
NameTypeDescription
filerequiredfilePNG, JPEG or PDF. Up to 25 MiB. The type is detected from the file contents, not the filename.
widthrequirednumberIntended print width. Must be greater than 0.
heightrequirednumberIntended print height. Must be greater than 0.
unitrequiredstringin or mm.
garment_colorstringOptional #RRGGBB color. Stored with the check; it does not change the measurements.
Request
curl https://api.imagepresto.com/api/v1/artwork-checks/quote \
  -H "Authorization: Bearer $ARTWORK_API_KEY" \
  -F "file=@artwork.png" \
  -F "width=10" \
  -F "height=5" \
  -F "unit=in"
Response · 200
{
  "page_count": 1,
  "credits": 1,
  "input_hash": "9f2c1d0e...64 hex characters",
  "tariff_version": 1,
  "quote_id": "7b1e6f0a-2c3d-4e5f-8a9b-0c1d2e3f4a5b",
  "quote_expires_at": "2026-11-18T12:30:00.000000+00:00"
}
Response fields
NameTypeDescription
page_countinteger1 for an image; the number of pages for a PDF.
creditsintegerCredits the check will reserve.
quote_idUUIDPass this to Submit a check. Single use.
quote_expires_attimestampWhen the stored upload is discarded.
input_hashstringFingerprint of the file and options. Only needed if you re-upload the file instead of using quote_id.
tariff_versionintegerPricing rule version. Currently 1.

Each account keeps at most 10 unused quotes; older ones are discarded.

Submit a check

POST/api/v1/artwork-checks

Reserves credits and queues the check. Returns 202 Accepted straight away; the report is produced in the background.

Headers
NameTypeDescription
Idempotency-KeyrequiredstringYour unique ID for this check: 1–200 visible ASCII characters, no spaces. See Idempotency and retries.
X-Artwork-Input-HashstringOptional. The quote's input_hash. Send it together with X-Artwork-Expected-Credits.
X-Artwork-Expected-CreditsintegerOptional. The credits you agreed to. If the real cost differs, the request fails with 409 quote_changed and nothing is reserved.

Option 1: submit a quote (recommended)

Send JSON with the quote_id. The file is not uploaded again.

Request
curl https://api.imagepresto.com/api/v1/artwork-checks \
  -H "Authorization: Bearer $ARTWORK_API_KEY" \
  -H "Idempotency-Key: order-18422-front" \
  -H "Content-Type: application/json" \
  -d '{"quote_id": "7b1e6f0a-2c3d-4e5f-8a9b-0c1d2e3f4a5b"}'

Option 2: upload the file directly

Send the same form fields as a quote. Use this when you do not need to show the cost first.

Request
curl https://api.imagepresto.com/api/v1/artwork-checks \
  -H "Authorization: Bearer $ARTWORK_API_KEY" \
  -H "Idempotency-Key: order-18422-front" \
  -F "file=@artwork.png" \
  -F "width=10" \
  -F "height=5" \
  -F "unit=in"
Response · 202
{
  "id": "3d5c9a2e-7f41-4b8a-9c1d-5e6f7a8b9c0d",
  "processing_status": "queued",
  "reserved_credits": 1,
  "report_url": "/api/v1/artwork-checks/3d5c9a2e-7f41-4b8a-9c1d-5e6f7a8b9c0d"
}
Response fields
NameTypeDescription
idUUIDThe check ID. Store it; you need it to fetch the report.
processing_statusstringqueued, running, completed or failed.
reserved_creditsintegerCredits reserved for this check.
report_urlstringPath of the Retrieve a check endpoint for this check.

Retrieve a check

GET/api/v1/artwork-checks/{id}

Returns the status and, once completed, the report. Poll this endpoint every few seconds until processing_status is completed or failed. Both are final. There are no webhooks.

Request
curl https://api.imagepresto.com/api/v1/artwork-checks/3d5c9a2e-7f41-4b8a-9c1d-5e6f7a8b9c0d \
  -H "Authorization: Bearer $ARTWORK_API_KEY"
Response · 200 (completed, trimmed)
{
  "id": "3d5c9a2e-7f41-4b8a-9c1d-5e6f7a8b9c0d",
  "processing_status": "completed",
  "credits": 1,
  "created_at": "2026-11-18T12:01:07.412000+00:00",
  "completed_at": "2026-11-18T12:01:11.903000+00:00",
  "source": "api",
  "key_id": "c2a4e6f8-1b3d-4f5a-8c7e-9d0b1a2c3e4f",
  "key_label": "Order intake",
  "key_suffix": "x4Qz9A",
  "requested_size": { "width": 10, "height": 5, "unit": "in" },
  "reservation_status": "settled",
  "report_state": "retained",
  "report_expires_at": "2027-02-16T12:01:11.903000+00:00",
  "media_expires_at": "2026-11-19T12:01:07.412000+00:00",
  "readiness": "issues_found",
  "error_code": null,
  "report": {
    "schema_version": 1,
    "processing_status": "completed",
    "readiness": "issues_found",
    "requested_size": { "width": 10, "height": 5, "unit": "in" },
    "rule_settings": {
      "version": 1,
      "target_dpi": 300,
      "minimum_dpi": 150,
      "aspect_tolerance": 0.01
    },
    "pages": [
      {
        "page_number": 1,
        "format": "PNG",
        "source_pixels": { "width": 2000, "height": 1000 },
        "effective_dpi": { "x": 200, "y": 200 },
        "fitted_size_inches": { "width": 10, "height": 5 },
        "aspect_ratio_error": 0,
        "alpha": { "has_transparency": false }
      }
    ],
    "findings": [
      {
        "code": "below_target_dpi",
        "severity": "warning",
        "message": "... This is below the configured target 300 DPI. ...",
        "evidence": {
          "scenario": "full_canvas",
          "effective_dpi": { "x": 200, "y": 200 },
          "target_dpi": 300,
          "minimum_dpi": 150
        },
        "limitations": [
          "Pixel count cannot establish whether the source was previously enlarged."
        ],
        "rule_version": 1
      }
    ],
    "customer_explanation": "Measured artwork properties triggered the listed size, resolution or visibility flags. ..."
  },
  "preview_urls": [
    "/api/v1/artwork-checks/3d5c9a2e-7f41-4b8a-9c1d-5e6f7a8b9c0d/preview?index=0",
    "/api/v1/artwork-checks/3d5c9a2e-7f41-4b8a-9c1d-5e6f7a8b9c0d/preview?index=1",
    "/api/v1/artwork-checks/3d5c9a2e-7f41-4b8a-9c1d-5e6f7a8b9c0d/preview?index=2"
  ],
  "previews": [
    { "url": "...preview?index=0", "page_number": 1, "background": "checkerboard", "ordinal": 0 },
    { "url": "...preview?index=1", "page_number": 1, "background": "light", "ordinal": 1 },
    { "url": "...preview?index=2", "page_number": 1, "background": "dark", "ordinal": 2 }
  ]
}
Response fields
NameTypeDescription
processing_statusstringqueued, running, completed or failed.
readinessstring | nullno_flags, issues_found or inconclusive. Null until completed.
reportobject | nullThe full report. See Reading the report. Null before completion and after the report expires.
previewsarrayPreview images with their page number and background. Empty once previews expire.
reservation_statusstringreserved while running, settled when charged, released when returned.
error_codestring | nullWhy a check failed, for example analysis_timeout or invalid_or_expired_media.
media_expires_attimestampWhen the upload and previews are deleted.
report_expires_attimestamp | nullWhen the report is deleted.

List checks

GET/api/v1/artwork-checks

Returns your account's checks, newest first.

Query parameters
NameTypeDescription
limitinteger1–100. Default 20.
cursorstringThe next_cursor from the previous page. Keep the same filters between pages.
statusstringqueued, running, completed or failed.
key_idUUIDOnly checks submitted with this API key.
created_aftertimestampISO 8601 with a time zone, for example 2026-11-18T00:00:00Z.
created_beforetimestampISO 8601 with a time zone.
Request
curl "https://api.imagepresto.com/api/v1/artwork-checks?status=completed&limit=20" \
  -H "Authorization: Bearer $ARTWORK_API_KEY"
Response · 200
{
  "checks": [
    {
      "id": "3d5c9a2e-7f41-4b8a-9c1d-5e6f7a8b9c0d",
      "processing_status": "completed",
      "credits": 1,
      "created_at": "2026-11-18T12:01:07.412000+00:00",
      "completed_at": "2026-11-18T12:01:11.903000+00:00",
      "source": "api",
      "requested_size": { "width": 10, "height": 5, "unit": "in" },
      "reservation_status": "settled",
      "report_state": "retained",
      "readiness": "issues_found"
    }
  ],
  "next_cursor": "WyIyMDI2LTExLTE4VDEyOjAxOjA3..."
}

next_cursor is null on the last page. Unknown or repeated query parameters return 422.

Download a preview

GET/api/v1/artwork-checks/{id}/preview?index={n}

Returns one preview as image/png. Each page has three previews: on a checkerboard, a light and a dark background. Use the URLs in the previews array from Retrieve a check, which tell you the page and background of each index.

Request
curl "https://api.imagepresto.com/api/v1/artwork-checks/3d5c9a2e-7f41-4b8a-9c1d-5e6f7a8b9c0d/preview?index=0" \
  -H "Authorization: Bearer $ARTWORK_API_KEY" \
  --output preview-page1-checkerboard.png

Previews need the same Authorization header as every other request, so the URLs cannot be used directly in an <img> tag. They return 404 after 24 hours. The original upload cannot be downloaded.

OpenAPI schema

GET/api/v1/artwork-checks/openapi.json

The machine-readable description of these endpoints, generated from the running service. No API key is needed. Download OpenAPI JSON.

Reading the report

Start with readiness, then read findings for the reasons.

Readiness values
ValueMeaning
no_flagsNothing crossed a warning or error threshold at the requested size.
issues_foundAt least one warning or error, such as low resolution or mismatched proportions.
inconclusiveMeasured, but the result depends on something the API cannot judge, such as partial transparency. Still a completed, charged check.
Finding codes
CodeSeverityMeaning
below_minimum_dpierrorEffective DPI at the requested size is under your minimum.
below_target_dpiwarningEffective DPI is above your minimum but under your target.
aspect_mismatchwarningThe artwork's proportions differ from the requested area by more than your tolerance.
partial_alphawarningSome pixels are semi-transparent.
transparent_marginsinfoThe visible artwork is smaller than the canvas.
empty_artworkerrorThe image has no visible pixels.
pdf_measurement_limitationswarningPart of a PDF page could not be measured reliably.
  • Thresholds are yours. Target DPI, minimum DPI and aspect tolerance are set in the dashboard. Each report records the values it used in rule_settings.
  • Each finding carries its evidence. evidence holds the measured numbers, message is a sentence you can show a customer, and limitations says what the measurement cannot prove.
  • Pages differ by file type. Image pages report pixel dimensions, effective DPI and transparency. PDF pages report page boxes and each placed image; vector content has no DPI.
  • It is a measurement, not an approval. The API cannot judge sharpness, color accuracy or how a file will look on a particular garment.
  • Record the versions. Reports include schema_version, and each finding its rule_version.

Errors

Errors are JSON with a stable code. Branch on the status and code, not the message. Quote the request_id when you contact support.

Error response
{
  "error": {
    "code": "insufficient_credits",
    "message": "Insufficient artwork credits"
  },
  "request_id": "11111111-1111-4111-8111-111111111111"
}
Status codes
StatusCodeWhat to do
400invalid_requestMalformed request, or a credential in the URL. Fix the request.
401unauthorized, invalid_keyMissing, revoked or expired key. Check the header and the key.
402insufficient_creditsNot enough credits. Buy more, then retry with the same key and inputs.
403forbidden, spending_pausedThe request was not over HTTPS, or spending on the account is paused. Contact support if paused.
404not_foundNo such check on this account, or the preview has expired.
409idempotency_conflict, quote_expired, quote_changed, settings_changedThe key was already used with different inputs, or the quote is expired, used or no longer matches. Get a new quote. For settings_changed, retry.
413payload_too_largeThe file is over 25 MiB.
422invalid_inputUnsupported or damaged file, bad dimensions, or an unknown field. Retrying will not help.
429rate_limited, active_limitToo many requests, or two checks already in progress. Wait for the number of seconds in the Retry-After header.
503unavailableTemporary problem. Retry with backoff, keeping the same Idempotency-Key.

Idempotency and retries

The Idempotency-Key header makes submitting safe to retry. If a request times out, you cannot tell whether the check was accepted. Send the same request again with the same key:

  • Same key, same inputs: you get the original check back, even if it has already finished. You are never charged twice.
  • Same key, different inputs: 409 idempotency_conflict.
  • New key: a new check and a new charge.

Generate the key before the first attempt and store it with your order, for example order-18422-front or a UUID. Retry only on network errors, 429 and 503, with a growing delay and a limit on attempts. Do not retry 4xx errors other than 429.

Limits

Per account
LimitValue
File size25 MiB
PDF pages20
Image size40 million pixels
Quotes and submissions30 per 60 seconds, counted together
Reads (retrieve, list, preview)600 per 60 seconds
Checks in progress2 at a time
Unused quotes10, each kept for 30 minutes

Over a limit you get 429 with a Retry-After header in seconds. Rejected requests count toward the rate limits.

Credits

  • One credit per image, one per PDF page. The quote tells you the exact number.
  • Reserved on submit, charged on completion. A completed check is charged whatever its readiness. If a check fails, the reservation is released.
  • Separate from creative credits. API credits are bought in packs from the dashboard and are not shared with an Image Presto subscription.
  • Subscriber discount. Paid Hobby, Freelancer and Pro subscribers get 1%, 3% and 5% off packs. The price per check does not change.
  • Free calls. Quotes, retrieving, listing, previews and the OpenAPI schema use no credits.

Data retention

How long data is kept
DataKept for
Uploaded file and previews24 hours from submission
Report90 days from completion
Unused quote upload30 minutes
Check history (status, size, credits)Kept after the report expires

These periods cannot be extended. Save the report in your own system if you need it for longer. Analysis runs on Image Presto servers; files are not sent to an external AI provider.

Example clients

Complete command-line clients with bounded retries, backoff and polling. Python and Node.js run on their own with no packages to install; the cURL runner needs submit.py beside it. They upload the file directly, so each new run uses credits.

Usage
export ARTWORK_API_KEY='ip_art_your_key_here'
export ARTWORK_API_BASE_URL='https://api.imagepresto.com'
export ARTWORK_IDEMPOTENCY_KEY='order-18422-front'

python3 submit.py /absolute/path/artwork.png 10 5 in

Download submit.py

View submit.py source
#!/usr/bin/env python3
"""Python 3.10+ stdlib example. POST spends API credits; GET polling does not.
Persist ARTWORK_IDEMPOTENCY_KEY with the original bytes/dimensions before running.
Direct admission remains chargeable. For confirmed PDF totals use POST /quote
and paired confirmation headers from quickstart.md; the dashboard does this.
Run: python3 submit.py /local/artwork.png 254 127 mm
Optional --curl uses curl transport with this same bounded retry policy.
"""
import email.utils
import http.client
import json
import math
import os
from pathlib import Path
import re
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid


class Stop(Exception):
    pass


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None


def main():
    args = sys.argv[1:]
    use_curl = bool(args and args[0] == '--curl')
    if use_curl:
        args.pop(0)
    if len(args) != 4:
        raise Stop('Usage: submit.py [--curl] LOCAL_FILE WIDTH HEIGHT in|mm')
    file, width, height, unit = args
    key = os.environ.get('ARTWORK_API_KEY', '')
    idem = os.environ.get('ARTWORK_IDEMPOTENCY_KEY', '')
    base = os.environ.get('ARTWORK_API_BASE_URL', '').rstrip('/')
    parsed = urllib.parse.urlsplit(base)
    if not key or not re.fullmatch(r'[!-~]{1,200}', idem) or not re.fullmatch(r'[!-~]+', key):
        raise Stop('Set API key and a persisted owner-generated idempotency key in the environment.')
    if parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path or not parsed.hostname:
        raise Stop('Base URL must be an HTTPS origin, without credentials, path or query.')
    if parsed.scheme != 'https' and not (parsed.scheme == 'http' and parsed.hostname in ('127.0.0.1', 'localhost', '::1')):
        raise Stop('HTTPS required; HTTP allowed only for a local test fixture.')
    if unit not in ('in', 'mm') or not all(math.isfinite(float(v)) and float(v) > 0 for v in (width, height)):
        raise Stop('Use finite positive physical dimensions and in or mm.')
    raw = Path(file).read_bytes()
    if not 0 < len(raw) <= 25 * 1024 * 1024:
        raise Stop('File must be nonempty and at most 25 MiB.')
    boundary = 'artwork-' + uuid.uuid4().hex
    body = b''
    for name, value in (('width', width), ('height', height), ('unit', unit)):
        body += f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode()
    body += f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="artwork"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode() + raw + f'\r\n--{boundary}--\r\n'.encode()
    deadline = time.monotonic() + 180
    opener = urllib.request.build_opener(NoRedirect)

    def pause(seconds):
        if not math.isfinite(seconds) or seconds < 0 or time.monotonic() + seconds >= deadline:
            raise Stop('Retry budget exhausted. Preserve the original idempotency key and inputs; check dashboard before retrying.')
        time.sleep(seconds)

    def request(method, route):
        if not re.fullmatch(r'/api/v1/artwork-checks(?:/[0-9a-fA-F-]{36})?', route):
            raise Stop('Unexpected report route; refusing to forward credentials.')
        for attempt in range(5):
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                raise Stop('Time budget exhausted; preserve original key and inputs.')
            headers = {'Authorization': 'Bearer ' + key, 'Accept': 'application/json'}
            if method == 'POST':
                headers.update({'Idempotency-Key': idem, 'Content-Type': 'multipart/form-data; boundary=' + boundary})
            status, response_headers, data = 0, {}, b''
            try:
                if use_curl:
                    # Secrets go over stdin, not argv; private temp files are cleaned.
                    with tempfile.TemporaryDirectory() as folder:
                        payload, head = Path(folder) / 'payload', Path(folder) / 'headers'
                        payload.write_bytes(body)
                        cmd = ['curl', '--silent', '--max-time', str(min(20, remaining)), '--request', method,
                               '--header', '@-', '--dump-header', str(head), '--write-out', '\n%{http_code}', base + route]
                        if method == 'POST':
                            cmd += ['--data-binary', '@' + str(payload)]
                        result = subprocess.run(cmd, input=''.join(f'{k}: {v}\n' for k, v in headers.items()).encode(), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=min(21, remaining + 1))
                        if result.returncode:
                            raise OSError()
                        data, code = result.stdout.rsplit(b'\n', 1)
                        status = int(code)
                        # read_text normalizes CRLF/LF. Skip interim/proxy blocks
                        # and trailers: only a matching final status starts headers.
                        for block in head.read_text().split('\n\n'):
                            status_line, _, fields = block.partition('\n')
                            if re.fullmatch(rf'HTTP/\S+ {status}(?: .*)?', status_line):
                                response_headers = email.message_from_string(fields)
                else:
                    req = urllib.request.Request(base + route, data=body if method == 'POST' else None, headers=headers, method=method)
                    try:
                        response = opener.open(req, timeout=min(20, remaining))
                    except urllib.error.HTTPError as error:
                        response = error
                    with response:
                        status, response_headers, data = int(response.status or 0), response.headers, response.read(2 * 1024 * 1024)
            except (OSError, http.client.HTTPException, subprocess.SubprocessError):
                pass  # Ambiguous response loss: retry ONLY identical POST/key or this GET.
            if 200 <= status < 300:
                try:
                    return json.loads(data)
                except (ValueError, UnicodeError):
                    status = 0  # Incomplete success body: ambiguous, same-key retry.
            if status not in (0, 429, 503):
                # No raw error text, credentials, signed media URLs or upload data in logs.
                request_id = ''
                try:
                    candidate = json.loads(data).get('request_id', '')
                    request_id = str(uuid.UUID(candidate))
                except (ValueError, TypeError, AttributeError):
                    pass
                raise Stop(f'HTTP {status}; stop and resolve before retrying. Request ID: {request_id}')
            if attempt == 4:
                raise Stop('Retry attempts exhausted. Keep original key/inputs; inspect dashboard. No automatic purchase or new submission.')
            wait = min(2 ** attempt, 8)
            retry_after = response_headers.get('Retry-After')
            if retry_after:
                try:
                    wait = max(wait, float(retry_after))
                except ValueError:
                    wait = max(wait, email.utils.parsedate_to_datetime(retry_after).timestamp() - time.time())
            pause(wait)
        raise Stop('Retry budget exhausted.')

    accepted = request('POST', '/api/v1/artwork-checks')
    job_id = str(uuid.UUID(accepted['id']))
    print('Check:', job_id)
    route = '/api/v1/artwork-checks/' + job_id
    for poll in range(12):
        detail = request('GET', route)
        status = detail.get('processing_status')
        if status == 'completed':
            readiness = (detail.get('report') or {}).get('readiness')
            print('completed', readiness if readiness in ('no_flags', 'issues_found', 'inconclusive') else 'report unavailable')
            return
        if status == 'failed':
            raise Stop('Check failed; stop polling. Inspect dashboard reservation status; do not resubmit automatically.')
        if status not in ('queued', 'running'):
            raise Stop('Unexpected status; inspect dashboard without creating another check.')
        if poll < 11:
            pause(min(2 ** poll, 8))
    raise Stop('Polling budget exhausted. Resume GET for this check; never create a new key to poll.')


if __name__ == '__main__':
    try:
        main()
    except Stop as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
    except Exception:
        print('Example stopped safely. Preserve key and original inputs; check dashboard. No raw errors logged.', file=sys.stderr)
        sys.exit(1)

Download submit.cjs

View submit.cjs source
#!/usr/bin/env node
// Node 22+; no packages. POST spends API credits; GET polling does not.
// Persist ARTWORK_IDEMPOTENCY_KEY and original inputs BEFORE invoking this example.
// Direct admission is backwards compatible and chargeable. For confirmed PDF totals,
// use POST /quote plus both confirmation headers as documented in quickstart.md.
// node submit.cjs /local/artwork.png 254 127 mm
const fs = require("node:fs");
const { setTimeout: sleep } = require("node:timers/promises");
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
async function main() {
  const [file, width, height, unit, extra] = process.argv.slice(2);
  const key = process.env.ARTWORK_API_KEY || "";
  const idem = process.env.ARTWORK_IDEMPOTENCY_KEY || "";
  const base = new URL(process.env.ARTWORK_API_BASE_URL);
  if (!/^[!-~]+$/.test(key) || !/^[!-~]{1,200}$/.test(idem))
    throw Error(
      "Set API key and persisted owner-generated idempotency key in the environment.",
    );
  if (
    base.username ||
    base.password ||
    base.search ||
    base.hash ||
    base.pathname !== "/" ||
    (base.protocol !== "https:" &&
      !(
        base.protocol === "http:" &&
        ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname)
      ))
  )
    throw Error(
      "HTTPS origin required; HTTP only for loopback test fixtures. No credentials, query or path.",
    );
  if (
    !file ||
    extra ||
    !["in", "mm"].includes(unit) ||
    ![width, height].every((v) => Number.isFinite(Number(v)) && Number(v) > 0)
  )
    throw Error("Usage: node submit.cjs LOCAL_FILE WIDTH HEIGHT in|mm");
  const raw = fs.readFileSync(file);
  if (!raw.length || raw.length > 25 * 1024 * 1024)
    throw Error("File must be nonempty and at most 25 MiB.");
  const deadline = Date.now() + 180000;
  async function pause(seconds) {
    if (
      !Number.isFinite(seconds) ||
      seconds < 0 ||
      Date.now() + seconds * 1000 >= deadline
    )
      throw Error(
        "Retry budget exhausted; preserve original key/inputs and inspect dashboard.",
      );
    await sleep(seconds * 1000);
  }
  async function request(method, route) {
    if (!/^\/api\/v1\/artwork-checks(?:\/[0-9a-f-]{36})?$/i.test(route))
      throw Error("Unexpected route; refusing to forward credentials.");
    for (let attempt = 0; attempt < 5; attempt++) {
      const remaining = deadline - Date.now();
      if (remaining <= 0)
        throw Error("Time budget exhausted; preserve original key and inputs.");
      const headers = {
        Authorization: "Bearer " + key,
        Accept: "application/json",
      };
      let body;
      if (method === "POST") {
        headers["Idempotency-Key"] = idem;
        body = new FormData();
        body.set("file", new Blob([raw]), "artwork");
        body.set("width", width);
        body.set("height", height);
        body.set("unit", unit);
      }
      let response;
      try {
        response = await fetch(new URL(route, base), {
          method,
          headers,
          body,
          redirect: "manual",
          signal: AbortSignal.timeout(Math.min(20000, remaining)),
        });
      } catch {
        /* Ambiguous failure: same original bytes/options/key, never a new charge key. */
      }
      if (response?.ok) {
        try {
          return await response.json();
        } catch {
          /* Response body loss is ambiguous too. */
        }
      } else if (response && ![429, 503].includes(response.status)) {
        let requestId = "";
        try {
          const data = await response.json();
          if (UUID.test(data.request_id)) requestId = data.request_id;
        } catch {}
        throw Error(
          `HTTP ${response.status}; stop and resolve before retrying. Request ID: ${requestId}`,
        );
      }
      if (attempt === 4)
        throw Error(
          "Retry attempts exhausted. Keep original key/inputs; inspect dashboard. No automatic purchase or new submission.",
        );
      let wait = Math.min(2 ** attempt, 8);
      const retryAfter = response?.headers.get("Retry-After");
      if (retryAfter) {
        const seconds = /^\d+(?:\.\d+)?$/.test(retryAfter)
          ? Number(retryAfter)
          : (Date.parse(retryAfter) - Date.now()) / 1000;
        if (!Number.isFinite(seconds))
          throw Error(
            "Invalid Retry-After; stop safely and inspect dashboard.",
          );
        wait = Math.max(wait, seconds);
      }
      await pause(wait);
    }
  }
  const accepted = await request("POST", "/api/v1/artwork-checks");
  if (!UUID.test(accepted.id))
    throw Error(
      "Unexpected check ID; inspect dashboard without creating another check.",
    );
  console.log("Check:", accepted.id);
  const route = "/api/v1/artwork-checks/" + accepted.id;
  for (let poll = 0; poll < 12; poll++) {
    const detail = await request("GET", route);
    if (detail.processing_status === "completed") {
      const readiness = detail.report?.readiness;
      console.log(
        "completed",
        ["no_flags", "issues_found", "inconclusive"].includes(readiness)
          ? readiness
          : "report unavailable",
      );
      return;
    }
    if (detail.processing_status === "failed")
      throw Error(
        "Check failed; stop polling. Inspect dashboard reservation status; do not resubmit automatically.",
      );
    if (!["queued", "running"].includes(detail.processing_status))
      throw Error(
        "Unexpected status; inspect dashboard without creating another check.",
      );
    if (poll < 11) await pause(Math.min(2 ** poll, 8));
  }
  throw Error(
    "Polling budget exhausted. Resume GET for this check; never create a new key to poll.",
  );
}
// Only controlled messages are emitted; never print raw provider/network exceptions.
main().catch((error) => {
  const safe =
    /^(Set API|HTTPS origin|Usage:|File must|Retry |Time budget|Unexpected |HTTP \d|Invalid Retry|Check failed|Polling budget)/.test(
      error.message,
    );
  console.error(
    safe
      ? error.message
      : "Example stopped safely. Preserve key and original inputs; check dashboard. No raw errors logged.",
  );
  process.exitCode = 1;
});

Download submit.sh

View submit.sh source
#!/usr/bin/env bash
# cURL + Python 3.10+ transport example. Download submit.py beside this file.
# bash submit.sh /local/artwork.png 254 127 mm
# Shares the tested bounded retry policy, multipart body and safe output with Python.
# The Python --curl transport executes curl --header @- --data-binary @PRIVATE_FILE:
# auth travels over stdin, never shell trace/argv; no --location or automatic retries.
# POST reserves/spends API credits. Persist the original idempotency key and inputs.
set -eu
exec python3 "$(dirname "$0")/submit.py" --curl "$@"

Support

Email info@imagepresto.com with the request_id or check ID. Never send API keys or artwork by email. Balance, purchases, keys and history are in the dashboard.