Skip to content

Code Examples

Ready-to-use examples for integrating the QBar Scanner API in various languages.

cURL

bash
# Create a QR code
curl -X POST https://api.qbar-scanner.com/api/v1/qrcodes \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $QBAR_API_KEY" \
  -d '{
    "type": "url",
    "content": { "url": "https://example.com" },
    "name": "My Website",
    "is_dynamic": true
  }'

# List QR codes
curl "https://api.qbar-scanner.com/api/v1/qrcodes?page=1&limit=10" \
  -H "X-API-Key: $QBAR_API_KEY"

# Download QR image
curl "https://api.qbar-scanner.com/api/v1/qrcodes/{id}/image?size=500" \
  -H "X-API-Key: $QBAR_API_KEY" \
  -o qrcode.svg

JavaScript / Node.js

javascript
const API_KEY = process.env.QBAR_API_KEY
const BASE = 'https://api.qbar-scanner.com/api/v1'

// Create a QR code
async function createQrCode() {
  const res = await fetch(`${BASE}/qrcodes`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': API_KEY
    },
    body: JSON.stringify({
      type: 'url',
      content: { url: 'https://example.com' },
      name: 'My Website',
      is_dynamic: true,
      style: {
        dotsOptions: { type: 'rounded', color: '#667eea' }
      }
    })
  })

  const data = await res.json()
  console.log('Created:', data.id)
  console.log('Image URL:', data.image_url)
  return data
}

// Bulk create
async function bulkCreate(urls) {
  const qrcodes = urls.map((url, i) => ({
    type: 'url',
    content: { url },
    name: `Link ${i + 1}`,
    is_dynamic: true
  }))

  const res = await fetch(`${BASE}/qrcodes/bulk`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': API_KEY
    },
    body: JSON.stringify({ qrcodes })
  })

  return res.json()
}

// Download image
async function downloadImage(id, size = 400) {
  const res = await fetch(`${BASE}/qrcodes/${id}/image?size=${size}`, {
    headers: { 'X-API-Key': API_KEY }
  })
  const svg = await res.text()
  // Save to file (Node.js)
  const fs = await import('fs')
  fs.writeFileSync('qrcode.svg', svg)
}

Python

python
import requests
import os

API_KEY = os.environ["QBAR_API_KEY"]
BASE = "https://api.qbar-scanner.com/api/v1"
HEADERS = {
    "Content-Type": "application/json",
    "X-API-Key": API_KEY
}

# Create a QR code
def create_qr_code():
    res = requests.post(f"{BASE}/qrcodes", json={
        "type": "url",
        "content": {"url": "https://example.com"},
        "name": "My Website",
        "is_dynamic": True,
        "style": {
            "dotsOptions": {"type": "rounded", "color": "#667eea"}
        }
    }, headers=HEADERS)
    data = res.json()
    print(f"Created: {data['id']}")
    return data

# List QR codes
def list_qr_codes(page=1, limit=20):
    res = requests.get(f"{BASE}/qrcodes", params={
        "page": page, "limit": limit
    }, headers=HEADERS)
    return res.json()

# Download image
def download_image(qr_id, size=400):
    res = requests.get(
        f"{BASE}/qrcodes/{qr_id}/image",
        params={"size": size},
        headers={"X-API-Key": API_KEY}
    )
    with open("qrcode.svg", "wb") as f:
        f.write(res.content)

# Bulk create
def bulk_create(urls):
    qrcodes = [
        {"type": "url", "content": {"url": u}, "name": f"Link {i+1}"}
        for i, u in enumerate(urls)
    ]
    res = requests.post(f"{BASE}/qrcodes/bulk",
        json={"qrcodes": qrcodes}, headers=HEADERS)
    return res.json()

PHP

php
<?php
$apiKey = getenv('QBAR_API_KEY');
$base = 'https://api.qbar-scanner.com/api/v1';

function qbarRequest($method, $path, $body = null) {
    global $apiKey, $base;

    $ch = curl_init("$base$path");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        "X-API-Key: $apiKey"
    ]);

    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    } elseif ($method === 'PUT') {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    } elseif ($method === 'DELETE') {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
    }

    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

// Create QR code
$result = qbarRequest('POST', '/qrcodes', [
    'type' => 'url',
    'content' => ['url' => 'https://example.com'],
    'name' => 'My Website',
    'is_dynamic' => true
]);

echo "Created: " . $result['id'] . "\n";
echo "Image: " . $result['image_url'] . "\n";

Ruby

ruby
require 'net/http'
require 'json'
require 'uri'

API_KEY = ENV['QBAR_API_KEY']
BASE = 'https://api.qbar-scanner.com/api/v1'

def qbar_request(method, path, body = nil)
  uri = URI("#{BASE}#{path}")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = case method
    when :get    then Net::HTTP::Get.new(uri)
    when :post   then Net::HTTP::Post.new(uri)
    when :put    then Net::HTTP::Put.new(uri)
    when :delete then Net::HTTP::Delete.new(uri)
  end

  request['Content-Type'] = 'application/json'
  request['X-API-Key'] = API_KEY
  request.body = body.to_json if body

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

# Create QR code
result = qbar_request(:post, '/qrcodes', {
  type: 'url',
  content: { url: 'https://example.com' },
  name: 'My Website',
  is_dynamic: true
})

puts "Created: #{result['id']}"

Go

go
package main

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

const baseURL = "https://api.qbar-scanner.com/api/v1"

func createQrCode(apiKey string) (map[string]interface{}, error) {
    body := map[string]interface{}{
        "type":       "url",
        "content":    map[string]string{"url": "https://example.com"},
        "name":       "My Website",
        "is_dynamic": true,
    }

    jsonBody, _ := json.Marshal(body)
    req, _ := http.NewRequest("POST", baseURL+"/qrcodes", bytes.NewBuffer(jsonBody))
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("X-API-Key", apiKey)

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

    var result map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&result)
    return result, nil
}

func main() {
    apiKey := os.Getenv("QBAR_API_KEY")
    result, err := createQrCode(apiKey)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("Created:", result["id"])
}

Java

java
import java.net.http.*;
import java.net.URI;

public class QBarExample {
    static final String BASE = "https://api.qbar-scanner.com/api/v1";
    static final String API_KEY = System.getenv("QBAR_API_KEY");

    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();

        String body = """
            {
                "type": "url",
                "content": { "url": "https://example.com" },
                "name": "My Website",
                "is_dynamic": true
            }
            """;

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(BASE + "/qrcodes"))
            .header("Content-Type", "application/json")
            .header("X-API-Key", API_KEY)
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();

        HttpResponse<String> response = client.send(request,
            HttpResponse.BodyHandlers.ofString());

        System.out.println("Status: " + response.statusCode());
        System.out.println("Body: " + response.body());
    }
}

QBar Scanner Developer API