Skip to main content
QR Code API: Copy-Paste Examples [JS, Python, PHP]
DevelopersLast updated: 16 February 202610 min read

QR Code API: Copy-Paste Examples [JS, Python, PHP]

M

Marc

QR-Verse Team

A QR code API lets you generate QR codes programmatically - from your web application, mobile app, backend system, or automation pipeline. Instead of manually creating QR codes one at a time through a web interface, you send an HTTP request and get a QR code image back in milliseconds. If you need to generate QR codes at scale, integrate them into your product, or automate workflows that involve physical-to-digital bridges, an API is the way to do it.

This guide covers the best places to integrate a QR code API in web, mobile, and backend systems. You will learn how QR code APIs work, see copy-paste code examples in four languages, compare the top providers, and walk away with production-ready best practices. Whether you are building an e-commerce checkout, a shipping label system, or a marketing automation pipeline, this is your complete reference for QR code API integration.


Why Integrate QR Codes via API?

Manual QR code creation works when you need a handful of codes. But the moment your business scales - hundreds of product labels, thousands of event tickets, personalized marketing mailers - manual creation becomes a bottleneck.

Here is what an API unlocks:

  • Automation. Generate QR codes as part of your existing workflows. A new order triggers a shipping label with a QR code. A new user gets a personalized onboarding QR code. No human intervention.
  • Scale. Create 10,000 QR codes in minutes, not days. Bulk generation endpoints process batches efficiently.
  • Dynamic content. Dynamic QR codes let you change the destination URL after the code is printed. The API gives you full control over creating and updating these codes programmatically.
  • Consistency. Every QR code follows the same design, error correction level, and branding guidelines. No one-off mistakes.
  • Analytics. Track every scan with timestamp, location, and device data. API-generated dynamic codes feed into your analytics pipeline automatically.
i

If you are new to the difference between static and dynamic QR codes, read our complete comparison guide first. For API integration, dynamic QR codes are almost always the right choice because you can update destinations without reprinting.


Best Places to Integrate QR Code API in Web, Mobile, and Backend Systems

This is the section most developers are searching for. Here are the six most impactful integration points, with concrete examples and architecture guidance for each.

Web Applications

E-commerce platforms are the highest-impact integration point. Generate a unique QR code for every order confirmation page, packing slip, and digital receipt. When scanned, the QR code can link to order tracking, a return portal, or a product review page.

SaaS dashboards that serve businesses benefit enormously from embedded QR generation. Let your users create branded QR codes without leaving your platform - whether that is a restaurant management system generating menu QR codes, a CRM creating vCard QR codes for sales reps, or a booking platform producing confirmation codes.

Booking and reservation systems can attach a QR code to every confirmation email and check-in page. Hotels, airlines, and event venues use API-generated QR codes as digital boarding passes and check-in tokens.

Implementation pattern for web apps:

// Server-side route handler (Next.js API route example)
export async function POST(request) {
  const { url, label } = await request.json()

  const response = await fetch('https://api.qr-verse.com/v1/qr-codes', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.QR_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      type: 'url',
      data: url,
      options: {
        size: 512,
        format: 'png',
        errorCorrection: 'H',
        label: label
      }
    })
  })

  const qrCode = await response.json()
  return Response.json(qrCode)
}
!

Never call a QR code API directly from client-side JavaScript. Your API key would be visible in the browser's developer tools. Always proxy requests through your backend server.

Mobile Apps

Mobile is where QR codes shine because the camera is right there. If your app generates QR codes for users to share, an API call from your backend is cleaner and more reliable than a client-side library.

React Native and Flutter apps should call your backend, which then calls the QR code API. The backend returns the QR code image (as a URL or base64 string) to the mobile client. This keeps your API key secure and lets you add caching.

Native iOS and Android apps follow the same pattern. Your Swift or Kotlin code sends a request to your own API endpoint, which handles the QR code generation server-side.

Common mobile use cases:

  • Digital loyalty cards - each customer gets a unique QR code that the cashier scans
  • Peer-to-peer sharing - share a contact card, WiFi password, or payment link as a QR code
  • Ticket wallets - event tickets with scannable QR codes for entry
  • Business card apps - generate vCard QR codes from contact data

Backend Systems

Backend integration is where QR code APIs deliver the most value at scale. These are systems where no human is clicking "generate" - the QR codes are created as part of automated business processes.

CRM systems (Salesforce, HubSpot, custom) - attach a QR code to every new contact record. Sales reps can print a sheet of personalized QR codes linking to their calendar booking page. See our marketing guide for more QR strategies in customer acquisition.

ERP and inventory systems - generate QR codes for asset tracking, warehouse bin locations, and work-in-progress routing. Each item gets a unique code linking to its full history. Read more about QR codes for product packaging.

Shipping and logistics - create QR codes for shipping labels that link to real-time tracking pages. Unlike barcodes, QR codes can encode enough data for a full tracking URL with query parameters.

import requests

def generate_shipping_qr(tracking_number, carrier):
    """Generate a QR code for a shipping label."""
    tracking_url = f"https://yoursite.com/track/{carrier}/{tracking_number}"

    response = requests.post(
        "https://api.qr-verse.com/v1/qr-codes",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json={
            "type": "url",
            "data": tracking_url,
            "options": {
                "size": 256,
                "format": "svg",
                "errorCorrection": "M"
            }
        }
    )

    return response.json()["image_url"]

Marketing Automation

Marketing teams need QR codes in email campaigns, landing pages, direct mail, and social media posts. An API integration with your marketing platform means every campaign asset gets a trackable QR code automatically.

Email marketing platforms (Mailchimp, SendGrid, custom) - embed a unique QR code in each email that links to a personalized landing page. Track which recipients scanned vs. clicked. This is a powerful attribution signal that most marketers miss.

Landing page builders - dynamically generate QR codes on landing pages so visitors can switch from desktop to mobile seamlessly. The QR code links to the same page, pre-filled with the visitor's session data.

Direct mail automation - services like Lob and PostGrid can include API-generated QR codes in printed mailers. Each piece gets a unique code for response tracking.

For marketing attribution, always use dynamic QR codes with UTM parameters baked into the destination URL. This lets you see QR code scans alongside other traffic sources in Google Analytics. Learn more in our analytics tracking guide.

Point of Sale and Retail Systems

Retail is one of the fastest-growing QR code integration points. Modern POS systems use QR codes for contactless payments, digital receipts, loyalty programs, and product information.

Digital receipts - instead of printing a paper receipt, display a QR code on the terminal screen. The customer scans it to get their receipt on their phone. Works for sustainability-conscious brands and reduces paper costs.

Product displays - generate QR codes for shelf labels that link to detailed product pages, reviews, and comparison tools. Update the destination URL seasonally without reprinting labels.

Loyalty programs - each customer gets a persistent QR code that the cashier scans to apply points. The same code works across all locations. See our loyalty program guide for detailed strategies.

Event Management Platforms

Events generate massive volumes of QR codes - one per ticket, per attendee, per session. API integration is the only practical approach at this scale.

Ticketing systems - generate a unique QR code for every ticket sold. The code encodes a ticket ID that your door scanning system validates in real time. For implementation details, read our event ticketing QR code guide.

Conference apps - attendee badges with QR codes for session check-in, lead scanning at booths, and networking (scan someone's badge to exchange contact info).

Virtual and hybrid events - QR codes on screen during live streams that link to polls, Q&A pages, or exclusive content.


How QR Code APIs Work

If you have used any REST API, you already know how QR code APIs work. The core flow is straightforward:

  1. Authenticate - include your API key in the request header
  2. Send a POST request - specify the QR code type, content data, and design options
  3. Receive the response - get back an image URL, base64 data, or a binary image file
  4. Use the QR code - embed it in your app, email, PDF, or print layout

Authentication

Most QR code APIs use one of two authentication methods:

MethodExampleBest For
Bearer tokenAuthorization: Bearer sk_live_abc123Server-to-server calls
API key parameter?apikey=abc123Quick testing (not production)

Always use bearer tokens in production. API key parameters appear in server logs and URL history.

Request and Response Cycle

A typical QR code generation request looks like this:

curl -X POST https://api.qr-verse.com/v1/qr-codes \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "url",
    "data": "https://example.com/landing-page",
    "options": {
      "size": 512,
      "format": "png",
      "errorCorrection": "H",
      "color": "#000000",
      "backgroundColor": "#FFFFFF"
    }
  }'

The response typically includes:

{
  "id": "qr_7f8a9b2c",
  "type": "url",
  "data": "https://example.com/landing-page",
  "image_url": "https://cdn.qr-verse.com/qr/qr_7f8a9b2c.png",
  "short_url": "https://qrv.se/abc123",
  "created_at": "2026-02-16T10:30:00Z",
  "scans": 0
}

For dynamic QR codes, the short_url is what gets encoded into the QR pattern. You can update the data field later through a PUT request, and all existing printed codes will redirect to the new destination.


Code Examples: Generate QR Codes Programmatically

Here are production-ready examples in four languages. Each example shows how to create a QR code, handle errors, and process the response.

JavaScript / Node.js

async function createQRCode(destinationUrl, options = {}) {
  const response = await fetch('https://api.qr-verse.com/v1/qr-codes', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.QR_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      type: 'url',
      data: destinationUrl,
      options: {
        size: options.size || 512,
        format: options.format || 'png',
        errorCorrection: options.errorCorrection || 'H',
        ...options
      }
    })
  })

  if (!response.ok) {
    const error = await response.json()
    throw new Error(`QR generation failed: ${error.message}`)
  }

  return response.json()
}

// Usage
const qr = await createQRCode('https://example.com/product/123', {
  size: 1024,
  format: 'svg'
})
console.log(qr.image_url)

Python

import requests
import os

def create_qr_code(destination_url, size=512, fmt="png", error_correction="H"):
    """Generate a QR code via the API."""
    response = requests.post(
        "https://api.qr-verse.com/v1/qr-codes",
        headers={
            "Authorization": f"Bearer {os.environ['QR_API_KEY']}",
            "Content-Type": "application/json"
        },
        json={
            "type": "url",
            "data": destination_url,
            "options": {
                "size": size,
                "format": fmt,
                "errorCorrection": error_correction
            }
        }
    )
    response.raise_for_status()
    return response.json()

# Create a single QR code
qr = create_qr_code("https://example.com/event/ticket/456")
print(f"QR code URL: {qr['image_url']}")

# Bulk generation
products = ["prod_001", "prod_002", "prod_003"]
for product_id in products:
    qr = create_qr_code(f"https://example.com/products/{product_id}")
    print(f"{product_id}: {qr['image_url']}")

cURL

# Basic QR code generation
curl -X POST https://api.qr-verse.com/v1/qr-codes \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "url",
    "data": "https://example.com",
    "options": {
      "size": 512,
      "format": "png",
      "errorCorrection": "H"
    }
  }'

# Generate a WiFi QR code
curl -X POST https://api.qr-verse.com/v1/qr-codes \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "wifi",
    "data": {
      "ssid": "GuestNetwork",
      "password": "welcome2024",
      "encryption": "WPA2"
    },
    "options": {
      "size": 512,
      "format": "svg"
    }
  }'

# Update a dynamic QR code destination
curl -X PUT https://api.qr-verse.com/v1/qr-codes/qr_7f8a9b2c \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "data": "https://example.com/new-destination"
  }'

PHP

function createQRCode(string $url, array $options = []): array
{
    $payload = json_encode([
        'type' => 'url',
        'data' => $url,
        'options' => array_merge([
            'size' => 512,
            'format' => 'png',
            'errorCorrection' => 'H'
        ], $options)
    ]);

    $ch = curl_init('https://api.qr-verse.com/v1/qr-codes');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . getenv('QR_API_KEY'),
            'Content-Type: application/json'
        ],
        CURLOPT_POSTFIELDS => $payload
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200 && $httpCode !== 201) {
        throw new RuntimeException("QR generation failed: HTTP $httpCode");
    }

    return json_decode($response, true);
}

// Usage
$qr = createQRCode('https://example.com/invoice/789', ['format' => 'svg']);
echo $qr['image_url'];

Choosing a QR Code API: Provider Comparison

Not all QR code APIs are equal. Here is a comparison of the top providers based on the features that matter most to developers.

FeatureQR-VerseQR Server (goqr.me)QR TIGERUniqode
Free tierYes (web)Yes (fully free)NoNo
Dynamic QR codesYesNoYesYes
Scan analyticsYesNoYesYes
Custom brandingYesNoYesYes
Logo embeddingYesNoYesYes
AI QR artYesNoNoNo
Rate limit (free)GenerousUnlimitedN/AN/A
Response formatPNG, SVG, PDFPNG, SVG, EPSPNG, SVGPNG, SVG, PDF
AuthenticationBearer tokenNoneAPI keyAPI key
WebhooksPlannedNoNoYes
Bulk generationYesNoYesYes

QR-Verse (Recommended)

QR-Verse offers a full-featured QR code platform with a free web generator, dynamic QR codes, scan analytics, and AI-powered QR code art. API access is available on the Pro tier. The unique advantage is the AI art generation - you can create visually stunning QR codes that double as brand artwork. If you are already using QR-Verse for manual QR code creation, the API is a natural extension.

QR Server (goqr.me)

The simplest free option. No authentication required - just call the endpoint with query parameters. The catch: no dynamic QR codes, no analytics, no branding. Good for prototyping and internal tools where tracking does not matter.

QR TIGER

A mature commercial API with good documentation. Starts at $7/month for API access. Solid choice for businesses that need dynamic QR codes and analytics but do not need AI art features.

Uniqode (formerly Beaconstac)

Enterprise-focused with comprehensive documentation in six languages and webhook support. The most feature-rich option for large organizations, but pricing reflects that - it is the most expensive option on this list.

If you are evaluating providers, start by creating a free QR code on QR-Verse to test the output quality. The web interface uses the same engine as the API, so what you see is what you get programmatically.


Best Practices for QR Code API Integration

These are the patterns that separate production-grade integrations from fragile prototypes.

Error Correction Levels

QR codes have four error correction levels that determine how much of the code can be damaged (or obscured by a logo) while remaining scannable:

LevelRecoveryBest For
L (Low)7%Digital-only use, small QR codes
M (Medium)15%General purpose, most use cases
Q (Quartile)25%Outdoor signage, likely wear
H (High)30%Logo embedding, harsh environments

Use level H when embedding a logo - the logo covers part of the code and you need maximum error correction to compensate. For everything else, level M is the sweet spot between data density and reliability.

Image Formats

  • SVG - use for print. SVG is vector-based, so it scales to any size without pixelation. Perfect for billboards, posters, and packaging. See our print and size guide for detailed specifications.
  • PNG - use for digital. Websites, emails, apps, and dashboards. Choose a size of at least 512x512px.
  • PDF - use when handing off to a print designer who needs a self-contained file.

Logo Embedding Without Breaking Scannability

When you embed a logo into a QR code, you are literally covering up data modules. Follow these rules:

  1. Keep the logo under 30% of the QR code area - any larger and even H-level error correction may not save you
  2. Always use error correction level H when adding a logo
  3. Center the logo - the QR code's positioning markers (the three corner squares) must remain visible
  4. Test every code - scan the final output with at least three different phones before shipping to production

Dynamic vs. Static for API Use

For API integrations, always default to dynamic QR codes. Here is why:

  • You can fix mistakes without reprinting
  • You can A/B test destinations
  • You get scan analytics for every code
  • You can expire codes after a campaign ends
  • You can redirect codes to different URLs based on location or device

Static codes are only appropriate when you need the simplest possible setup (no account, no tracking) and the destination URL will never change. Learn more in our static vs. dynamic comparison.

Security: Protect Your API Keys

This is non-negotiable:

  • Never expose API keys in client-side code. Not in JavaScript, not in mobile app bundles, not in environment variables that get bundled into frontend builds.
  • Use environment variables on your server. Access them via process.env (Node.js), os.environ (Python), or getenv() (PHP).
  • Rotate keys if you suspect a leak. Most providers let you generate new keys instantly.
  • Use scoped keys if your provider supports them - a key that can only create QR codes but not delete them, for example.
!

A leaked API key can let an attacker generate QR codes that point to malicious URLs under your account. This is a phishing vector - the QR codes would appear to come from your organization. Read our QR code security guide for more on this threat.

Rate Limiting and Caching

Every API has rate limits. Here is how to work within them:

  • Cache QR code images - if you are displaying the same QR code on a product page that gets 10,000 views per day, generate the code once and cache the image URL. Do not regenerate on every page load.
  • Use a CDN - serve cached QR code images from a CDN for fast global delivery.
  • Implement exponential backoff - if you hit a rate limit (HTTP 429), wait and retry with increasing delays.
  • Batch where possible - if you need 1,000 QR codes, use the bulk generation endpoint instead of 1,000 individual requests.
// Simple caching pattern with in-memory cache
const qrCache = new Map()

async function getOrCreateQR(url) {
  const cacheKey = `qr:${url}`

  if (qrCache.has(cacheKey)) {
    return qrCache.get(cacheKey)
  }

  const qr = await createQRCode(url)
  qrCache.set(cacheKey, qr)

  // Expire cache after 24 hours
  setTimeout(() => qrCache.delete(cacheKey), 86400000)

  return qr
}

Advanced Use Cases

Once you have basic API integration working, these advanced patterns unlock significant business value.

Bulk QR Code Generation for Product Packaging

When you need thousands of unique QR codes - one for every product SKU, every serial number, or every packaging unit - bulk generation is essential.

The pattern: prepare a CSV or JSON file with all your product data, then use the bulk endpoint to generate all codes in a single request.

import requests
import os

def bulk_generate(products):
    """Generate QR codes for a list of products."""
    items = [
        {
            "type": "url",
            "data": f"https://yoursite.com/products/{p['sku']}",
            "label": p["name"],
            "options": {"size": 512, "format": "svg", "errorCorrection": "H"}
        }
        for p in products
    ]

    response = requests.post(
        "https://api.qr-verse.com/v1/qr-codes/bulk",
        headers={
            "Authorization": f"Bearer {os.environ['QR_API_KEY']}",
            "Content-Type": "application/json"
        },
        json={"items": items}
    )
    response.raise_for_status()
    return response.json()["results"]

# Generate 500 product QR codes
products = [{"sku": f"SKU-{i:04d}", "name": f"Product {i}"} for i in range(500)]
results = bulk_generate(products)

For packaging-specific guidance, read our product packaging QR code guide.

Dynamic QR Codes for Event Tickets

Event ticketing is one of the most common API use cases. Each ticket gets a unique QR code that serves as both the entry pass and a data carrier.

The workflow:

  1. Customer purchases a ticket
  2. Your backend calls the QR code API to generate a unique code
  3. The code encodes a validation URL: https://events.yoursite.com/validate/TICKET-ID
  4. The code is embedded in the confirmation email and added to the customer's digital wallet
  5. At the door, staff scan the code. Your system validates it in real time and marks it as used

For a full implementation walkthrough, see our event ticketing guide and event RSVP guide.

Scan Analytics and Attribution Tracking

Every scan of a dynamic QR code generates data. The API gives you access to this data programmatically:

  • Timestamp - when was the code scanned?
  • Location - city, country, and coordinates (based on IP)
  • Device - iOS, Android, model, OS version
  • Referrer - where was the QR code placed?

Use this data for attribution:

// Fetch scan analytics for a QR code
const analytics = await fetch(
  `https://api.qr-verse.com/v1/qr-codes/${qrId}/analytics?range=30d`,
  {
    headers: {
      'Authorization': `Bearer ${process.env.QR_API_KEY}`
    }
  }
)

const data = await analytics.json()
console.log(`Total scans: ${data.total_scans}`)
console.log(`Unique scanners: ${data.unique_scanners}`)
console.log(`Top country: ${data.top_countries[0].name}`)

Combine QR scan data with your existing analytics stack. Pass UTM parameters in the destination URL, and you can track the full journey from physical scan to online conversion. For a deep dive into analytics, see our QR code analytics tracking guide.

White-Label QR Codes with Custom Domains

For agencies and SaaS platforms that resell QR code functionality, white-labeling is critical. Instead of qrv.se/abc123, your QR codes resolve through qr.yourclient.com/abc123.

Custom domains:

  • Build trust (users see a familiar domain when they scan)
  • Enable brand consistency across all touchpoints
  • Protect against provider lock-in (you control the DNS)

QR-Verse supports custom domains on Business plans and above. See pricing details or sign up for a free account to get started.


Getting Started with QR-Verse

You do not need API access to start generating QR codes. The free QR code generator lets you create dynamic QR codes, track scans, customize designs, and even generate AI QR code art - all through the web interface. No account required for basic codes.

When you are ready to integrate QR code generation into your applications programmatically:

  1. Create a free QR-Verse account
  2. Generate your first QR codes through the web interface to test quality
  3. Upgrade to Pro for API access and higher rate limits
  4. Use the code examples in this guide to build your integration
  5. Monitor scan analytics through the dashboard or API

For questions about API integration, pricing, or custom requirements, reach out to [email protected].


Frequently Asked Questions

Ready to create your QR code?

Free plan available. No signup required. Create professional QR codes in seconds.

Create Free QR Code

Ready to try it yourself?

Create professional QR codes with tracking, custom colors, and AI-generated art.

Try Free
Start Free

Create your QR code in seconds

No signup, no credit card. 25 QR types with full customization. Upgrade to Pro (EUR 4.99/mo) for unlimited power.

Share this article

Related Articles

Create QR Code