Complete developer documentation for programmatic barcode generation
The Barcodes.dev REST API provides programmatic access to generate high-quality barcodes, QR codes, 2D matrix codes, and postal codes. Perfect for developers who need to integrate barcode generation into their applications, e-commerce platforms, inventory systems, and more.
Simple REST API with JSON requests and responses. Works with any programming language that supports HTTP.
Generate Code128, EAN, UPC, ISBN, QR codes, DataMatrix (with DMRE support), Aztec, postal codes, and more.
Output in PNG, JPEG, or WEBP formats with customizable sizing and colors.
Comprehensive validation with detailed error messages for debugging.
API v1: Free public access. API v2: Free tier (1,000/month) + paid tiers for high volume.
Full OpenAPI specification for code generation and interactive documentation.
https://barcodes.dev
Try this command to generate your first barcode using API v1 (no authentication required):
curl -X POST https://barcodes.dev/api/v1/barcode \
-H "Content-Type: application/json" \
-d '{"text": "Hello World", "barcode_type": "code128"}' \
--output my-first-barcode.png
๐ก Pro Tip: All endpoints return PNG images by default. You can request JPEG or WEBP by setting "image_format": "JPEG" or "image_format": "WEBP".
No authentication required โข Rate limited for fair use โข Perfect for getting started
API v1 provides free public access to basic barcode and QR code generation. No registration or API key required!
https://barcodes.dev/api/v1/Generate Linear/1D Barcodes
Create traditional 1D barcodes including Code128, Code39, EAN, UPC, ISBN, and more. Now supports 50+ linear symbology types.
code128, gs1, gs1_128, ean14, nve18, sscc18, hibc_128, dpdean, ean2, ean5, ean8, ean13, upc, upca, upce, isbn, isbn10, isbn13, sbn, jancode39, excode39, code32, hibc_39, vin, logmarscode93, code11, codabarc25standard, c25iata, c25ind, c25inter, itf, c25logic, itf14, dpleit, dpidentplessey, msi, msi_plesseytelepen, telepen_numpharma, pharmacode, pzndbar_omn, dbar_ltd, dbar_exp, databar_omn, databar_ltd, databar_exp, gs1_databar_omn, gs1_databar_ltd, gs1_databar_expkoreapost, channelgtin
| Parameter | Type | Required | Description |
|---|---|---|---|
text |
string | โ Yes | Data to encode in the barcode |
barcode_type |
string | โ Yes | Type of barcode to generate |
image_format |
string | No | Output format: PNG, JPEG, WEBP (default: PNG) |
output |
string | No | Response type: base64 or file (default: file) |
curl -X POST https://barcodes.dev/api/v1/barcode \\
-H "Content-Type: application/json" \\
-d '{
"text": "123456789012",
"barcode_type": "code128",
"image_format": "PNG"
}' \\
--output barcode.png
200 OK - Returns binary image data with appropriate Content-Type header.
Generate QR Codes
Create QR codes with customizable error correction, colors, and sizing options.
| Parameter | Type | Required | Description |
|---|---|---|---|
text |
string | โ Yes | Data to encode in the QR code |
error_correction |
string | No | Error correction level: L, M, Q, H (default: M) |
box_size |
integer | No | Size of each box in pixels (default: 10) |
border |
integer | No | Border size in boxes (default: 4) |
image_format |
string | No | Output format: PNG, JPEG, WEBP (default: PNG) |
curl -X POST https://barcodes.dev/api/v1/qrcode \\
-H "Content-Type: application/json" \\
-d '{
"text": "https://barcodes.dev",
"error_correction": "M",
"box_size": 10,
"border": 4,
"image_format": "PNG"
}' \\
--output qrcode.png
200 OK - Returns binary image data with appropriate Content-Type header.
Usage Statistics
Get current usage statistics for the public API.
curl -X GET https://barcodes.dev/api/v1/usage
200 OK
{
"success": true,
"usage": {
"current_hour": 15,
"current_day": 243,
"api_version": "v1"
}
}
Version Information
Get API version information and available features for the public API.
curl -X GET https://barcodes.dev/api/v1/version
200 OK
{
"version": "1.0",
"api_version": "1.0",
"features": ["barcode", "qrcode", "usage", "version"]
}
Enhanced features โข Batch processing โข Account management โข Higher rate limits
API v2 requires authentication but offers enhanced features and higher rate limits.
https://barcodes.dev/api/v2/X-API-Key headerGenerate Linear/1D Barcodes (Enhanced)
Create traditional 1D barcodes with enhanced features and both POST and GET support. Now supports 50+ linear symbology types.
code128, gs1, gs1_128, ean14, nve18, sscc18, hibc_128, dpdean, ean2, ean5, ean8, ean13, upc, upca, upce, isbn, isbn10, isbn13, sbn, jancode39, excode39, code32, hibc_39, vin, logmarscode93, code11, codabarc25standard, c25iata, c25ind, c25inter, itf, c25logic, itf14, dpleit, dpidentplessey, msi, msi_plesseytelepen, telepen_numpharma, pharmacode, pzndbar_omn, dbar_ltd, dbar_exp, databar_omn, databar_ltd, databar_exp, gs1_databar_omn, gs1_databar_ltd, gs1_databar_expkoreapost, channelgtin
curl -X POST https://barcodes.dev/api/v2/barcode \\
-H "Content-Type: application/json" \\
-H "X-API-Key: bcd_your_api_key_here" \\
-d '{
"text": "123456789012",
"barcode_type": "code128",
"image_format": "PNG"
}' \\
--output barcode.png
curl -X GET "https://barcodes.dev/api/v2/barcode?text=123456&barcode_type=code128" \\ -H "X-API-Key: bcd_your_api_key_here" \\ --output barcode.png
{
"success": true,
"data": "iVBORw0KGgoAAAANSUhEUgAA...",
"format": "PNG",
"encoding": "base64",
"barcode_type": "code128",
"text": "123456789012",
"user_tier": "free"
}
Generate QR Codes (Enhanced)
Create QR codes with enhanced features and both POST and GET support.
curl -X POST https://barcodes.dev/api/v2/qrcode \\
-H "Content-Type: application/json" \\
-H "X-API-Key: bcd_your_api_key_here" \\
-d '{
"text": "https://barcodes.dev",
"error_correction": "M",
"box_size": 10,
"border": 4,
"image_format": "PNG"
}' \\
--output qrcode.png
curl -X GET "https://barcodes.dev/api/v2/qrcode?text=https://barcodes.dev&error_correction=M" \\ -H "X-API-Key: bcd_your_api_key_here" \\ --output qrcode.png
Generate 2D Matrix Codes
Create 2D matrix codes including DataMatrix (with DMRE support), Aztec, MaxiCode, and more advanced 2D formats.
datamatrix, aztec, maxicode, codeone, gridmatrix, dotcode, hanxin, microqr, rmqr, upnqr
curl -X POST https://barcodes.dev/api/v2/2d \\
-H "Content-Type: application/json" \\
-H "X-API-Key: bcd_your_api_key_here" \\
-d '{
"text": "Sample DataMatrix with DMRE",
"twod_type": "datamatrix",
"shape": "dmre",
"scale_factor": 8,
"image_format": "PNG"
}' \\
--output datamatrix.png
curl -X GET "https://barcodes.dev/api/v2/2d?text=Sample%20Data&twod_type=datamatrix&shape=dmre" \\ -H "X-API-Key: bcd_your_api_key_here" \\ --output datamatrix.png
Generate Postal Codes
Create postal barcodes for various national postal services including USPS, Royal Mail, Australia Post, and more.
usps_imd, usps_postnet, usps_planet, royal_mail, ukroyalmail, australia_post, auspost, netherlands_kix, japan_post, japanpost, korea_post
curl -X POST https://barcodes.dev/api/v2/postal \\
-H "Content-Type: application/json" \\
-H "X-API-Key: bcd_your_api_key_here" \\
-d '{
"text": "12345678901",
"postal_type": "usps_imd",
"height": 50,
"image_format": "PNG"
}' \\
--output postal.png
curl -X GET "https://barcodes.dev/api/v2/postal?text=12345678901&postal_type=usps_imd" \\ -H "X-API-Key: bcd_your_api_key_here" \\ --output postal.png
Generate Stacked Codes
Create stacked barcode formats including PDF417, MicroPDF417, and other multi-row barcode types.
pdf417, pdf417comp, micropdf417, codablock_f, code16k, code49, gs1_databar_stacked, gs1_databar_stacked_omni, gs1_databar_expanded_stacked
curl -X POST https://barcodes.dev/api/v2/stacked \\
-H "Content-Type: application/json" \\
-H "X-API-Key: bcd_your_api_key_here" \\
-d '{
"text": "PDF417 Stacked Data",
"stacked_type": "pdf417",
"height": 80,
"columns": 6,
"image_format": "PNG"
}' \\
--output stacked.png
curl -X GET "https://barcodes.dev/api/v2/stacked?text=PDF417%20Data&stacked_type=pdf417" \\ -H "X-API-Key: bcd_your_api_key_here" \\ --output stacked.png
Generate Composite Codes
Create composite barcode symbols that combine linear and 2D components for enhanced data encoding.
gs1_128_cc, eanx_cc, upca_cc, upce_cc, dbar_omn_cc, dbar_ltd_cc, dbar_exp_cc, dbar_stk_cc, dbar_omnstk_cc, dbar_expstk_cc
curl -X POST https://barcodes.dev/api/v2/composite \\
-H "Content-Type: application/json" \\
-H "X-API-Key: bcd_your_api_key_here" \\
-d '{
"text": "^010123456789012815170719",
"primary_data": "(01)01234567890128(15)170719",
"composite_type": "gs1_128_cc",
"cc_mode": 2,
"image_format": "PNG"
}' \\
--output composite.png
curl -X GET "https://barcodes.dev/api/v2/composite?text=^010123456789012815170719&primary_data=(01)01234567890128(15)170719&composite_type=gs1_128_cc" \\ -H "X-API-Key: bcd_your_api_key_here" \\ --output composite.png
Batch Generation (POST Only)
Generate multiple barcodes and QR codes in a single request. Maximum 10 items per batch.
curl -X POST https://barcodes.dev/api/v2/batch \\
-H "Content-Type: application/json" \\
-H "X-API-Key: bcd_your_api_key_here" \\
-d '{
"batch": [
{
"type": "barcode",
"text": "BATCH-001",
"barcode_type": "code128",
"image_format": "PNG"
},
{
"type": "qrcode",
"text": "https://example.com",
"error_correction": "M"
}
]
}'
{
"success": true,
"batch_results": [
{
"index": 0,
"success": true,
"data": "base64_encoded_barcode",
"format": "PNG",
"encoding": "base64"
},
{
"index": 1,
"success": true,
"data": "base64_encoded_qrcode",
"format": "PNG",
"encoding": "base64"
}
],
"total_processed": 2,
"user_tier": "free"
}
Account Information (GET Only)
Get detailed account information including usage stats and tier details.
curl -X GET https://barcodes.dev/api/v2/account \\ -H "X-API-Key: bcd_your_api_key_here"
{
"success": true,
"account": {
"id": 123,
"email": "user@example.com",
"tier": "free",
"active": true,
"created_at": "2024-01-01T00:00:00",
"monthly_limit": 1000,
"current_usage": 150,
"remaining": 850
}
}
Enhanced Usage Statistics (GET Only)
Get detailed usage statistics with account information and tier details.
curl -X GET https://barcodes.dev/api/v2/usage \\ -H "X-API-Key: bcd_your_api_key_here"
{
"success": true,
"usage": {
"current_hour": 15,
"current_day": 243,
"current_month": 850,
"monthly_limit": 1000,
"remaining": 150,
"reset_date": "2025-11-01T00:00:00Z"
},
"account": {
"tier": "free",
"api_version": "v2"
}
}
Barcode Degradation Testing (v2 Exclusive)
Apply realistic degradation effects to existing barcode images to test scanner robustness. This endpoint only accepts pre-generated barcode images - use the generation endpoints first to create your barcode.
scratches, fading, water_droplets, stains, smudges, partial_removallow_ink, broken_bars, white_noisecylindrical (warping), flexible (wrinkles)metallic (reflection), transparent (overlay)
count: 1-15 (default: 3) - Number of scratchesseverity: 0.1-1.0 (default: 0.5) - Scratch depth (0.1=light, 1.0=deep)angle_range: [min, max] degrees (default: [0, 180]) - Scratch directionscross_modules: true/false (default: true) - Can cross barcode barswidth_range: [min, max] pixels (default: [1, 5]) - Scratch thicknesscontrast_reduction: 0.1-0.9 (default: 0.3) - Amount of fadingpattern: "uniform" | "gradient" | "random" (default: "uniform")center_point: [x, y] 0-1 coords (default: [0.5, 0.5]) - For gradientdroplet_count: 1-20 (default: 5) - Number of dropletssize_range: [min, max] 0.01-0.15 (default: [0.02, 0.15]) - Size as fractionintensity: 0.1-1.0 (default: 0.7) - Droplet opacityrefraction_strength: 0.1-1.0 (default: 0.5) - Distortion strengthstain_count: 1-15 (default: 3) - Number of stainsstain_type: "dirt" | "ink" | "grease" | "food" | "oil" | "coffee" | "mixed"intensity: 0.1-1.0 (default: 0.6) - Stain opacitysize_range: [min, max] 0.01-0.2 (default: [0.03, 0.12]) - Size as fractionsmudge_count: 1-10 (default: 2) - Number of smudgessmudge_type: "finger" | "grease" | "pressure" | "mixed"intensity: 0.1-1.0 (default: 0.4) - Smudge darknessdirection_range: [min, max] degrees (default: [0, 360])size_range: [min, max] 0.05-0.3 (default: [0.08, 0.25])direction: 0-360 degrees (default: 0) - Blur directionintensity: 0.5-10.0 (default: 2.0) - Blur distance in pixelsposition: [x, y] 0-1 coords (default: [0.5, 0.5]) - Glare centerintensity: 0.1-1.0 (default: 0.8) - Glare brightnesssize: 10-200 pixels (default: 50) - Glare radiuslight_direction: "center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right"intensity: 0.1-1.0 (default: 0.3) - Ink spread amountspread_radius: 1-5 pixels (default: 2) - Spread distancestreak_count: 3-20 (default: 8) - Number of white streaksstreak_width_range: [min, max] 1-8 pixels (default: [1, 4])intensity: 0.5-1.0 (default: 0.8) - Streak brightnessvertical_coverage: 0.3-1.0 (default: 0.7) - Height coveragespeckle_density: 0.1-0.8 (default: 0.3) - White speckle densitystreak_count: 5-30 (default: 12) - Number of thin streaksintensity: 0.3-1.0 (default: 0.6) - Effect intensityspeckle_size_range: [min, max] 1-5 pixels (default: [1, 3])noise_density: 0.1-0.8 (default: 0.4) - Noise pixel densityintensity: 0.4-1.0 (default: 0.7) - Noise brightnesscluster_probability: 0.1-0.6 (default: 0.3) - Clustering chancecluster_size_range: [min, max] 2-8 pixels (default: [2, 5])removal_count: 1-5 (default: 1) - Number of removed areassize_range: [min, max] 0.1-0.6 (default: [0.1, 0.3]) - Size as fraction of imageremoval_type: "rectangular" | "circular" | "irregular" | "mixed" (default: "mixed") - Shape of removalcoverage: 0.1-0.6 (default: 0.4) - Maximum fraction of barcode that can be removedradius: 10.0-200.0 (default: 50.0) - Cylinder radius in pixelsaxis: "vertical" | "horizontal" (default: "vertical")wrap_angle: 45.0-360.0 degrees (default: 180.0) - Surface coveragefold_count: 1-8 (default: 3) - Number of wrinklesdepth: 0.1-1.0 (default: 0.5) - Wrinkle depthdirection: "vertical" | "horizontal" | "diagonal" | "random"specularity: 0.1-1.0 (default: 0.7) - Surface shininessroughness: 0.0-1.0 (default: 0.3) - Surface roughnessreflection_count: 1-5 (default: 2) - Number of hotspotsopacity: 0.1-0.9 (default: 0.6) - Overlay transparencyrefraction_index: 1.0-2.0 (default: 1.4) - Material refractionthickness: 0.1-5.0 (default: 1.0) - Overlay thicknessvariants: 1-10 (default: 1) - Number of degraded versionsseed: integer - Random seed for reproducible results๐ก Pro Tip: Combine multiple effects for realistic degradation scenarios. Start with lower intensity values and adjust based on your testing needs.
Step 1: Generate your barcode using any generation endpoint
Step 2: Pass the base64 image data to this degradation endpoint
Step 1: Generate QR Code
curl -X POST https://barcodes.dev/api/v2/qrcode \\
-H "Content-Type: application/json" \\
-H "X-API-Key: bcd_your_api_key_here" \\
-d '{
"text": "https://company.example.com/product/12345",
"error_correction": "H",
"image_format": "PNG",
"output": "base64"
}'
# Response includes: {"success": true, "data": "iVBORw0KGgoAAAANSUhEUgAA...", ...}
Step 2: Apply Water Damage Effects
curl -X POST https://barcodes.dev/api/v2/degrade \\
-H "Content-Type: application/json" \\
-H "X-API-Key: bcd_your_api_key_here" \\
-d '{
"source": {
"image_data": "iVBORw0KGgoAAAANSUhEUgAA..."
},
"degradation": {
"categories": {
"damage": [
{
"type": "water_droplets",
"count": 5,
"size_range": [10, 25],
"refraction_strength": 0.7,
"surface_tension": 0.8
}
]
}
},
"output": {
"format": "base64",
"include_metadata": true
}
}'
# First generate a Code128 barcode, then apply multiple degradation effects
curl -X POST https://barcodes.dev/api/v2/degrade \\
-H "Content-Type: application/json" \\
-H "X-API-Key: bcd_your_api_key_here" \\
-d '{
"source": {
"image_data": "iVBORw0KGgoAAAANSUhEUgAA..."
},
"degradation": {
"categories": {
"damage": [
{
"type": "scratches",
"count": 3,
"severity": 0.5
},
{
"type": "stains",
"count": 2,
"stain_type": "grease",
"opacity_range": [0.3, 0.6]
}
],
"printing": [
{
"type": "low_ink",
"intensity": 0.6,
"pattern": "random"
}
],
"geometry": [
{
"type": "cylindrical",
"radius": 50,
"axis": "vertical"
}
]
},
"global_params": {
"variants": 3,
"preserve_readability": 0.7
}
},
"output": {
"format": "base64",
"include_metadata": true
}
}'
{
"success": true,
"degraded_barcodes": [
{
"variant_id": "variant_001",
"data": "iVBORw0KGgoAAAANSUhEUgAA...",
"format": "PNG",
"degradation_applied": {
"environmental": ["water_droplets", "smudges"],
"physical": ["scratches", "stains"],
"printing": {
"quality_reduction": 0.3
},
"geometry": ["cylindrical"]
}
}
],
"metadata": {
"preset_used": "custom",
"total_variants": 3,
"processing_time_ms": 247.5
}
}
Degradation Presets (v2 Exclusive)
Get predefined degradation preset configurations for common testing scenarios.
curl -X GET https://barcodes.dev/api/v2/presets \\ -H "X-API-Key: bcd_your_api_key_here"
{
"success": true,
"presets": {
"light_damage": {
"name": "Light Damage",
"description": "Minor wear and tear - light environmental effects",
"effects": ["minor_smudges", "light_printing_issues"]
},
"moderate_damage": {
"name": "Moderate Damage",
"description": "Typical handling damage - moderate environmental and physical effects",
"effects": ["water_droplets", "scratches", "reduced_print_quality"]
},
"severe_damage": {
"name": "Severe Damage",
"description": "Heavy degradation - multiple adverse effects",
"effects": ["multiple_stains", "deep_scratches", "poor_print_quality", "smudges"]
}
}
}
This section provides structured information optimized for AI assistants and code generation tools:
API Purpose: Generate barcodes programmatically via REST API
Base URL: https://barcodes.dev
Authentication: v1: None required, v2: API key required
Content-Type: application/json
Response: Binary image data (PNG/JPEG/WEBP) or JSON with base64
Prompt: "Generate a function that creates a Code128 barcode using the barcodes.dev API"
Prompt: "Create error handling for barcode API responses"
Prompt: "Build a React component that generates QR codes with custom colors"
Prompt: "Write a Python script to batch generate barcodes from a CSV file"
Prompt: "Create a function to apply degradation effects to test barcode scanner robustness"
Prompt: "Build a QR code generator with logo overlay and water damage simulation"
{
"api_versions": {
"v1": {
"authentication": "None required",
"rate_limiting": "Fair use policy",
"features": "Basic generation, public access",
"supported_methods": ["POST", "GET"]
},
"v2": {
"authentication": "API key required (X-API-Key header)",
"rate_limiting": "Tier-based limits (1,000/month free)",
"features": "Enhanced responses, batch processing, account management, GET/POST support",
"supported_methods": ["POST", "GET"]
}
},
"v1_endpoints": {
"/api/v1/barcode": {
"methods": ["POST"],
"purpose": "Generate 1D barcodes - Public access",
"required": ["text", "barcode_type"],
"optional": ["image_format", "output"],
"authentication": "None"
},
"/api/v1/qrcode": {
"methods": ["POST"],
"purpose": "Generate QR codes - Public access",
"required": ["text"],
"optional": ["error_correction", "image_format", "fill_color", "back_color", "box_size", "border"],
"authentication": "None"
},
"/api/v1/usage": {
"methods": ["GET"],
"purpose": "Get basic usage statistics",
"required": [],
"optional": [],
"authentication": "None"
},
"/api/v1/version": {
"methods": ["GET"],
"purpose": "Get API version information and features",
"required": [],
"optional": [],
"authentication": "None"
}
},
"v2_endpoints": {
"/api/v2/barcode": {
"methods": ["POST", "GET"],
"purpose": "Generate 1D barcodes with enhanced features",
"required": ["text", "barcode_type"],
"optional": ["image_format", "output"],
"authentication": "API key required"
},
"/api/v2/qrcode": {
"methods": ["POST", "GET"],
"purpose": "Generate QR codes with enhanced features",
"required": ["text"],
"optional": ["error_correction", "image_format", "fill_color", "back_color", "box_size", "border"],
"authentication": "API key required"
},
"/api/v2/2d": {
"methods": ["POST", "GET"],
"purpose": "Generate 2D matrix codes including DataMatrix with DMRE support",
"required": ["text"],
"optional": ["twod_type", "shape", "scale_factor", "image_format", "output"],
"authentication": "API key required"
},
"/api/v2/postal": {
"methods": ["POST", "GET"],
"purpose": "Generate postal barcodes for various national services",
"required": ["text"],
"optional": ["postal_type", "height", "image_format", "output"],
"authentication": "API key required"
},
"/api/v2/stacked": {
"methods": ["POST", "GET"],
"purpose": "Generate stacked barcode formats like PDF417",
"required": ["text"],
"optional": ["stacked_type", "height", "columns", "rows", "image_format", "output"],
"authentication": "API key required"
},
"/api/v2/composite": {
"methods": ["POST", "GET"],
"purpose": "Generate composite barcode symbols with linear and 2D components",
"required": ["text", "primary_data"],
"optional": ["composite_type", "height", "cc_mode", "cc_columns", "image_format", "output"],
"authentication": "API key required"
},
"/api/v2/batch": {
"methods": ["POST"],
"purpose": "Generate multiple barcodes/QR codes in one request (max 10)",
"required": ["batch"],
"optional": [],
"authentication": "API key required"
},
"/api/v2/account": {
"methods": ["GET"],
"purpose": "Get account information and usage statistics",
"required": [],
"optional": [],
"authentication": "API key required"
},
"/api/v2/usage": {
"methods": ["GET"],
"purpose": "Get enhanced usage statistics with account details",
"required": [],
"optional": [],
"authentication": "API key required"
},
"/api/v2/degrade": {
"methods": ["POST"],
"purpose": "Apply degradation effects to existing barcode images",
"required": ["source.image_data", "degradation"],
"optional": ["output"],
"authentication": "API key required"
},
"/api/v2/presets": {
"methods": ["GET"],
"purpose": "Get predefined degradation preset configurations",
"required": [],
"optional": [],
"authentication": "API key required"
}
},
"supported_formats": ["PNG", "JPEG", "WEBP"],
"output_modes": ["file", "base64"],
"error_handling": "HTTP status codes + JSON error messages"
}
Use Case: Generate product barcodes for inventory
Best Endpoint: /api/v1/barcode or /api/v2/barcode
Recommended Types: EAN13, UPC-A, Code128
Use Case: QR codes for document tracking
Best Endpoint: /api/v1/qrcode or /api/v2/qrcode
Features: Custom colors, error correction
Use Case: Generate multiple codes at once
Best Endpoint: /api/v2/batch (API key required)
Features: Up to 10 codes per request, mixed types
Use Case: Monitor API usage and limits
Best Endpoint: /api/v2/account (API key required)
Features: Usage stats, tier information
Use Case: Test barcode scanner robustness
Best Endpoint: /api/v2/degrade (API key required)
Features: Realistic damage effects, logo overlay support
Complete, production-ready examples with error handling and best practices:
AI Context: Production-ready Python function with comprehensive error handling, logging, and type hints. Suitable for integration into web applications, CLI tools, or automation scripts.
import requests
import logging
from typing import Optional, Dict, Any
from pathlib import Path
def generate_barcode(
text: str,
barcode_type: str = 'code128',
image_format: str = 'PNG',
output_path: Optional[str] = None,
base_url: str = 'https://barcodes.dev'
) -> Dict[str, Any]:
"""
Generate a barcode using the barcodes.dev API.
Args:
text: Data to encode in the barcode
barcode_type: Type of barcode (code128, ean13, upca, etc.)
image_format: Output format (PNG, JPEG, WEBP)
output_path: File path to save the barcode (optional)
base_url: API base URL
Returns:
Dict with success status, file path (if saved), and any error info
"""
try:
# Prepare request payload
payload = {
'text': text,
'barcode_type': barcode_type,
'image_format': image_format
}
# Make API request (using v1 for simplicity - no authentication required)
response = requests.post(
f'{base_url}/api/v1/barcode',
json=payload,
timeout=30,
headers={'User-Agent': 'BarcodeGenerator/1.0'}
)
# Handle response
if response.status_code == 200:
# Save to file if path provided
if output_path:
file_path = Path(output_path)
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, 'wb') as f:
f.write(response.content)
logging.info(f"Barcode saved to {file_path}")
return {
'success': True,
'file_path': str(file_path),
'size_bytes': len(response.content)
}
else:
return {
'success': True,
'data': response.content,
'size_bytes': len(response.content)
}
else:
# Parse error response
try:
error_data = response.json()
error_msg = error_data.get('message', 'Unknown error')
except:
error_msg = f"HTTP {response.status_code}"
logging.error(f"Barcode generation failed: {error_msg}")
return {
'success': False,
'error': error_msg,
'status_code': response.status_code
}
except requests.exceptions.RequestException as e:
logging.error(f"Network error: {e}")
return {
'success': False,
'error': f"Network error: {e}"
}
except Exception as e:
logging.error(f"Unexpected error: {e}")
return {
'success': False,
'error': f"Unexpected error: {e}"
}
# Example usage
if __name__ == "__main__":
# Configure logging
logging.basicConfig(level=logging.INFO)
# Generate and save barcode
result = generate_barcode(
text='PROD-12345-ABC',
barcode_type='code128',
output_path='./barcodes/product_12345.png'
)
if result['success']:
print(f"โ
Barcode generated: {result.get('file_path', 'in memory')}")
else:
print(f"โ Error: {result['error']}")
const fs = require('fs');
const fetch = require('node-fetch');
async function generateBarcode() {
const response = await fetch('https://barcodes.dev/api/barcode', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: '123456789012',
barcode_type: 'code128',
image_format: 'PNG'
})
});
if (response.ok) {
const buffer = await response.buffer();
fs.writeFileSync('barcode.png', buffer);
console.log('Barcode saved successfully!');
} else {
const error = await response.json();
console.error('Error:', error);
}
}
generateBarcode();
$data = json_encode([
'text' => '123456789012',
'barcode_type' => 'code128',
'image_format' => 'PNG'
]);
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => $data
]
]);
$response = file_get_contents('https://barcodes.dev/api/barcode', false, $context);
if ($response !== false) {
file_put_contents('barcode.png', $response);
echo "Barcode saved successfully!";
} else {
echo "Error generating barcode";
}
# Generate QR Code
curl -X POST https://barcodes.dev/api/qrcode \\
-H "Content-Type: application/json" \\
-d '{
"text": "https://barcodes.dev",
"error_correction": "M",
"image_format": "PNG"
}' \\
--output qrcode.png
# Generate DataMatrix with DMRE support (API v2)
curl -X POST https://barcodes.dev/api/v2/2d \\
-H "Content-Type: application/json" \\
-H "X-API-Key: bcd_your_api_key_here" \\
-d '{
"text": "Sample data with DMRE",
"twod_type": "datamatrix",
"shape": "dmre",
"image_format": "PNG"
}' \\
--output datamatrix.png
# Generate Postal Code
curl -X POST https://barcodes.dev/api/v2/postal \\
-H "Content-Type: application/json" \\
-H "X-API-Key: bcd_your_api_key_here" \\
-d '{
"text": "12345678901",
"postal_type": "usps_imd",
"image_format": "PNG"
}' \\
--output postal.png
# Apply Degradation Effects for Testing (Step 2)
# Note: First generate QR code using /api/v2/qrcode, then use image_data here
curl -X POST https://barcodes.dev/api/v2/degrade \\
-H "Content-Type: application/json" \\
-H "X-API-Key: bcd_your_api_key_here" \\
-d '{
"source": {
"image_data": "iVBORw0KGgoAAAANSUhEUgAA..."
},
"degradation": {
"categories": {
"damage": [
{
"type": "scratches",
"count": 2,
"severity": 0.4
}
],
"printing": [
{
"type": "low_ink",
"intensity": 0.5
}
]
}
},
"output": {
"format": "base64",
"include_metadata": true
}
}' \\
--output degraded_qr.json
Get the complete OpenAPI 3.0 specification for automatic code generation and interactive documentation:
๐ Download: swagger.yaml
๐ ๏ธ Use Cases:
Use AI chatbots to generate client libraries by providing the OpenAPI specification URL. Here are example prompts:
Create a Python client library for the API defined at https://barcodes.dev/swagger.yaml.
Requirements:
- Support both v1 (public) and v2 (authenticated) endpoints
- Use X-API-Key header for v2 authentication
- Include methods for: barcode generation, QR codes, 2D codes, postal codes, stacked codes, composite codes, and batch processing
- Handle both binary image responses and JSON responses
- Include proper error handling and rate limiting
- Base URL: https://barcodes.dev
Key endpoints to implement:
- POST /api/v1/barcode (public)
- POST /api/v2/barcode (authenticated)
- POST /api/v2/batch (authenticated)
- GET /api/v2/account (authenticated)
Create a JavaScript/Node.js client for the Barcodes.dev API using the OpenAPI spec at https://barcodes.dev/swagger.yaml.
Requirements:
- ES6 class-based client with async/await
- Support for both browser and Node.js environments
- API key authentication for v2 endpoints
- TypeScript type definitions
- Built-in retry logic and error handling
- Examples for all endpoint types
Simply adapt the prompts above for your preferred language (Java, C#, Go, PHP, etc.) and include language-specific requirements.
๐ก Pro Tip: The more specific you are about your requirements (error handling, authentication, response parsing), the better client code you'll get!
๐ Two API Versions Available! Choose between anonymous access (v1) or enhanced authenticated features (v2).
We provide flexible options to support developers and businesses worldwide. To ensure fair access for everyone, please use the API responsibly and follow these guidelines:
While we don't impose hard rate limits, we actively monitor usage patterns. Users who abuse this free service or violate fair use guidelines may face temporary or permanent restrictions, including rate limiting or IP blocking. For high-volume commercial use, please contact us to discuss appropriate solutions that ensure service stability for all users.
We're constantly improving! Send us your feedback to help make the API even better.