Quick Start

What is the Barcode API?

The Barcode API lets you generate barcode images on demand via a simple HTTP GET request — no SDK required, no complex setup. Construct a URL with the barcode format and data, and get back a ready-to-use image in SVG, PNG, JPG, or WebP format. Use it in web apps, PDF pipelines, label printing workflows, ERP integrations, or any backend that needs machine-readable codes.

It supports 50+ barcode formats including Code 128, EAN-13, UPC-A, QR Code, Data Matrix, PDF417, and many more — powered by JsBarcode and BWIP-JS under the hood.

Base URL

https://www.barcodegen.net

Authentication

All requests must include a valid API key in the Authorization header using the Bearer scheme.

Authorization: Bearer YOUR_API_KEY

API keys are managed in your dashboard. Each request deducts 1 credit from your account balance. If authentication fails or your balance is insufficient, the request is rejected before any barcode generation takes place — you are never charged for failed requests.

Note: The API requires server-side requests only. Do not embed your API key in browser-side code or <img> src URLs — the Authorization header cannot be set by browsers for image requests. Use a server-side proxy instead (see Embedding Barcodes in HTML).

Quick Start

Generate a Code 128 barcode encoding ABC-123:

GET /api/barcode/Code128/ABC-123

Call it from your backend:

curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://www.barcodegen.net/api/barcode/Code128/ABC-123"

To get a PNG instead of SVG:

curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://www.barcodegen.net/api/barcode/Code128/ABC-123?format=png" \
  --output barcode.png

Endpoint

Generate Barcode

GET /api/barcode/{format}/{data}

Returns a barcode image in the requested output format.

Path Parameters

ParameterTypeRequiredDescription
formatstringYesBarcode format identifier (case-insensitive). See Supported Formats for the full list.
datastringYesThe value to encode. Must conform to the rules of the chosen format (e.g. EAN-13 requires exactly 12–13 digits).

Query Parameters

ParameterTypeRequiredDefaultDescription
formatstringNosvgOutput image format. One of svg, png, jpg, webp. PNG, JPG, and WebP require a paid plan.

Example Requests

# SVG (free and paid plans)
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://www.barcodegen.net/api/barcode/EAN13/5901234123457"

# PNG (paid plans only)
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://www.barcodegen.net/api/barcode/EAN13/5901234123457?format=png" \
  --output barcode.png

# JPG (paid plans only)
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://www.barcodegen.net/api/barcode/QRCODE/https://example.com?format=jpg" \
  --output barcode.jpg

Example Response

On success, the response body is the raw image with the following headers:

HTTP/1.1 200 OK
Content-Type: image/svg+xml
Cache-Control: public, max-age=31536000, immutable
X-Credits-Cost: 1
X-Credits-Remaining: 499

Output Formats

FormatContent-TypeAvailable On
svgimage/svg+xmlAll plans
pngimage/pngPaid plans only
jpgimage/jpegPaid plans only
webpimage/webpPaid plans only

Free plan accounts requesting PNG, JPG, or WebP will receive a 402 error with an upgrade link.

Response Headers

HeaderDescription
X-Credits-CostNumber of credits deducted for this request.
X-Credits-RemainingYour remaining credit balance after deduction.

Supported Formats

The API supports two rendering engines internally. All formats below are available through the same endpoint — you do not need to specify an engine.

Linear (1D) Barcodes

FormatDescription
CODE128General-purpose alphanumeric. Most widely used in logistics and retail.
EAN1313-digit European Article Number. Standard retail product barcode.
ISBNInternational Standard Book Number (uses EAN-13).
ISSNInternational Standard Serial Number for periodicals.
ISMNInternational Standard Music Number.

2D Barcodes

FormatDescription
QRCODEQR Code. High-capacity 2D code for URLs, text, vCards, etc.
DATAMATRIXCompact 2D code widely used in electronics and healthcare.
PDF417Stacked 2D barcode. Common on ID cards and shipping labels.
AZTECHigh-density 2D code used on airline boarding passes.
HANXINHan Xin Code. Chinese national standard 2D barcode.

The format path parameter is case-insensitiveCode128, code128, and CODE128 all work identically.

Error Codes

StatusErrorDescription
400Invalid parametersformat or data path segment is missing.
400Unsupported format "{format}"The ?format= query value is not one of svg, png, jpg, webp.
400Invalid barcode value for format "{format}": {data}The data does not conform to the rules of the requested barcode format (e.g. wrong length, invalid characters). No credits are charged.
401Missing or invalid API keyThe Authorization header is missing, malformed, or the key has been revoked.
402Insufficient creditsYour credit balance is zero or below the cost of this request.
402Format "{format}" is available on paid plans onlyPNG, JPG, or WebP requested on a free plan account.
429Rate limit exceededToo many requests in a short window. Wait and retry.
500Barcode generation failedUnexpected server-side error. No credits are charged.

Error Response Shape

All errors return JSON:

{
  "error": "Invalid barcode value for format \"EAN13\": 123"
}

Upgrade-required errors also include an upgrade_url field:

{
  "error": "Format \"png\" is available on paid plans only. Upgrade at https://www.barcodegen.net/pricing",
  "upgrade_url": "https://www.barcodegen.net/pricing"
}

Credit Deduction Model

Credits are deducted before barcode generation begins, using an atomic Redis operation to prevent race conditions under concurrent load. The sequence is:

  1. Request is authenticated and rate-limited.
  2. 1 credit is atomically reserved from your balance.
  3. Barcode is generated and converted to the requested format.
  4. On any generation or conversion failure, credits are automatically refunded.
  5. On success, the image is returned along with the updated balance in the response headers.

This means you only pay for barcodes that are successfully generated.

Embedding Barcodes in HTML

Because the API requires an Authorization header, you cannot use the API URL directly as an <img src>. Browsers do not send custom headers for image requests, and exposing your API key in frontend code is a security risk.

The correct approach is a server-side proxy route that holds your API key securely and forwards requests:

// app/api/barcode/[...slug]/route.ts (proxy)
export async function GET(
  req: Request,
  { params }: { params: { slug: string[] } }
) {
  const [format, data] = params.slug;
  const outputFormat = new URL(req.url).searchParams.get('format') ?? 'svg';

  const upstream = await fetch(
    `https://www.barcodegen.net/api/barcode/${format}/${encodeURIComponent(data)}?format=${outputFormat}`,
    { headers: { Authorization: `Bearer ${process.env.BARCODE_API_KEY}` } }
  );

  const body = await upstream.arrayBuffer();
  return new Response(body, {
    headers: {
      'Content-Type': upstream.headers.get('Content-Type') ?? 'image/svg+xml',
      'Cache-Control': 'public, max-age=31536000, immutable',
    },
  });
}

Then use your proxy URL safely in HTML:

<!-- SVG via proxy (free plan) -->
<img src="/api/barcode/Code128/ABC-123" alt="Barcode ABC-123" />

<!-- PNG via proxy (paid plan) -->
<img src="/api/barcode/Code128/ABC-123?format=png" alt="Barcode ABC-123" />

Your API key stays on the server and is never exposed to the browser.

Caching

Successful responses are served with:

Cache-Control: public, max-age=31536000, immutable

The same barcode URL (same format + same data + same output format) will always produce the same output, so CDN and browser caching work reliably. Cached responses do not deduct additional credits — you are only charged on the first generation.

Code Examples

JavaScript (fetch)

const response = await fetch(
  'https://www.barcodegen.net/api/barcode/Code128/ABC-123',
  { headers: { Authorization: 'Bearer YOUR_API_KEY' } }
);

if (!response.ok) {
  const { error } = await response.json();
  throw new Error(error);
}

const svg = await response.text();
const remaining = response.headers.get('X-Credits-Remaining');

console.log(`Credits remaining: ${remaining}`);
document.getElementById('barcode').innerHTML = svg;

JavaScript — PNG download

const response = await fetch(
  'https://www.barcodegen.net/api/barcode/Code128/ABC-123?format=png',
  { headers: { Authorization: 'Bearer YOUR_API_KEY' } }
);

if (!response.ok) {
  const { error } = await response.json();
  throw new Error(error);
}

const blob = await response.blob();
const url = URL.createObjectURL(blob);

const a = document.createElement('a');
a.href = url;
a.download = 'barcode.png';
a.click();

Python (requests)

import requests

resp = requests.get(
    'https://www.barcodegen.net/api/barcode/EAN13/5901234123457',
    headers={'Authorization': 'Bearer YOUR_API_KEY'},
)
resp.raise_for_status()

with open('barcode.svg', 'w') as f:
    f.write(resp.text)

print('Credits remaining:', resp.headers['X-Credits-Remaining'])
# PNG output (paid plans)
resp = requests.get(
    'https://www.barcodegen.net/api/barcode/EAN13/5901234123457',
    params={'format': 'png'},
    headers={'Authorization': 'Bearer YOUR_API_KEY'},
)
resp.raise_for_status()

with open('barcode.png', 'wb') as f:
    f.write(resp.content)

PHP (cURL)

$ch = curl_init('https://www.barcodegen.net/api/barcode/QRCODE/https://example.com');
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer YOUR_API_KEY']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$svg = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($status === 200) {
    file_put_contents('barcode.svg', $svg);
}

Rate Limits

Requests are rate-limited per API key using a sliding window algorithm:

PlanLimit
Free10 requests / minute
Paid50 requests / minute

Exceeding the limit returns a 429 response. Implement exponential backoff before retrying.

Next Steps

  • Supported Formats — Full format list with valid value rules and encoding limits
  • Credit Pricing — Plan comparison and how to top up your balance
  • Rate Limits — Request limits per API key and how to handle 429 responses
  • Dashboard — View usage history and manage your API keys