Generate Barcode
Generate barcodes for shipping labels, inventory management, and product identification. This endpoint supports multiple barcode formats and returns the barcode as a base64-encoded image.
/API/v2/barcode.php
Cost: $0.001 per barcode generation
Rate Limit: 60 requests per minute
Supported Formats: CODE128, CODE39, EAN13, UPC, QR Code
Barcode Requirements
- Data must be valid for the specified format
- Maximum length varies by format
- Returns base64-encoded PNG image
- Default size: 200x100 pixels
Authentication
This endpoint requires Bearer token authentication. Include your API key in the Authorization header.
curl -X POST https://developers.labelscheap.com/API/v2/barcode.php \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "X-Requested-With: XMLHttpRequest" \
-d '{"barcode": "123456789", "format": "CODE128"}'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://developers.labelscheap.com/API/v2/barcode.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer YOUR_API_KEY',
'X-Requested-With: XMLHttpRequest'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'barcode' => '123456789',
'format' => 'CODE128'
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
import requests
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY',
'X-Requested-With': 'XMLHttpRequest'
}
data = {
'barcode': '123456789',
'format': 'CODE128'
}
response = requests.post(
'https://developers.labelscheap.com/API/v2/barcode.php',
headers=headers,
json=data
)
data = response.json()
fetch('https://developers.labelscheap.com/API/v2/barcode.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY',
'X-Requested-With': 'XMLHttpRequest'
},
body: JSON.stringify({
barcode: '123456789',
format: 'CODE128'
})
})
.then(response => response.json())
.then(data => console.log(data));
Request
This endpoint accepts a POST request with barcode generation parameters in the JSON body.
Headers
| Header | Required | Description |
|---|---|---|
Content-Type |
Yes | Must be application/json |
Authorization |
Yes | Bearer token with your API key |
X-Requested-With |
Yes | Must be XMLHttpRequest |
Request Body
| Field | Type | Required | Description |
|---|---|---|---|
barcode |
string | Yes | The data to encode in the barcode |
format |
string | No | Barcode format (default: CODE128) |
width |
integer | No | Image width in pixels (default: 200) |
height |
integer | No | Image height in pixels (default: 100) |
Supported Barcode Formats
| Format | Description | Max Length | Use Case |
|---|---|---|---|
CODE128 |
Alphanumeric barcode | Variable | Shipping labels, inventory |
CODE39 |
Alphanumeric barcode | Variable | Industrial applications |
EAN13 |
13-digit numeric | 13 | Retail products |
UPC |
12-digit numeric | 12 | US retail products |
QR |
2D QR code | Variable | URLs, contact info |
Example Request Body
{
"barcode": "123456789",
"format": "CODE128",
"width": 300,
"height": 150
}
Response
The response includes the generated barcode as a base64-encoded PNG image and metadata about the generation.
Success Response
{
"STATUS": "success",
"MESSAGE": "Barcode generated successfully",
"CODE": "200",
"DATA": {
"barcode": "123456789",
"format": "CODE128",
"image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
"width": 300,
"height": 150,
"amount_deducted": 0.001
},
"TIMESTAMP": "2024-01-15 10:30:00"
}
Response Fields
| Field | Type | Description |
|---|---|---|
STATUS |
string | Always "success" for successful requests |
MESSAGE |
string | Human-readable success message |
CODE |
string | HTTP status code as string |
DATA.barcode |
string | The original barcode data |
DATA.format |
string | The barcode format used |
DATA.image |
string | Base64-encoded PNG image data |
DATA.width |
integer | Image width in pixels |
DATA.height |
integer | Image height in pixels |
DATA.amount_deducted |
number | Amount deducted from account balance |
TIMESTAMP |
string | ISO 8601 timestamp of the response |
Code Examples
Here are complete examples for different programming languages:
<?php
class LabelsCheapAPI {
private $apiKey;
private $baseUrl = 'https://developers.labelscheap.com/API/v2/';
public function __construct($apiKey) {
$this->apiKey = $apiKey;
}
public function generateBarcode($barcodeData, $format = 'CODE128', $width = 200, $height = 100) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->baseUrl . 'barcode.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $this->apiKey,
'X-Requested-With: XMLHttpRequest'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'barcode' => $barcodeData,
'format' => $format,
'width' => $width,
'height' => $height
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
public function saveBarcodeImage($imageData, $filename) {
// Remove data:image/png;base64, prefix
$base64Data = str_replace('data:image/png;base64,', '', $imageData);
$imageData = base64_decode($base64Data);
return file_put_contents($filename, $imageData);
}
}
// Usage
try {
$api = new LabelsCheapAPI('YOUR_API_KEY');
$result = $api->generateBarcode('123456789', 'CODE128', 300, 150);
if ($result['STATUS'] === 'success') {
echo "Barcode generated successfully!\n";
echo "Format: " . $result['DATA']['format'] . "\n";
echo "Size: " . $result['DATA']['width'] . "x" . $result['DATA']['height'] . "\n";
echo "Amount deducted: $" . $result['DATA']['amount_deducted'] . "\n";
// Save the barcode image
$api->saveBarcodeImage($result['DATA']['image'], 'barcode.png');
echo "Barcode saved as barcode.png\n";
} else {
echo "Error: " . $result['MESSAGE'] . "\n";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
?>
import requests
import base64
import json
class LabelsCheapAPI:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = 'https://developers.labelscheap.com/API/v2/'
self.headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}',
'X-Requested-With': 'XMLHttpRequest'
}
def generate_barcode(self, barcode_data, format='CODE128', width=200, height=100):
try:
response = requests.post(
f'{self.base_url}barcode.php',
headers=self.headers,
json={
'barcode': barcode_data,
'format': format,
'width': width,
'height': height
},
timeout=30
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
raise Exception(f'Request failed: {str(e)}')
except json.JSONDecodeError as e:
raise Exception(f'Invalid JSON response: {str(e)}')
def save_barcode_image(self, image_data, filename):
# Remove data:image/png;base64, prefix
base64_data = image_data.replace('data:image/png;base64,', '')
image_bytes = base64.b64decode(base64_data)
with open(filename, 'wb') as f:
f.write(image_bytes)
# Usage
try:
api = LabelsCheapAPI('YOUR_API_KEY')
result = api.generate_barcode('123456789', 'CODE128', 300, 150)
if result['STATUS'] == 'success':
print("Barcode generated successfully!")
print(f"Format: {result['DATA']['format']}")
print(f"Size: {result['DATA']['width']}x{result['DATA']['height']}")
print(f"Amount deducted: ${result['DATA']['amount_deducted']}")
# Save the barcode image
api.save_barcode_image(result['DATA']['image'], 'barcode.png')
print("Barcode saved as barcode.png")
else:
print(f"Error: {result['MESSAGE']}")
except Exception as e:
print(f"Error: {str(e)}")
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
public class LabelsCheapAPI
{
private readonly string _apiKey;
private readonly string _baseUrl = "https://developers.labelscheap.com/API/v2/";
private readonly HttpClient _httpClient;
public LabelsCheapAPI(string apiKey)
{
_apiKey = apiKey;
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
_httpClient.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
}
public async Task<dynamic> GenerateBarcodeAsync(string barcodeData, string format = "CODE128", int width = 200, int height = 100)
{
try
{
var requestData = new {
barcode = barcodeData,
format = format,
width = width,
height = height
};
var json = JsonConvert.SerializeObject(requestData);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync($"{_baseUrl}barcode.php", content);
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject(responseContent);
}
catch (HttpRequestException ex)
{
throw new Exception($"Request failed: {ex.Message}");
}
catch (JsonException ex)
{
throw new Exception($"Invalid JSON response: {ex.Message}");
}
}
public void SaveBarcodeImage(string imageData, string filename)
{
// Remove data:image/png;base64, prefix
var base64Data = imageData.Replace("data:image/png;base64,", "");
var imageBytes = Convert.FromBase64String(base64Data);
File.WriteAllBytes(filename, imageBytes);
}
}
// Usage
public class Program
{
public static async Task Main()
{
try
{
var api = new LabelsCheapAPI("YOUR_API_KEY");
var result = await api.GenerateBarcodeAsync("123456789", "CODE128", 300, 150);
if (result.STATUS == "success")
{
Console.WriteLine("Barcode generated successfully!");
Console.WriteLine($"Format: {result.DATA.format}");
Console.WriteLine($"Size: {result.DATA.width}x{result.DATA.height}");
Console.WriteLine($"Amount deducted: ${result.DATA.amount_deducted}");
// Save the barcode image
api.SaveBarcodeImage(result.DATA.image.ToString(), "barcode.png");
Console.WriteLine("Barcode saved as barcode.png");
}
else
{
Console.WriteLine($"Error: {result.MESSAGE}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
class LabelsCheapAPI {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://developers.labelscheap.com/API/v2/';
this.headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
'X-Requested-With': 'XMLHttpRequest'
};
}
async generateBarcode(barcodeData, format = 'CODE128', width = 200, height = 100) {
try {
const response = await fetch(`${this.baseUrl}barcode.php`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify({
barcode: barcodeData,
format: format,
width: width,
height: height
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
throw new Error(`Request failed: ${error.message}`);
}
}
saveBarcodeImage(imageData, filename) {
// Remove data:image/png;base64, prefix
const base64Data = imageData.replace('data:image/png;base64,', '');
// Convert base64 to blob and download
const byteCharacters = atob(base64Data);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], { type: 'image/png' });
// Create download link
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}
}
// Usage
async function main() {
try {
const api = new LabelsCheapAPI('YOUR_API_KEY');
const result = await api.generateBarcode('123456789', 'CODE128', 300, 150);
if (result.STATUS === 'success') {
console.log('Barcode generated successfully!');
console.log(`Format: ${result.DATA.format}`);
console.log(`Size: ${result.DATA.width}x${result.DATA.height}`);
console.log(`Amount deducted: $${result.DATA.amount_deducted}`);
// Save the barcode image
api.saveBarcodeImage(result.DATA.image, 'barcode.png');
} else {
console.log(`Error: ${result.MESSAGE}`);
}
} catch (error) {
console.error(`Error: ${error.message}`);
}
}
main();
Request Tester
Test the barcode generation endpoint with your API key:
Common Error Responses
Here are the most common error responses you might encounter:
Invalid Barcode Format (422)
{
"STATUS": "error",
"MESSAGE": "Invalid barcode format",
"CODE": "2015",
"HTTP_STATUS": 422,
"DATA": {},
"TIMESTAMP": "2024-01-15 10:30:00"
}
Invalid Barcode Data (422)
{
"STATUS": "error",
"MESSAGE": "Invalid barcode data for specified format",
"CODE": "2005",
"HTTP_STATUS": 422,
"DATA": {},
"TIMESTAMP": "2024-01-15 10:30:00"
}
Insufficient Balance (402)
{
"STATUS": "error",
"MESSAGE": "Insufficient balance for this operation",
"CODE": "3001",
"HTTP_STATUS": 402,
"DATA": {},
"TIMESTAMP": "2024-01-15 10:30:00"
}
Barcode Service Unavailable (503)
{
"STATUS": "error",
"MESSAGE": "Barcode generation service is unavailable",
"CODE": "5013",
"HTTP_STATUS": 503,
"DATA": {},
"TIMESTAMP": "2024-01-15 10:30:00"
}
Error Handling Best Practices
- Validate barcode data before sending requests
- Check format requirements for each barcode type
- Handle rate limiting by implementing exponential backoff
- Implement retry logic for transient errors (5xx status codes)
- Check account balance before making barcode generation requests
- Display user-friendly error messages based on the error code