DEV Community

Fred Santos
Fred Santos

Posted on

How to Generate QR Codes via REST API (Examples in 5 Languages)

How to Generate QR Codes via REST API (Examples in 5 Languages)

QR codes are everywhere — restaurant menus, payment links, event check-ins, product packaging. Generating them via API is simpler than installing a library in every language and environment you work with.

This tutorial shows how to generate QR codes using IteraTools' QR endpoint, with examples in Python, JavaScript, PHP, Go, and Ruby.

Why Use a QR Code API Instead of a Library?

  • No dependencies: No qrcode, python-qrcode, node-qrcode, or similar library to install and maintain.
  • Consistent output: Same quality and format across all your systems.
  • Serverless friendly: Works in Lambda, Cloud Functions, Edge workers — anywhere HTTP works.
  • Customization without code: Colors, logo overlays, error correction levels via parameters.
  • One less thing to update: Library updates, security patches, dependency conflicts — not your problem.

Comparison Table

Approach Setup Customization Server Needed Cost
IteraTools API API key High (colors, logos) No ~$0.001/code
python-qrcode pip install Medium Yes (Python env) Free
node-qrcode npm install Medium Yes (Node env) Free
GoQR.me API None Low No Free (limited)
QR Server API None Low No Free (watermark)

For most production apps, paying fractions of a cent per QR code is cheaper than managing library dependencies.

Generate a QR Code — curl

curl -X POST https://api.iteratools.com/v1/qrcode \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "data": "https://iteratools.com",
    "size": 300,
    "format": "png"
  }' \
  --output qrcode.png
Enter fullscreen mode Exit fullscreen mode

With custom colors and logo:

curl -X POST https://api.iteratools.com/v1/qrcode \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "data": "https://iteratools.com",
    "size": 400,
    "format": "png",
    "foreground": "#1a1a2e",
    "background": "#ffffff",
    "error_correction": "H"
  }'
Enter fullscreen mode Exit fullscreen mode

Response (when using return_url: true):

{
  "url": "https://cdn.iteratools.com/qrcodes/abc123.png",
  "size": 400,
  "format": "png",
  "credits_used": 1
}
Enter fullscreen mode Exit fullscreen mode

Examples in 5 Languages

Python

import requests
from pathlib import Path

API_KEY = "your_api_key_here"

def generate_qrcode(data: str, output_file: str = "qr.png", size: int = 300) -> str:
    response = requests.post(
        "https://api.iteratools.com/v1/qrcode",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json={
            "data": data,
            "size": size,
            "format": "png",
            "return_url": True
        }
    )
    response.raise_for_status()
    result = response.json()

    # Download PNG
    img = requests.get(result["url"])
    Path(output_file).write_bytes(img.content)
    print(f"QR saved: {output_file}")
    return result["url"]

# Generate QR for a payment link
generate_qrcode("https://pay.example.com/invoice/12345", "payment_qr.png")
Enter fullscreen mode Exit fullscreen mode

JavaScript (Node.js / fetch)

const fs = require('fs');

async function generateQRCode(data, outputFile = 'qr.png', size = 300) {
  const response = await fetch('https://api.iteratools.com/v1/qrcode', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.ITERATOOLS_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ data, size, format: 'png', return_url: true })
  });

  if (!response.ok) {
    throw new Error(`API error: ${response.status}`);
  }

  const result = await response.json();

  // Download and save
  const imgResponse = await fetch(result.url);
  const buffer = Buffer.from(await imgResponse.arrayBuffer());
  fs.writeFileSync(outputFile, buffer);

  console.log(`QR saved: ${outputFile}`);
  return result.url;
}

// Usage
generateQRCode('https://example.com/menu', 'menu_qr.png', 400)
  .then(url => console.log('URL:', url))
  .catch(console.error);
Enter fullscreen mode Exit fullscreen mode

PHP

<?php

function generateQRCode(string $data, string $outputFile = 'qr.png', int $size = 300): string {
    $apiKey = getenv('ITERATOOLS_API_KEY');

    $payload = json_encode([
        'data'       => $data,
        'size'       => $size,
        'format'     => 'png',
        'return_url' => true,
    ]);

    $ch = curl_init('https://api.iteratools.com/v1/qrcode');
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $payload,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            "Authorization: Bearer $apiKey",
            'Content-Type: application/json',
        ],
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($response, true);
    $imageData = file_get_contents($result['url']);
    file_put_contents($outputFile, $imageData);

    echo "QR saved: $outputFile\n";
    return $result['url'];
}

// Generate QR for WiFi credentials
generateQRCode('WIFI:T:WPA;S:MyNetwork;P:MyPassword;;', 'wifi_qr.png');
Enter fullscreen mode Exit fullscreen mode

Go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
)

const apiKey = "your_api_key_here"

type QRRequest struct {
    Data      string `json:"data"`
    Size      int    `json:"size"`
    Format    string `json:"format"`
    ReturnURL bool   `json:"return_url"`
}

type QRResponse struct {
    URL         string `json:"url"`
    CreditsUsed int    `json:"credits_used"`
}

func generateQRCode(data, outputFile string, size int) (string, error) {
    payload, _ := json.Marshal(QRRequest{
        Data: data, Size: size, Format: "png", ReturnURL: true,
    })

    req, _ := http.NewRequest("POST", "https://api.iteratools.com/v1/qrcode",
        bytes.NewBuffer(payload))
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()

    var result QRResponse
    json.NewDecoder(resp.Body).Decode(&result)

    // Download image
    imgResp, _ := http.Get(result.URL)
    defer imgResp.Body.Close()
    imgData, _ := io.ReadAll(imgResp.Body)
    os.WriteFile(outputFile, imgData, 0644)

    fmt.Printf("QR saved: %s\n", outputFile)
    return result.URL, nil
}

func main() {
    generateQRCode("https://example.com/product/42", "product_qr.png", 350)
}
Enter fullscreen mode Exit fullscreen mode

Ruby

require 'net/http'
require 'json'
require 'uri'
require 'open-uri'

API_KEY = ENV['ITERATOOLS_API_KEY'] || 'your_api_key_here'

def generate_qrcode(data, output_file: 'qr.png', size: 300)
  uri = URI('https://api.iteratools.com/v1/qrcode')

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Post.new(uri.path)
  request['Authorization'] = "Bearer #{API_KEY}"
  request['Content-Type'] = 'application/json'
  request.body = { data: data, size: size, format: 'png', return_url: true }.to_json

  response = http.request(request)
  result = JSON.parse(response.body)

  # Download image
  URI.open(result['url']) do |img|
    File.binwrite(output_file, img.read)
  end

  puts "QR saved: #{output_file}"
  result['url']
end

# Generate QR for business card vCard
vcard = "BEGIN:VCARD\nVERSION:3.0\nFN:John Doe\nTEL:+15551234567\nEND:VCARD"
generate_qrcode(vcard, output_file: 'business_card_qr.png', size: 350)
Enter fullscreen mode Exit fullscreen mode

Common QR Code Use Cases

  • Payment links: Generate per-transaction QR codes for checkout pages
  • Restaurant menus: Unique QR per table or menu version
  • WiFi credentials: WIFI:T:WPA;S:NetworkName;P:Password;;
  • vCards: Encode contact information in QR for business cards
  • Event check-in: Unique QR per ticket/attendee
  • Product tracking: QR codes that link to warranty/support pages

Conclusion

Generating QR codes via REST API is simpler than managing a library in every language and runtime you work with. IteraTools provides a clean endpoint at ~$0.001/code — practically free for most use cases, with no library installs or dependency management.

Since it's the same API as your image processing, scraping, and PDF tools, there's zero additional setup.

Generate your first QR at api.iteratools.com

Top comments (0)