How to Generate Custom QR Codes with Python
QR codes are everywhere. They handle contactless restaurant menus, physical tickets, inventory tags, and quick-login screens. But while adding a static QR code is easy, generating custom, dynamic, styled QR codes programmatically on your backend can quickly turn into an operational bottleneck.
Using the QR Code Generator on Apify, you can generate perfectly styled, high-resolution QR codes with a single API call. Here is how to build a dynamic QR code generator pipeline using Python.
The Messy State of Server-Side QR Code Generation
Most Python developers start by looking up a native QR library. The standard path is to pip-install qrcode and Pillow. While this works fine on a local development machine, moving it to production brings several immediate challenges.
Pillow is a heavy graphics library with native C dependencies. If you deploy your application to AWS Lambda, Google Cloud Functions, or an Alpine Linux Docker container, compiling these dependencies often fails or requires installing extra system packages.
Furthermore, styling the QR codes — adding custom brand colors, adjusting margins, or exporting high-quality SVG formats instead of standard PNGs — requires writing complex graphics manipulation code. If your backend needs to serve hundreds of dynamic codes concurrently, running the generation code on your main server thread blocks event loops and degrades performance.
Delegating this work to a dedicated microservice API eliminates these headaches. Your server stays lightweight, you don't need any complex system dependencies, and you can focus entirely on your core application logic.
Programmatic QR Code Generation
The QR Code Generator takes parameters such as the raw text, size, color, background color, margin size, image format (PNG, SVG, or JPEG), and error correction level, and returns the generated QR image directly or uploads it to a dataset.
Here is how to request and save a custom QR code using Python and the requests library.
import requests
API_TOKEN = "YOUR_APIFY_TOKEN"
ACTOR_ID = "weeknds~qr-code-generator"
def generate_qr_code(text, filename="qr_code.png", color="#000000", bg_color="#ffffff", size=300, format="png"):
url = f"https://api.apify.com/v2/acts/{ACTOR_ID}/run-sync-get-dataset-items?token={API_TOKEN}"
# Configure the payload with custom styles
payload = {
"text": text,
"size": size,
"color": color,
"backgroundColor": bg_color,
"format": format,
"margin": 4,
"errorCorrectionLevel": "H" # High error correction allows damage/overlay
}
# Run the actor synchronously
response = requests.post(url, json=payload)
response.raise_for_status()
results = response.json()
if not results:
raise Exception("Failed to generate QR code")
# The actor returns the image in base64 format or as a direct file link
qr_data = results[0]
image_url = qr_data.get("fileUrl")
# Download the generated image file
img_response = requests.get(image_url)
img_response.raise_for_status()
with open(filename, "wb") as f:
f.write(img_response.content)
print(f"Successfully saved custom QR code to {filename}")
# Generate a brand-colored QR code
generate_qr_code(
text="https://apify.com",
filename="apify_qr.png",
color="#FF5733", # Custom orange/red hex color
bg_color="#FFFFFF",
size=400
)
By requesting the output synchronously, you can fetch, save, and serve the QR code file in under two seconds.
Dynamic Ticket Generation and Delivery
For event platforms or ticketing engines, each attendee needs a unique QR code containing their reservation ID. This code must be generated dynamically on booking and sent in a confirmation email.
Here is how to structure a reservation workflow that generates a styled QR code for a new booking:
import json
import uuid
def process_ticket_booking(user_email, event_name, ticket_type):
# Create a unique reservation ID
reservation_id = str(uuid.uuid4())
# Encode structured ticket details in the QR code
ticket_payload = {
"reservation_id": reservation_id,
"event": event_name,
"type": ticket_type,
"email": user_email
}
qr_payload_string = json.dumps(ticket_payload)
# File naming convention
filename = f"tickets/ticket_{reservation_id}.png"
# Generate the styled QR code matching event branding
# Using high error correction so it scans even if folded or slightly scuffed
try:
generate_qr_code(
text=qr_payload_string,
filename=filename,
color="#2E4053", # Deep slate gray
bg_color="#FADBD8", # Soft pastel pink
size=350
)
return {
"status": "success",
"reservation_id": reservation_id,
"ticket_file": filename,
"message": "Ticket QR generated and saved."
}
except Exception as e:
return {
"status": "error",
"reason": str(e)
}
This ensures that every ticket issued is uniquely trackable, visually unique, and instantly ready for check-in scanners.
Batch Inventory QR Code Creator
If you are setting up an inventory tracking system, you likely have a CSV sheet containing hundreds of asset IDs. You need to convert all of them into physical labels.
Running these lookups in a loop is simple, but we should handle API rate limits and organize the outputs efficiently.
import csv
import time
import os
def generate_inventory_labels(csv_filepath, output_dir="labels"):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(csv_filepath, mode="r", encoding="utf-8") as file:
reader = csv.DictReader(file)
for idx, row in enumerate(reader):
asset_id = row.get("asset_id")
asset_name = row.get("name")
if not asset_id:
continue
# Create descriptive filenames
clean_name = asset_name.lower().replace(" ", "_")
filename = os.path.join(output_dir, f"{asset_id}_{clean_name}.png")
print(f"Processing label [{idx + 1}]: {asset_name} ({asset_id})...")
try:
generate_qr_code(
text=f"https://inventory.internal/assets/{asset_id}",
filename=filename,
color="#111111",
bg_color="#FFFFFF",
size=250
)
# Polite delay to respect API rate limits
time.sleep(0.5)
except Exception as e:
print(f"Error processing asset {asset_id}: {e}")
continue
# Mock CSV structure
# asset_id,name
# AST-992,MacBook Pro M3
# AST-993,Office Chair Herman Miller
# AST-994,Dell UltraSharp 27 Monitor
This allows you to quickly export a folder of ready-to-print labels that can be applied to physical office assets or stock warehouse boxes.
Pricing
The QR Code Generator costs $0.001 per run. Generating 10,000 unique ticket or asset labels costs exactly $10. With no base server subscription costs or infrastructure maintenance, you only pay for the exact volume of QR codes your platform generates.
Integrating the API
Generating custom, styled graphics does not require building heavy infrastructure or managing system library complications. By calling the QR generation endpoint directly, you can programmatically produce styled vector or raster files using minimal code.
Top comments (0)