This post was drafted with AI assistance and reviewed by the PerfectVector team.
A script that calls a conversion API needs more than the happy path. It has to survive a dropped connection without converting twice, cope with error responses that aren't what you expected, and stop waiting at some point. Here is a single-image Python example that does all three, run against the PerfectVector Developer API with a test key. Test keys return a fixed sample SVG, so the run needed no credits.
import hashlib, os, sys, time import requests API = "https://api.perfectvector.com/v1" HEADERS = {"Authorization": f"Bearer {os.environ['PERFECTVECTOR_API_KEY']}"} class OutOfTime(Exception): pass def left(deadline): return deadline - time.monotonic() def pause(seconds, deadline): if seconds > left(deadline): raise OutOfTime("not enough time budget left to wait") time.sleep(seconds) def call(method, url, deadline, headers=None, **kw): if left(deadline) <= 0: raise OutOfTime("time budget used up") return requests.request(method, url, headers={**HEADERS, **(headers or {})}, timeout=min(130, left(deadline)), **kw) # the API may wait up to 120 s def describe(r): try: p = r.json() # API errors: application/problem+json return f"{r.status_code} {p['code']}: {p['detail']}" except Exception: # the network edge can answer with HTML return f"{r.status_code}, not an API error body" def convert(path, out, key=None, max_wait=300): data = open(path, "rb").read() # Derived from the file bytes: a retry of the same file reuses the conversion. # Pass key="..." for an intentional new conversion of the same bytes. key = key or "img-" + hashlib.sha256(data).hexdigest()[:32] deadline = time.monotonic() + max_wait try: for attempt in range(3): try: r = call("POST", f"{API}/vectorizations", deadline, headers={"Idempotency-Key": key, "Accept": "image/svg+xml"}, files={"image": (os.path.basename(path), data)}) except requests.RequestException as e: print("network error:", e) if attempt < 2: pause(2 ** attempt, deadline) continue if r.status_code == 201 and r.headers.get("Content-Type", "").startswith("image/svg+xml"): open(out, "wb").write(r.content) return f"saved {out} ({len(r.content)} bytes), charged={r.headers.get('X-Credits-Charged', '?')}, replayed={r.headers.get('Idempotent-Replayed', 'false')}" if r.status_code in (429, 503): if attempt < 2: wait = int(r.headers["Retry-After"]) if r.headers.get("Retry-After", "").isdigit() else 2 pause(wait, deadline) continue if r.status_code >= 400: return describe(r) v = r.json() # 201 or 202: a vectorization object while v["status"] in ("queued", "processing"): pause(2, deadline) g = call("GET", f"{API}/vectorizations/{v['id']}", deadline) if g.status_code >= 400: return describe(g) v = g.json() if v["status"] != "succeeded": return f"failed: {v['results'][0]['error']['code']} (not charged)" svg = call("GET", v["results"][0]["result"]["url"], deadline) if svg.status_code >= 400: return describe(svg) open(out, "wb").write(svg.content) return f"saved {out} ({len(svg.content)} bytes) from the result URL" return "gave up after 3 attempts" except OutOfTime as e: return f"{e}; the conversion may still finish, so look it up by Idempotency-Key later" except (KeyError, IndexError, TypeError, ValueError): return "unexpected API response shape; check the docs for this API version" except requests.RequestException as e: return f"network error: {e}" if __name__ == "__main__": print(convert(sys.argv[1], sys.argv[2])) What it does, and why each piece is there:
- The key comes from the file.
Idempotency-Keyis a hash of the image bytes, so a retry of the same file reuses the first conversion for as long as the API keeps the key (24 hours, per the docs). The flip side: converting the same bytes again on purpose inside that window returns the old conversion, so the function takes an explicitkey=for a deliberate redo. - One time budget.
max_waitbecomes a deadline. Every request checks it first and gets a timeout capped by what's left, and every wait (back-off,Retry-After, polling) is skipped, with a clear message, if it wouldn't fit. ARetry-Afterlonger than the budget ends the call instead of sleeping. If time runs out, the conversion may still finish on the server, so the message says to look it up by itsIdempotency-Keylater. Two limits to know:requests' timeout bounds each connect and read, not the total elapsed time of a slow response, so for a hard wall-clock limit run the call in a thread or process you can abandon; and an SVG body that arrives just after the deadline is still saved, while a late JSON success is not followed by a download request. The docs also warn thatrequestshas no default timeout and HTTPX's default is short, so set one for this endpoint either way. - Branching on status and
Content-Type.201withimage/svg+xmlis the file. Any other201or202carries a vectorization object, so the code reads itsstatusinstead of assuming: a201can be a finished conversion without the SVG attached, or a failed one (not charged).queuedandprocessingare polled every 2 seconds. - Errors without crashing. API errors come as
application/problem+jsonwith a stablecode;429and503are retried afterRetry-After. Responses from the network edge can be non-JSON (the docs say so for some403and429), sodescribe()falls back to the status code. The follow-up status and download calls get the same checks, and a response with an unexpected shape (missing fields, emptyresults, a non-JSON201) returns a clear message instead of a traceback.
What we ran (test key, 2026-11-13, Python 3.9, requests 2.32.5):
| Case | Result |
|---|---|
| A new 320×240 PNG, first call | saved 713 bytes, charged=0, replayed=false |
| The same file again | saved 713 bytes, charged=0, replayed=true |
| The same bytes with an explicit new key (a separate run) | saved 713 bytes, charged=0, replayed=false |
| A 64×64 PNG | 422 invalid_image: Each image dimension must be between 100 and 4096 pixels |
| A wrong key | 401 invalid_api_key |
The three saved files were byte-identical. The 713 bytes are the test-mode sample file, which is the same for every image, so this run checks the request flow, not trace quality. Test mode answers instantly and never returns 202, so we exercised the other branches with mocked responses and a fake clock (17 cases): three request timeouts, Retry-After: 3600, Retry-After: 2 three times and a date-format Retry-After, an HTML 403, a 202 that goes processing → succeeded → download, a conversion that never finishes (budgets of 20 s and 3 s), an HTTP 500 on the status call, a failed conversion, 201 bodies with missing fields, empty results, a null result and no JSON at all, and responses that arrive at 301 s against a 300 s budget. In 15 of the 17 the code stopped at or before the budget (300 of 300 s for three timeouts, 20 of 20 s, 2 of 3 s). In the two where the response itself landed at 301 s, the late JSON success ended with a "time budget used up" message and no download request, and the late SVG body was saved. Every unusual response ended with a message instead of a traceback.
One limit to plan around: by default an account runs one live conversion at a time, across all its keys. A second request is refused rather than queued, normally with 429 too_many_in_flight, or with 402 insufficient_credits when the available balance covers only the running conversion. Run a batch one image after another instead of in parallel. We haven't run live conversions for this post.
Docs: Quickstart.
We build PerfectVector, an image-to-vector tool.



