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.
- Create an API key. The full key is shown once. Store it as
ARTWORK_API_KEYon your server. - Get a quote. Upload the file with its print size. You get back the credit cost and a
quote_id. Nothing is charged. - Submit the quote. This reserves the credits and queues the check.
- 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"import os
import time
import uuid
import requests # pip install requests
BASE = "https://api.imagepresto.com/api/v1/artwork-checks"
HEADERS = {"Authorization": f"Bearer {os.environ['ARTWORK_API_KEY']}"}
# 1. Quote: upload once and see the cost. Nothing is charged.
with open("artwork.png", "rb") as artwork:
response = requests.post(
f"{BASE}/quote",
headers=HEADERS,
files={"file": artwork},
data={"width": "10", "height": "5", "unit": "in"},
timeout=60,
)
response.raise_for_status()
quote = response.json()
print(f"{quote['page_count']} page(s) = {quote['credits']} credit(s)")
# 2. Submit the quote. This reserves the credits.
# Save the key first: retrying with the same key never charges twice.
idempotency_key = str(uuid.uuid4())
response = requests.post(
BASE,
headers={**HEADERS, "Idempotency-Key": idempotency_key},
json={"quote_id": quote["quote_id"]},
timeout=60,
)
response.raise_for_status()
check_id = response.json()["id"]
# 3. Poll until the check finishes.
for _ in range(60):
check = requests.get(f"{BASE}/{check_id}", headers=HEADERS, timeout=30).json()
if check["processing_status"] in ("completed", "failed"):
break
time.sleep(3)
if check["processing_status"] == "completed":
report = check["report"]
print(report["readiness"])
for finding in report["findings"]:
print(finding["severity"], finding["code"], "-", finding["message"])
else:
print("Check did not complete:", check.get("error_code"))// Node.js 22+ (built-in fetch and FormData). Save as check.mjs
import { randomUUID } from "node:crypto";
import { openAsBlob } from "node:fs";
const BASE = "https://api.imagepresto.com/api/v1/artwork-checks";
const headers = { Authorization: `Bearer ${process.env.ARTWORK_API_KEY}` };
async function call(url, init) {
const response = await fetch(url, init);
const body = await response.json();
if (!response.ok) {
throw new Error(`${response.status} ${body.error?.code} (request ${body.request_id})`);
}
return body;
}
// 1. Quote: upload once and see the cost. Nothing is charged.
const form = new FormData();
form.set("file", await openAsBlob("artwork.png"), "artwork.png");
form.set("width", "10");
form.set("height", "5");
form.set("unit", "in");
const quote = await call(`${BASE}/quote`, { method: "POST", headers, body: form });
console.log(`${quote.page_count} page(s) = ${quote.credits} credit(s)`);
// 2. Submit the quote. This reserves the credits.
// Save the key first: retrying with the same key never charges twice.
const idempotencyKey = randomUUID();
const accepted = await call(BASE, {
method: "POST",
headers: {
...headers,
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify({ quote_id: quote.quote_id }),
});
// 3. Poll until the check finishes.
let check;
for (let attempt = 0; attempt < 60; attempt++) {
check = await call(`${BASE}/${accepted.id}`, { headers });
if (["completed", "failed"].includes(check.processing_status)) break;
await new Promise((resolve) => setTimeout(resolve, 3000));
}
if (check.processing_status === "completed") {
console.log(check.report.readiness);
for (const finding of check.report.findings) {
console.log(finding.severity, finding.code, "-", finding.message);
}
} else {
console.log("Check did not complete:", check.error_code);
}Authentication
Send your API key in the Authorization header on every request, over HTTPS:
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.
| Name | Type | Description |
|---|---|---|
filerequired | file | PNG, JPEG or PDF. Up to 25 MiB. The type is detected from the file contents, not the filename. |
widthrequired | number | Intended print width. Must be greater than 0. |
heightrequired | number | Intended print height. Must be greater than 0. |
unitrequired | string | in or mm. |
garment_color | string | Optional #RRGGBB color. Stored with the check; it does not change the measurements. |
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"{
"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"
}| Name | Type | Description |
|---|---|---|
page_count | integer | 1 for an image; the number of pages for a PDF. |
credits | integer | Credits the check will reserve. |
quote_id | UUID | Pass this to Submit a check. Single use. |
quote_expires_at | timestamp | When the stored upload is discarded. |
input_hash | string | Fingerprint of the file and options. Only needed if you re-upload the file instead of using quote_id. |
tariff_version | integer | Pricing 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.
| Name | Type | Description |
|---|---|---|
Idempotency-Keyrequired | string | Your unique ID for this check: 1–200 visible ASCII characters, no spaces. See Idempotency and retries. |
X-Artwork-Input-Hash | string | Optional. The quote's input_hash. Send it together with X-Artwork-Expected-Credits. |
X-Artwork-Expected-Credits | integer | Optional. 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.
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.
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"{
"id": "3d5c9a2e-7f41-4b8a-9c1d-5e6f7a8b9c0d",
"processing_status": "queued",
"reserved_credits": 1,
"report_url": "/api/v1/artwork-checks/3d5c9a2e-7f41-4b8a-9c1d-5e6f7a8b9c0d"
}| Name | Type | Description |
|---|---|---|
id | UUID | The check ID. Store it; you need it to fetch the report. |
processing_status | string | queued, running, completed or failed. |
reserved_credits | integer | Credits reserved for this check. |
report_url | string | Path 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.
curl https://api.imagepresto.com/api/v1/artwork-checks/3d5c9a2e-7f41-4b8a-9c1d-5e6f7a8b9c0d \
-H "Authorization: Bearer $ARTWORK_API_KEY"{
"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 }
]
}| Name | Type | Description |
|---|---|---|
processing_status | string | queued, running, completed or failed. |
readiness | string | null | no_flags, issues_found or inconclusive. Null until completed. |
report | object | null | The full report. See Reading the report. Null before completion and after the report expires. |
previews | array | Preview images with their page number and background. Empty once previews expire. |
reservation_status | string | reserved while running, settled when charged, released when returned. |
error_code | string | null | Why a check failed, for example analysis_timeout or invalid_or_expired_media. |
media_expires_at | timestamp | When the upload and previews are deleted. |
report_expires_at | timestamp | null | When the report is deleted. |
List checks
GET/api/v1/artwork-checks
Returns your account's checks, newest first.
| Name | Type | Description |
|---|---|---|
limit | integer | 1–100. Default 20. |
cursor | string | The next_cursor from the previous page. Keep the same filters between pages. |
status | string | queued, running, completed or failed. |
key_id | UUID | Only checks submitted with this API key. |
created_after | timestamp | ISO 8601 with a time zone, for example 2026-11-18T00:00:00Z. |
created_before | timestamp | ISO 8601 with a time zone. |
curl "https://api.imagepresto.com/api/v1/artwork-checks?status=completed&limit=20" \
-H "Authorization: Bearer $ARTWORK_API_KEY"{
"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.
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.pngPreviews 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.
| Value | Meaning |
|---|---|
no_flags | Nothing crossed a warning or error threshold at the requested size. |
issues_found | At least one warning or error, such as low resolution or mismatched proportions. |
inconclusive | Measured, but the result depends on something the API cannot judge, such as partial transparency. Still a completed, charged check. |
| Code | Severity | Meaning |
|---|---|---|
below_minimum_dpi | error | Effective DPI at the requested size is under your minimum. |
below_target_dpi | warning | Effective DPI is above your minimum but under your target. |
aspect_mismatch | warning | The artwork's proportions differ from the requested area by more than your tolerance. |
partial_alpha | warning | Some pixels are semi-transparent. |
transparent_margins | info | The visible artwork is smaller than the canvas. |
empty_artwork | error | The image has no visible pixels. |
pdf_measurement_limitations | warning | Part 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.
evidenceholds the measured numbers,messageis a sentence you can show a customer, andlimitationssays 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 itsrule_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": {
"code": "insufficient_credits",
"message": "Insufficient artwork credits"
},
"request_id": "11111111-1111-4111-8111-111111111111"
}| Status | Code | What to do |
|---|---|---|
| 400 | invalid_request | Malformed request, or a credential in the URL. Fix the request. |
| 401 | unauthorized, invalid_key | Missing, revoked or expired key. Check the header and the key. |
| 402 | insufficient_credits | Not enough credits. Buy more, then retry with the same key and inputs. |
| 403 | forbidden, spending_paused | The request was not over HTTPS, or spending on the account is paused. Contact support if paused. |
| 404 | not_found | No such check on this account, or the preview has expired. |
| 409 | idempotency_conflict, quote_expired, quote_changed, settings_changed | The 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. |
| 413 | payload_too_large | The file is over 25 MiB. |
| 422 | invalid_input | Unsupported or damaged file, bad dimensions, or an unknown field. Retrying will not help. |
| 429 | rate_limited, active_limit | Too many requests, or two checks already in progress. Wait for the number of seconds in the Retry-After header. |
| 503 | unavailable | Temporary 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
| Limit | Value |
|---|---|
| File size | 25 MiB |
| PDF pages | 20 |
| Image size | 40 million pixels |
| Quotes and submissions | 30 per 60 seconds, counted together |
| Reads (retrieve, list, preview) | 600 per 60 seconds |
| Checks in progress | 2 at a time |
| Unused quotes | 10, 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
| Data | Kept for |
|---|---|
| Uploaded file and previews | 24 hours from submission |
| Report | 90 days from completion |
| Unused quote upload | 30 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.
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 inView 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)
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;
});
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.