Sign up free
All articles

Engineering·8 min read

PNG to SVG API: Node.js and Python upload examples

Upload a PNG or JPG from Node.js or Python, save the SVG from JSON and handle retries safely. Includes idempotency, storage and timeout pitfalls.

Two open paper envelopes, a mint artwork card and a loose cord on a dark tabletop.
Editorial artwork: a conversion workflow needs a clear handoff and a checked result.
In this article

To convert a PNG or JPG through the Vectali API, send one file in the multipart field image, authenticate from your server and save the response’s svg string. The response is JSON, rather than a raw SVG download.

Decide how you retain the identity of a conversion before your first request. A timeout does not prove that the server stopped working. A retry with the same idempotency key and image bytes can recover a completed result without spending another allowance, provided its stored input and output remain available. Keep your own saved result once the job succeeds.

This tutorial provides complete Node.js and Python command-line examples, then explains the job record and error cases you need in an application. The examples follow the current endpoint contract and keep a failed attempt attached to its original job, so a network error does not become an unrelated second upload.

Set up the server-side request

For supported formats, allowances and the overall integration contract, start with the image-to-SVG API overview. This tutorial works through the Node.js and Python requests, job identity and failure handling.

Create an API key in the dashboard and configure it as VECTALI_API_KEY in your server environment. Keep it out of browser bundles, public environment variables, repositories and request logs.

Server conversions need available API allowance from an active API plan or administrator-granted API credits. Plans start at $19/month for 500 successful conversions. Web export credits and Web Pro’s browser exports are separate products; a browser allowance does not authorize a server conversion.

Use the versioned endpoint https://api.vectali.com/api/v1/vectorize. Send exactly one PNG or JPEG file as image, with Authorization: Bearer … and a stable Idempotency-Key. Let your HTTP client set the multipart content type and boundary.

Before writing code, choose where your application stores the input and request ID. A database job record or another durable server record is appropriate when a request may outlive the process handling it. An ID generated inside every retry attempt defeats the replay protection.

Check the API’s image limits

The server API accepts up to 10 MiB of image bytes, at most 4,000,000 pixels in total and no side longer than 4,096 pixels. A 2,000 × 2,000 image reaches the area limit. A different aspect ratio fits only when both area and side-length rules are satisfied.

The browser converter accepts the same file sizes and dimensions. Check the file-limits reference when preparing uploads. Send the original unchanged when it fits so the engine can use its full detail.

The example programs check the file’s byte length locally. They rely on the server to validate actual format bytes and image dimensions. In an application, add appropriate image validation before submission for faster feedback, while continuing to handle server-side rejection.

Do not fix an unsupported input by changing its extension. Export real PNG or JPEG bytes from the source application. If you resize a logo to fit, inspect small letter openings and thin strokes before treating the prepared image as equivalent.

Node.js: upload the file and save only the SVG

This example uses Node’s built-in Fetch, FormData and Blob APIs with filesystem functions. Use a supported Node release providing those globals; Node’s documentation describes the implementations.

Save the program as convert.mjs. Pass the input path, output path and a request ID you have generated once and retained for this job. Keep that third argument unchanged if you deliberately retry the same conversion.

import { readFile, writeFile } from "node:fs/promises";
import { basename, extname, resolve } from "node:path";

const [inputPath, outputPath, requestId] = process.argv.slice(2);
const apiKey = process.env.VECTALI_API_KEY;
if (!apiKey || !inputPath || !outputPath || !requestId) {
  throw new Error("Set VECTALI_API_KEY; pass input, output, and a saved job ID.");
}
if (resolve(inputPath) === resolve(outputPath)) {
  throw new Error("Keep the original input separate from the SVG output.");
}
if (!/^[A-Za-z0-9._:-]{8,128}$/.test(requestId)) {
  throw new Error("Use an 8–128 character request ID with letters, digits, . _ : -");
}
const extension = extname(inputPath).toLowerCase();
if (![".png", ".jpg", ".jpeg"].includes(extension)) {
  throw new Error("Choose a real PNG or JPEG file.");
}
const bytes = await readFile(inputPath);
if (bytes.length > 10 * 1024 * 1024) {
  throw new Error("The image exceeds 10 MiB.");
}
const type = extension === ".png" ? "image/png" : "image/jpeg";
const body = new FormData();
body.append("image", new Blob([bytes], { type }), basename(inputPath));

const response = await fetch("https://api.vectali.com/api/v1/vectorize", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${apiKey}`,
    "Idempotency-Key": requestId,
  },
  body,
  signal: AbortSignal.timeout(240_000),
});
const result = await response.json().catch(() => null);
if (!response.ok) {
  const code = typeof result?.code === "string" ? result.code : "non_json_error";
  throw new Error(`Conversion failed: HTTP ${response.status}, ${code}`);
}
if (typeof result?.svg !== "string" || !result.svg.length) {
  throw new Error("The response did not include an SVG document.");
}
await writeFile(outputPath, result.svg, "utf8");
console.log("Saved conversion", result.conversion_id);

For example, a retained application job ID could be supplied as node convert.mjs logo.png logo.svg logo-job-20261018-001. Choose a new ID for a genuinely new conversion, rather than reusing this illustrative value across unrelated images.

The 240-second timeout is an application choice, not a service-time promise. If it fires, preserve the same input bytes and job ID. A later attempt can recover a completed conversion, or report that the original attempt remains in progress.

Python: the same contract with Requests

Install requests in your application’s environment. Its multipart upload documentation shows how the file tuple provides a filename, binary file and media type.

Save this example as convert.py and pass the same three arguments as the Node program. The file is opened in binary mode, and the context manager closes it after the request finishes.

from pathlib import Path
import os
import re
import sys
import requests

if len(sys.argv) != 4 or not os.environ.get("VECTALI_API_KEY"):
    raise SystemExit("Set VECTALI_API_KEY; pass input, output, and a saved job ID.")
source, destination, request_id = sys.argv[1:]
if Path(source).resolve() == Path(destination).resolve():
    raise SystemExit("Keep input and output paths separate.")
if not re.fullmatch(r"[A-Za-z0-9._:-]{8,128}", request_id):
    raise SystemExit("Use a valid 8–128 character job ID.")
extension = Path(source).suffix.lower()
if extension not in {".png", ".jpg", ".jpeg"}:
    raise SystemExit("Choose a real PNG or JPEG file.")
if Path(source).stat().st_size > 10 * 1024 * 1024:
    raise SystemExit("The image exceeds 10 MiB.")
media_type = "image/png" if extension == ".png" else "image/jpeg"
with open(source, "rb") as image:
    response = requests.post(
        "https://api.vectali.com/api/v1/vectorize",
        headers={
            "Authorization": f"Bearer {os.environ['VECTALI_API_KEY']}",
            "Idempotency-Key": request_id,
        },
        files={"image": (Path(source).name, image, media_type)},
        timeout=(10, 240),
    )
try:
    result = response.json()
except ValueError:
    result = None
if not response.ok:
    code = result.get("code", "unknown") if isinstance(result, dict) else "non_json_error"
    raise SystemExit(f"Conversion failed: HTTP {response.status_code}, {code}")
if not isinstance(result, dict) or not isinstance(result.get("svg"), str) or not result["svg"]:
    raise SystemExit("The response did not include an SVG document.")
Path(destination).write_text(result["svg"], encoding="utf-8")
print("Saved conversion", result.get("conversion_id"))

As with the Node example, the filename extension selects a media-type hint; the server remains responsible for validating the actual bytes. The examples do not silently resize, remove backgrounds or change the logo to make it fit.

The two timeout settings do different jobs

The Python example’s timeout=(10, 240) sets connection and read timeouts. The read timeout limits how long the connection can go without receiving data; it is not a 240-second deadline for the entire job. Requests documents that distinction. Node’s abort signal limits the example’s fetch operation, but neither client timeout cancels a conversion already running on the service.

In a worker or queue, keep a separate job deadline and maximum attempt count. After a timeout, record an uncertain state and schedule one bounded retry with the original bytes and key. Do not launch several retries in parallel or silently give the next attempt a new ID.

Allow room for the output document

The endpoint limits the returned SVG document to 8 MiB before JSON encoding. Your application’s response limit needs to account for its JSON envelope and any escaping, rather than assuming that the original image’s compressed size predicts the response length.

Save the SVG string as UTF-8 and keep the conversion metadata in your job record. Writing the complete JSON into a file named logo.svg produces a mislabeled JSON document, even when the conversion itself succeeded. Test that distinction with an actual output assertion in your client tests.

Retain a job, rather than just a request

Store the input reference, idempotency key, job status and eventual conversion_id together. If your worker restarts, it should be able to rebuild the multipart request from the same bytes and the same key.

For an asynchronous application, write that job record before dispatching the conversion. Update it when a valid result arrives. A browser can then ask your server about its job instead of submitting another conversion because a page refreshed.

An application timeout creates uncertainty about completion. It does not authorize assuming that the allowance was unused. While the stored input and output remain available, a completed replay with the same key returns the original conversion and SVG without spending another allowance.

Do not reuse a completed key with different image bytes. That produces an idempotency conflict. A deliberate new conversion needs a new job ID; a retry of the old conversion needs the old ID and original input.

Classify the failure before retrying

Response Useful action
400 or 415 Correct the multipart field, key format or input format
401 Repair the server’s API-key configuration
402 Check API plan status or remaining server allowance
409 conversion_in_progress Wait, then retry the same job
409 idempotency_conflict Recover the original bytes or create a deliberate new job
409 result_unavailable Recover your saved output if you have it; a new conversion needs a deliberate new job
413 or 422 Correct byte size, dimensions or damaged input
429 Honor Retry-After and preserve the job identity
Network failure or retriable service error Back off and retry the same job within an explicit bound

Use the HTTP status and machine-readable code, rather than matching the exact human error sentence. An infrastructure error can return HTML or another non-JSON body, which is why both examples tolerate JSON parsing failure.

A bounded retry should stop when the application no longer needs the result, an input/configuration error requires correction or its attempt budget is exhausted. Do not create parallel retries for one in-progress conversion.

The error reference distinguishes specific service and result-availability cases. Keep request identifiers for support, but redact authorization headers, source images and full SVG payloads from routine logs.

Keep retry identity attached to the exact input

A filename is not a reliable identity for uploaded bytes. Someone can replace logo.png with a new version while a delayed worker still holds the old job. Persist a stable input reference or content hash with the idempotency key so a retry cannot silently pick up another file from the same path.

Keep the stored upload available until the job reaches a state your application can resolve. If your output write fails after a successful conversion, the conversion may already be complete. Recover the same job and save its replayed SVG rather than issuing an unrelated new request to compensate for a local filesystem problem.

Also store the returned conversion identifier with the result. That gives your application a stable way to refer to the successful conversion without retaining request headers in routine logs. Treat the source and output according to your application’s own access and retention requirements.

Account for server storage and deletion

This API is server-side. A successful conversion stores the source and SVG in the account’s private conversion history; it does not have the landing preview’s local-only behavior. Review the privacy policy and your own application’s retention needs before sending customer artwork.

Idempotent replay depends on the stored input and output. If either is no longer available, the API can return 409 result_unavailable. Do not treat the idempotency key as permanent output storage. Save a successful SVG and its conversion metadata in your own authorized result store, and coordinate deletion with any jobs that might still retry.

A new key after a missing-result error starts a new conversion and may consume allowance. Make that an explicit application decision, rather than a hidden fallback inside a generic retry handler.

Test the integration before using paid allowance

A local contract test can replace the HTTP client with a stub and exercise the behaviors around the conversion. It should check that exactly one image file is submitted, the same request ID is retained across a deliberate retry, and only the returned SVG string is written to the output file.

Include a success response, a JSON error and a non-JSON service error. Test a response that claims success but lacks the svg field. These cases catch integration mistakes without sending an image to the live service or requiring a paid conversion.

Mocked responses verify client behavior. They do not measure hosted engine availability or conversion quality. When you are ready for an end-to-end check, use the account and input planned for your application, and keep that result separate from the unit-test results.

Return a useful result to your browser

Your application server can store the SVG privately or return it to an authenticated client. Keep the secret Vectali API key on the server. Direct requests from arbitrary browser origins are not an alternative to a server integration.

For a preview, reference an SVG Blob URL from an image element rather than inserting returned markup into innerHTML. Revoke the previous object URL when replacing or removing the preview. The code examples reference contains a small implementation.

Preserve the selected input after a recoverable error, show a useful status and make retry an explicit action associated with the existing job. If the user selects another file, keep the new job distinct so an old response cannot replace its preview.

Finally, inspect conversion quality at the intended display size. A successful HTTP response establishes that the endpoint returned a result; it does not approve every curve, background or small letter. Use the logo review checklist before treating the SVG as a final design asset.