← All posts

2026-08-31

Python Barcode Label Generation: A Step-by-Step Guide

Python Barcode Label Generation: A Step-by-Step Guide
pdf labels barcodes label merge browser based graphical layout editor google sheets addin microsoft excel addon electronic shelf labels esl

Python Barcode Label Generation: A Step-by-Step Guide

If you’ve ever tried to generate a barcode label from a Python script, you know the usual path: pick a barcode library, render an image, build the label layout yourself, then figure out how to talk to a thermal printer. This guide takes a different, managed approach. You’ll use the Next Generation Label Printing System (LPSNG) as the rendering and printing engine, and drive it from Python with plain HTTP requests.

By the end, you’ll have a Python script that:

  • Authenticates against the LPSNG web service API
  • Looks up a label layout
  • Sends dynamic item data, including barcode content
  • Applies Python-based field customizations
  • Renders the label as PDF or PNG
  • Sends it to a printer or saves it locally

This is ideal for developers who need data-driven label generation in warehouse, logistics, retail, or fulfillment workflows — without building and maintaining a custom label rendering pipeline.

Prerequisites

Before you start, make sure you have:

  • Python 3.x installed on your machine.
  • An LPSNG account — either the cloud edition or an embedded edition — with access to the web service API.
  • A label layout created in the LPSNG label studio, or a sample layout you can use for testing. The layout should contain at least one barcode field.
  • OAuth2 client credentials for API authentication. See the OAuth2 guide for the simplified registration flow.
  • Basic familiarity with Python and REST APIs. The LPSNG web service is RESTful and returns JSON, so standard HTTP knowledge is enough.

You don’t need to install barcode fonts, ZPL/EPL drivers, or printer-specific SDKs. LPSNG handles those details behind its web service.

Step-by-Step: Generating Barcode Labels with Python

The workflow is straightforward: authenticate, identify the layout, prepare the data, optionally customize fields with a Python script block, render the label, and print or save it.

Step 1: Set up your Python environment

Create a project directory and install the requests library. The LPSNG API is RESTful, so you only need a standard HTTP client.

mkdir lpsng-python-labeling
cd lpsng-python-labeling
python -m venv venv
source venv/bin/activate  # or venv\Scripts\activate on Windows
pip install requests

Create a file named generate_label.py. At the top, define your LPSNG base URL and credentials. Replace the placeholder values with your actual instance details.

import requests
import json
from pathlib import Path

# Replace with your LPSNG instance URL, e.g. https://your-instance.lpsng.rsj.de
LPSNG_BASE_URL = "https://your-instance.lpsng.rsj.de"

# Replace with the credentials from your OAuth2 registration
CLIENT_ID = "your-client-id"
CLIENT_SECRET = "your-client-secret"

Step 2: Obtain an OAuth2 access token

LPSNG uses a simplified OAuth2 registration protocol. Once your external application is registered, you exchange your client credentials for an access token.

The example below keeps the token endpoint as a variable, so you can point it at the exact URL from the Web Service API documentation for your instance.

def get_access_token():
    # Use the token endpoint listed in the LPSNG OAuth2 guide.
    token_url = f"{LPSNG_BASE_URL}/oauth2/token"

    response = requests.post(
        token_url,
        data={
            "grant_type": "client_credentials",
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
        },
        timeout=30,
    )
    response.raise_for_status()
    return response.json()["access_token"]

In production code, cache the token and refresh it before it expires. For this walkthrough, you can request a new token each time.

Step 3: Retrieve your label layout ID

Each label layout in LPSNG has an ID. You can copy it from the LPSNG web UI by opening the layout properties, or you can query it through the API.

The web UI path is simplest for a first test. Open your label layout in the label studio and copy the layout ID from the URL or the layout settings.

If you want to automate layout lookup from Python, use the same REST pattern. The exact endpoint may vary by instance, so fill it in from your API reference:

def find_layout_id(token, layout_name):
    headers = {"Authorization": f"Bearer {token}"}

    # Replace /layouts with the list endpoint documented for your instance.
    response = requests.get(
        f"{LPSNG_BASE_URL}/layouts",
        headers=headers,
        timeout=30,
    )
    response.raise_for_status()

    for layout in response.json():
        if layout.get("name") == layout_name:
            return layout["id"]

    raise ValueError(f"Layout not found: {layout_name}")

For a quick script, a hardcoded layout ID is fine:

LAYOUT_ID = "your-layout-id"

Step 4: Prepare the data payload with barcode content

The web service API submits print jobs and renders single labels. Your payload typically contains a set of field values for the layout, including the value that should be encoded in the barcode.

Here is an example payload for an item label with a Code 128 barcode:

label_data = {
    "product_name": "Thermal Label Roll 100x150",
    "sku": "THR-100-150",
    "barcode": "4012345678901",
    "quantity": 12,
    "batch": "B20260831-04",
}

The field names in your payload must match the field names you defined in the LPSNG label studio. If your layout has a barcode field named barcode, LPSNG encodes the value you send for that field in the barcode format configured in the layout.

Step 5: Customize fields with the Python Field Script API

LPSNG includes a Python Field Script API that lets you attach small Python script blocks to label fields. Those scripts run before printing and can access or modify field values.

For example, suppose your warehouse data sometimes contains lowercase barcodes or trailing spaces, and you want to normalize the value before it reaches the barcode. In the LPSNG label studio, attach a script block to the barcode field that looks like this:

# Attached to the barcode field in LPSNG Label Studio.
# The script runs before printing and can access the current value.
if "barcode" in context:
    value = str(context["barcode"]).strip().upper()

The exact entry point and available objects are documented in the Python API reference. Use that reference to verify the exact hook signature for your LPSNG version. The key idea is that field-level Python scripts keep formatting logic close to the label, while your external Python application stays focused on data preparation and API calls.

Step 6: Call the web service endpoint to render the label

Now call LPSNG to render the label as a PDF or PNG. The web service API can render single labels, so you don’t need to run a local renderer.

def render_label(token, layout_id, data, output_format="pdf"):
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json",
    }

    # Use the render endpoint from the LPSNG Web Service API docs.
    render_url = f"{LPSNG_BASE_URL}/render"

    response = requests.post(
        render_url,
        headers=headers,
        json={
            "layout_id": layout_id,
            "data": data,
            "format": output_format,
        },
        timeout=60,
    )
    response.raise_for_status()
    return response.content

For PNG output, pass "png" as the format. The API response contains the binary file content, which you can save directly.

token = get_access_token()
pdf_bytes = render_label(token, LAYOUT_ID, label_data, "pdf")

Path("label.pdf").write_bytes(pdf_bytes)
print("Label rendered: label.pdf")

Step 7: Send the generated label to a printer or save it locally

If your LPSNG instance is connected to printers, you can submit a print job through the same web service API instead of downloading the file. The exact request shape is documented in the Web Service Interface.

A typical direct-print call follows the same REST pattern:

def send_to_printer(token, layout_id, data, printer_name):
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json",
    }

    # Use the print endpoint documented for your LPSNG instance.
    print_url = f"{LPSNG_BASE_URL}/print"

    response = requests.post(
        print_url,
        headers=headers,
        json={
            "layout_id": layout_id,
            "data": data,
            "printer": printer_name,
        },
        timeout=60,
    )
    response.raise_for_status()
    return response.json()

Replace "printer" with the printer name or ID configured in your LPSNG environment. If you prefer to keep the file locally, skip this step and use the PDF or PNG output from Step 6.

Verifying Your Label Output

Don’t assume the barcode is correct just because the PDF or PNG opened without errors. Run these checks:

  • Open the generated file visually. Confirm the text fields are populated, the barcode is visible, and the layout matches your label studio design.
  • Scan the barcode with a scanner app. Point a phone-based barcode scanner at the printed or on-screen barcode. Verify that the encoded data matches the value you sent in the payload.
  • Check field customizations. If you added a Python field script that uppercases or trims the barcode value, send lowercase or padded test data and confirm the output changed as expected.
  • Test with multiple data sets. Run the script with different SKUs, quantities, and barcode values to ensure no field is hardcoded or misaligned.

If your output is a PDF, print it once on the target thermal printer to confirm label dimensions and print density.

Troubleshooting Common Issues

Authentication errors

Double-check your OAuth2 client credentials and token endpoint. If the token has expired, request a new one. Confirm that the client is still registered in your LPSNG account and that the account has API access.

Label layout not found

Verify the layout ID and the user permissions associated with your OAuth2 client. The client may have access to the API but not to the specific layout. Check the layout name exactly, including case and whitespace.

Barcode not rendering

Ensure the barcode format is supported by LPSNG and that the value in the barcode field is valid for that format. For example, a Code 128 field should receive data that is valid for Code 128. See the Barcode Formats documentation for the complete list of supported 1D and 2D formats.

Also check that the barcode field in your layout is actually mapped to the payload key you are sending. A mismatch between field names is a common cause of empty barcodes.

Field script errors

If your Python field script raises an error, the API response usually contains an error message. Read it carefully; it often points to the line number or exception type in the script block. Use the Python API reference to confirm which objects are available in the script context.

Printing issues

If the label renders but doesn’t print, confirm the printer connectivity and driver setup in your LPSNG environment. Check that the printer name in your print call matches the name configured in LPSNG, and that the printer is online.

FAQ

Can I generate barcode labels in Python without using the LPSNG web service?

Yes, you could use raw libraries like python-barcode or reportlab, but you would need to handle label design, printer communication, and barcode standards yourself. LPSNG provides a managed service with a Python API that simplifies the entire process, including field customization and direct printing.

What barcode formats are supported by LPSNG?

LPSNG supports a wide range of 1D and 2D barcode formats. Refer to the Barcode Formats documentation for the complete list, including Code 128, QR Code, Data Matrix, and more.

Do I need to install any special Python packages to use the LPSNG API?

Only standard HTTP client libraries like requests are needed. The API is RESTful and returns JSON responses, making it easy to integrate with any Python environment.

Can I use the Python API to update electronic shelf labels (ESL) as well?

Yes, LPSNG offers an ESL interface and binding API that can be accessed via Python. Check the ESL documentation for details on updating ESL displays programmatically.

Conclusion

Python barcode label generation becomes much simpler when you let a managed service handle the rendering, barcode standards, and printing details. With LPSNG, your Python application only needs to authenticate, send field data, and call a REST endpoint. The label design stays in the label studio, while Python field scripts handle field-level formatting.

This approach fits neatly into larger automation workflows. If you’re evaluating label software as a developer, see Best Label Design Software for Developers: Why LPSNG Stands Out. If your labeling project extends to electronic shelf tags, continue with ESL Integration for Retail: A Complete Guide. And if most of your source data lives in spreadsheets, don’t miss Automate Label Printing from Excel: Save Time and Reduce Errors.

Ready to build your first Python-generated barcode label? Grab your OAuth2 credentials, pick a layout, and run the script with a real item. The Next Generation Label Printing System handles the heavy lifting — you write the integration.

Related posts

EU label: AI-generated content