Barcode Symbology Selection & Data Validation

/v1/barcode/generate accepts 11 symbologies. Each has hard rules about length and character set — and the API returns a 400 (not a warning) when you violate them. This page is the practical mapping from use case to symbology, plus a validator you can run locally so bad data never reaches the API.

For the full per-type metadata listing, see Barcode Types Reference.

Base URL: https://barcode.toolkitapi.io

Method Endpoint Auth
GET /v1/barcode/generate X-API-Key
GET /v1/barcode/decode X-API-Key
POST /v1/barcode/bulk X-API-Key
GET /v1/barcode/types X-API-Key

1. Use case → symbology

Use case Symbology Why
Retail product (US/Canada) upca Fixed 12 digits, universal POS scanner support
Retail product (international) ean13 Fixed 13 digits, GS1 standard
Small retail package ean8 Fixed 8 digits, when width is tight
Book (ISBN) isbn13 / isbn10 Hyphen-aware; scanners recognise bookland prefix
Magazine / serial issn Fixed 8 characters, periodical standard
Pharma (Germany) pzn Fixed 8 characters, German pharmaceutical number
Shipping carton (interleaved) itf Numeric, even digit count, printed on corrugate
Internal asset tags, SKUs code128 Full ASCII, variable length, highest density
Legacy industrial / automotive code39 Uppercase alphanumeric subset, very tolerant of poor print
Trade item with extra digits ean14 Fixed 14 digits, GTIN-14 cartons

Default rule: if there's no external standard compelling you elsewhere, use code128. It encodes all 128 ASCII characters, has the best density of the 1D types here, and every modern scanner reads it. Use code39 only when a legacy scanner requires it.


2. Per-type rules

Type Length Character set Checksum
code128 1 – 80 (practical) Full ASCII Automatic (mod 103)
code39 1 – 80 A-Z 0-9 - . $ / + % space Optional (mod 43)
ean13 12 or 13 digits only Auto-computed if 12 supplied
ean8 7 or 8 digits only Auto-computed if 7 supplied
ean14 13 or 14 digits only Auto-computed if 13 supplied
upca 11 or 12 digits only Auto-computed if 11 supplied
isbn13 12 or 13 digits (or hyphens, stripped) Auto-computed
isbn10 9 or 10 digits + X Auto-computed
issn 7 or 8 digits + X Auto-computed
pzn 7 or 8 digits Auto-computed
itf even number of digits digits only None

The checksum-easing convention

Every fixed-length numeric type accepts its length minus the check digit and computes the check digit for you. That is the single most useful behaviour to build around:

# Supply 12 digits, get a valid UPC-A (13th digit is computed)
curl -G "https://barcode.toolkitapi.io/v1/barcode/generate" \
  -H "X-API-Key: YOUR_KEY" \
  --data-urlencode "data=123456789012" \
  --data-urlencode "barcode_type=upca" \
  --output upca.png

If you supply the full length, the supplied check digit is used as-is — which means a wrong check digit produces a barcode that scans to a different value than you expect. Prefer the short form and let the API compute it.


3. Client-side validation

Fail locally, fast, with a clear message — before the network round-trip:

import re

# type -> (allowed_lengths, regex)
RULES = {
    "code128": (None, r"^[\x00-\x7F]+$"),
    "code39":  (None, r"^[A-Z0-9\-. $/+%]+$"),
    "ean13":   ({12, 13}, r"^\d+$"),
    "ean8":    ({7, 8},   r"^\d+$"),
    "ean14":   ({13, 14}, r"^\d+$"),
    "upca":    ({11, 12}, r"^\d+$"),
    "isbn13":  ({12, 13}, r"^[\d-]+$"),
    "isbn10":  ({9, 10},  r"^[\dX]+$"),
    "issn":    ({7, 8},   r"^[\dX]+$"),
    "pzn":     ({7, 8},   r"^\d+$"),
    "itf":     (None,     r"^\d+$"),
}

def validate(data: str, barcode_type: str) -> list[str]:
    """Return a list of problems; empty means OK to send."""
    if barcode_type not in RULES:
        return [f"unknown type {barcode_type!r}"]
    if not data:
        return ["data is empty"]
    if len(data) > 256:
        return [f"data is {len(data)} chars; the API caps it at 256"]

    lengths, pattern = RULES[barcode_type]
    problems = []

    if lengths and len(data) not in lengths:
        allowed = " or ".join(str(n) for n in sorted(lengths))
        problems.append(f"{barcode_type} requires {allowed} chars, got {len(data)}")

    if not re.match(pattern, data):
        problems.append(f"{data!r} contains characters {barcode_type} cannot encode")

    if barcode_type == "itf" and len(data) % 2 != 0:
        problems.append("itf requires an even number of digits")

    return problems

# validate("123456789012", "upca")   -> []
# validate("12345", "upca")          -> ['upca requires 11 or 12 chars, got 5']
# validate("abc", "ean13")           -> ["'abc' contains characters ean13 cannot encode"]
const RULES = {
  code128: { lengths: null, re: /^[\x00-\x7F]+$/ },
  code39: { lengths: null, re: /^[A-Z0-9\-. $/+%]+$/ },
  ean13: { lengths: [12, 13], re: /^\d+$/ },
  ean8: { lengths: [7, 8], re: /^\d+$/ },
  ean14: { lengths: [13, 14], re: /^\d+$/ },
  upca: { lengths: [11, 12], re: /^\d+$/ },
  itf: { lengths: null, re: /^\d+$/, even: true },
};

function validate(data, type) {
  const rule = RULES[type];
  if (!rule) return [`unknown type ${type}`];
  if (!data) return ["data is empty"];
  if (data.length > 256) return [`${data.length} chars exceeds the 256 limit`];

  const problems = [];
  if (rule.lengths && !rule.lengths.includes(data.length)) {
    problems.push(`${type} requires ${rule.lengths.join(" or ")} chars, got ${data.length}`);
  }
  if (!rule.re.test(data)) problems.push(`${JSON.stringify(data)} has unencodable characters`);
  if (rule.even && data.length % 2) problems.push("itf requires an even digit count");
  return problems;
}

Validating a batch before /v1/barcode/bulk

Bulk requests are all-or-nothing: one bad item raises a 400 and the whole batch fails, with the message naming the offending item (truncated to 50 chars). That is the worst possible failure mode — you pay latency for 19 good barcodes and get nothing.

items = [
    {"data": "123456789012", "barcode_type": "upca"},
    {"data": "ABC123", "barcode_type": "code128"},
    {"data": "78901", "barcode_type": "ean13"},   # bad: 5 digits
]

bad = [(i, validate(it["data"], it["barcode_type"])) for i, it in enumerate(items)]
bad = [(i, p) for i, p in bad if p]

if bad:
    raise ValueError(f"refusing to send; items {[i for i, _ in bad]} are invalid: {bad}")

# otherwise POST /v1/barcode/bulk with {"items": items}

Also enforce locally: 1 – 20 items per bulk request, PNG output only (bulk ignores format), and 256 characters per data value.


4. Rendering parameters that actually matter

Parameter Range Default Effect
format png, svg png svg for print/labels — infinitely scalable, no rasterisation artefacts
module_height 5.0 – 50.0 mm 15.0 The single biggest scan-rate factor. Below ~10 mm, laser scanners struggle.
quiet_zone 0.0 – 20.0 mm 6.5 White margin; below ~5 mm scanners lose the start/stop pattern
include_text bool true Human-readable line below the bars — keep it on for anything hand-keyed
fg_color / bg_color hex, ≤ 9 chars #000000 / #ffffff Must have high contrast; light bars on dark background will not scan on most readers

Print rules of thumb:

  • format=svg + module_height=10 + quiet_zone=5 is a safe default for a printed label.
  • Never scale the rasterised PNG up — re-request at target size, or use SVG.
  • fg_color/bg_color are inverted-safe only if your scanner supports inverse reading. Assume it doesn't: dark bars, light background, always.

5. Decoding to verify

GET /v1/barcode/decode takes an image URL (max 2048 chars) and returns every barcode it finds — 1D and QR.

curl -G "https://barcode.toolkitapi.io/v1/barcode/decode" \
  -H "X-API-Key: YOUR_KEY" \
  --data-urlencode "url=https://cdn.example.com/labels/shelf-42.png"
const found = await fetch(
  "https://barcode.toolkitapi.io/v1/barcode/decode?url=" +
    encodeURIComponent("https://cdn.example.com/labels/shelf-42.png"),
  { headers: { "X-API-Key": "YOUR_KEY" } }
).then((r) => r.json());

if (found.found === 0) throw new Error("no barcode detected — check quiet zone and contrast");

The image must be publicly reachable — the API fetches it server-side, so a localhost or private-network URL will fail. A generate→decode round-trip is the cheapest end-to-end test of your whole label pipeline:

import base64, requests

# generate as PNG base64 via bulk (single item), then host it, then decode
gen = requests.post(
    "https://barcode.toolkitapi.io/v1/barcode/bulk",
    headers={"X-API-Key": "YOUR_KEY"},
    json={"items": [{"data": "123456789012", "barcode_type": "upca"}]},
    timeout=30,
).json()

png_b64 = gen["results"][0]["image"]   # base64 PNG, no data: prefix
# upload png_b64 to a public URL, then:
# GET /v1/barcode/decode?url=<that url>  -> results[0].data should equal the input

6. Common errors

Status Message shape Cause
400 Failed to generate barcode for '<first 50 chars>': ... Invalid data for the symbology (length, charset)
400 ... from the decoder Unreachable or non-image URL on /decode
401 / 403 — Missing or invalid X-API-Key
422 Pydantic validation detail module_height or quiet_zone outside range; more than 20 bulk items
500 Decode failed: ... Decoder crashed on a corrupt image

Validate client-side (section 3) and most of these disappear.