Decode Pipeline & Symbol Types

GET /v1/qr/decode and GET /v1/barcode/decode are the same handler behind two routes: both call decode_from_url() and both return every symbol found in the image, QR and 1D alike. The qr prefix is a naming convention, not a filter.

This page documents the decode path at implementation level. For the request/response shape alongside bulk generation, see Bulk & Decode.

Base URL

https://barcode.toolkitapi.io

Routes

Method Route Notes
GET /v1/qr/decode url query param, max 2048 chars
GET /v1/barcode/decode Identical behaviour and response

Both decode routes are GET-only in the current build and both require url. To decode base64 you have in hand, host it briefly (or upload to your own storage/CDN) and pass that HTTPS URL.

Both routes are authenticated (X-API-Key or Authorization: Bearer).

The pipeline

  1. SSRF validation. validate_url(url) runs before any network call. Non-http(s) schemes, localhost, and private/link-local/loopback addresses are refused.
  2. Fetch. httpx GET, timeout=15.0, follow_redirects=True. There is a 10 MB post-download cap — note this is larger than the 5 MB logo limit used during generation, because photographs are big.
  3. Open. PIL.Image.open(BytesIO(content)). The format is sniffed from bytes, not from Content-Type or the file extension.
  4. Grayscale. img.convert("L") — colour is discarded before decoding. This is why colour QR codes work at all, and why low contrast between fg/bg kills decode even when the image "looks" fine.
  5. Detect. pyzbar.decode(grey) (system libzbar) scans the whole frame and returns all symbols it can locate in one pass.
  6. Map results. For each symbol → payload, type, quality label, polygon.

Because detection is a single whole-frame pass, one image can return many symbols — a label sheet with 12 barcodes returns found: 12. There is no limit/crop parameter; crop client-side if you need a specific symbol.

The response

{
  "found": 2,
  "results": [
    {
      "data": "https://example.com/menu",
      "type": "QRCODE",
      "quality": "good",
      "position": {"polygon": [{"x": 41, "y": 37}, {"x": 212, "y": 37}, {"x": 212, "y": 208}, {"x": 41, "y": 208}]}
    },
    {
      "data": "4006381333931",
      "type": "EAN13",
      "quality": "partial",
      "position": {"polygon": []}
    }
  ]
}
Field Notes
found len(results) — the count of decoded symbols, not the count of symbols in the image
data Payload string
type pyzbar type string, e.g. QRCODE, EAN13, CODE128
quality "good" if pyzbar reports quality ≥ 1, otherwise "partial". It reflects decode confidence, not image sharpness
position.polygon List of {x, y} corner points in source-image pixel coordinates. Empty list when pyzbar returns no polygon (common for 1D symbols)

Payload encoding

try:
    payload = symbol.data.decode("utf-8")
except UnicodeDecodeError:
    payload = symbol.data.hex()
  • Valid UTF-8 bytes are returned as text.
  • Anything else is silently hex-encoded — a binary 2FA seed or a Latin-1 string comes back as "68656c6c6f". There is no flag telling you which branch ran.

Detect it before using the value:

def payload_bytes(item: dict) -> bytes:
    """Recover the raw bytes whichever branch the decoder took."""
    s = item["data"]
    if item["type"] == "QRCODE" and len(s) % 2 == 0 and all(c in "0123456789abcdef" for c in s):
        try:
            return bytes.fromhex(s)
        except ValueError:
            pass
    return s.encode("utf-8")

Warning

The heuristic is ambiguous by nature: a genuine hex-looking string ("deadbeef") is indistinguishable from hex-encoded bytes DE AD BE EF. If your workflow round-trips binary payloads, prefix them with a marker byte and strip it after decoding — do not rely on sniffing.

Symbol type strings

type is whatever pyzbar reports. Values you will actually see:

2D

Value Notes
QRCODE Standard QR, including micro QR when libzbar supports it
DATABAR_EXP GS1 DataBar Expanded
PDF417 Stacked 2D, common on ID cards and boarding passes
AZTEC Transit tickets

1D

Value Notes
EAN13, EAN8 Retail GTIN; payload is 13/8 digits with check digit
UPCA, UPCE North American retail
CODE128 Full ASCII, most supply-chain labels
CODE39 Alphanumeric plus - . $ / + % space
CODE93 Denser Code39
I25 Interleaved 2 of 5, numeric only
CODABAR Numeric plus -$:/.+
DATABAR, DATABAR_EXP GS1 DataBar family

Matching is case-sensitive and exact. Tolerate aliases when branching on type:

ALIASES = {"EAN-13": "EAN13", "UPC-A": "UPCA", "UPC-E": "UPCE", "CODE-128": "CODE128",
           "I2OF5": "I25", "ITF": "I25", "QR": "QRCODE"}

def kind(item: dict) -> str:
    t = item["type"].upper()
    return ALIASES.get(t, t)

def is_gs1(item: dict) -> bool:
    return kind(item) in {"DATABAR", "DATABAR_EXP", "EAN13", "EAN8", "UPCA", "UPCE", "CODE128"}

Note that generation and decoding are asymmetric: while /v1/barcode/generate accepts lowercase enum values like ean13, the decoder reports EAN13.

Examples

Decode a label photo (GET)

curl -s "https://barcode.toolkitapi.io/v1/qr/decode?url=https%3A%2F%2Fcdn.example.com%2Flabel.png" \
  -H "X-API-Key: $BARCODE_API_KEY" \
  | jq '[.found, (.results[] | {type, quality, data})]'
import httpx

r = httpx.get(
    "https://barcode.toolkitapi.io/v1/qr/decode",
    headers={"X-API-Key": BARCODE_API_KEY},
    params={"url": "https://cdn.example.com/label.png"},
    timeout=45,          # server fetch is 15 s; leave headroom for a large image
)
r.raise_for_status()     # 400 = SSRF refusal / >10 MB / unopenable image
body = r.json()

for item in body["results"]:
    poly = item["position"].get("polygon") or []
    xs = [p["x"] for p in poly] or [None]
    print(f'{item["type"]:9} {item["quality"]:8} {item["data"][:60]}  x={min(xs) if xs[0] is not None else "-"}')
const qs = new URLSearchParams({ url: "https://cdn.example.com/label.png" });
const res = await fetch(`https://barcode.toolkitapi.io/v1/qr/decode?${qs}`, {
  headers: { "X-API-Key": process.env.BARCODE_API_KEY },
});
if (!res.ok) throw new Error(`${res.status} ${(await res.json()).detail}`);
const { found, results } = await res.json();

// Left-to-right order for a label sheet, using polygon centroids
const ordered = results
  .map((r) => {
    const pts = r.position.polygon ?? [];
    const cx = pts.length ? pts.reduce((s, p) => s + p.x, 0) / pts.length : 0;
    return { ...r, cx };
  })
  .sort((a, b) => a.cx - b.cx);

console.log(found, ordered.map((r) => r.data));

Persist a whole sheet in one call

import csv, httpx

def scan_sheet(url: str) -> list[dict]:
    r = httpx.get("https://barcode.toolkitapi.io/v1/barcode/decode",
                  headers={"X-API-Key": BARCODE_API_KEY},
                  params={"url": url}, timeout=60)
    r.raise_for_status()
    rows = []
    for item in r.json()["results"]:
        rows.append({
            "type": item["type"],
            "quality": item["quality"],
            "data": item["data"],
            "polygon_points": len(item["position"].get("polygon") or []),
        })
    return rows

rows = scan_sheet("https://cdn.example.com/label-sheet.png")
with open("scan.csv", "w", newline="") as fh:
    w = csv.DictWriter(fh, fieldnames=list(rows[0]))
    w.writeheader()
    w.writerows(rows)
print(len(rows), "symbols")   # e.g. 12 symbols from one A4 sheet

Retry with a re-uploaded, rotated, scaled copy

partial quality on a symbol you expected to read cleanly usually means the crop is too tight or the image was resized. A small offline preflight helps more than re-calling the API:

from PIL import Image, ImageOps

def prepare_for_decode(path: str, out: str, target_width: int = 1600) -> str:
    """Normalise EXIF rotation, upscale small symbols, boost contrast, flatten to gray."""
    img = Image.open(path)
    img = ImageOps.exif_transpose(img).convert("L")
    if img.width < target_width:
        scale = target_width / img.width
        img = img.resize((int(img.width * scale), int(img.height * scale)), Image.LANCZOS)
    img = ImageOps.autocontrast(img, cutoff=1)
    img.save(out, format="PNG")
    return out

print(prepare_for_decode("photo.jpg", "/tmp/ready.png"))  # then upload /tmp/ready.png and decode
// Browser-side preflight before uploading: flatten to grayscale and upscale.
export async function prepareForDecode(file, targetWidth = 1600) {
  const bmp = await createImageBitmap(file);
  const scale = Math.max(1, targetWidth / bmp.width);
  const canvas = new OffscreenCanvas(Math.round(bmp.width * scale), Math.round(bmp.height * scale));
  const ctx = canvas.getContext("2d", { willReadFrequently: true });
  ctx.drawImage(bmp, 0, 0, canvas.width, canvas.height);
  const { data } = ctx.getImageData(0, 0, canvas.width, canvas.height);
  for (let i = 0; i < data.length; i += 4) {
    const g = (data[i] * 0.299 + data[i + 1] * 0.587 + data[i + 2] * 0.114) | 0;
    data[i] = data[i + 1] = data[i + 2] = g;
  }
  ctx.putImageData(new ImageData(data, canvas.width, canvas.height), 0, 0);
  return canvas.convertToBlob({ type: "image/png" });
}

Failure modes

Symptom Cause Fix
found: 0, results: [] Nothing detected Larger crop, more contrast, less rotation/skew, avoid downscaled thumbnails
partial quality Marginal read Upscale + autocontrast, or regenerate the code bigger
400 Image too large: N bytes (limit 10 MB) Over the cap Downscale before hosting; PNG > JPEG for line art
400 mentioning the host/scheme SSRF guard Host the image on a public https:// URL
500 Decode failed: … Image fetched but unopenable, or libzbar error Confirm the URL serves real image bytes, not an HTML error page
Hex gibberish in data Non-UTF-8 payload branch Use the payload_bytes() helper above
Empty polygon pyzbar had no polygon for that symbol Normal for many 1D symbols — fall back to sheet order

Errors

Status Meaning
200 Always returned when the image loads — including found: 0
400 SSRF refusal, download > 10 MB, or unfetchable URL
401 Missing/invalid X-API-Key
422 url missing or > 2048 chars
500 Decode failed: …