GuidesDevelopers

How to generate QR codes in Python

Generate QR codes in Python with the qrcode or segno library for static codes, or with requests and the PikaQR API for dynamic codes you can track.

The short answer

For a code that never needs to change, install qrcode with pip and call qrcode.make. It runs on your own machine and needs no account. The segno library is a good alternative with no dependencies.

For a code you’ll want to change after it’s printed, or count scans for, create a dynamic code with requests and the PikaQR API. You get back a short link and an image, and you can change where it goes later.

Static or dynamic: which do you need?

A static code holds its content in the pattern. Once it’s printed, it can’t change, and you can’t tell how often it’s scanned. That suits a Wi-Fi password, a one-off ticket, or a code you draw on screen.

A dynamic code holds a short link instead, and the link decides where people go. Change the destination from your own code, add rules and read every scan. Pick dynamic for anything printed in numbers, put on a wall, or used in a campaign.

Static codes with qrcode

The qrcode library draws PNG images through Pillow, so install it with the pil extra. qrcode.make is the quickest route. The QRCode class gives you control over size, margin and error correction.

# pip install "qrcode[pil]"
import qrcode
from qrcode.constants import ERROR_CORRECT_M

# The quickest way
qrcode.make("https://example.com/menu").save("menu.png")

# With control over the details
qr = qrcode.QRCode(
    error_correction=ERROR_CORRECT_M,
    box_size=20,  # pixels per square
    border=4,     # the quiet zone, in squares
)
qr.add_data("https://example.com/menu")
qr.make(fit=True)
qr.make_image(fill_color="#1a1a2e", back_color="white").save("menu-large.png")

Static codes with segno

Segno has no dependencies and writes PNG and SVG on its own. Use make_qr so you always get a full-size QR code: segno.make can choose the smaller Micro QR format for short content, and many phones can’t read it.

  • Keep a border of 4 squares around the code. Scanners need that quiet zone.
  • Error correction is L, M, Q or H. M suits most print. Use Q or H if the code may get scratched or have a logo over it.
  • Make print files large and let the printer scale them down, or use SVG.
# pip install segno
import segno

qr = segno.make_qr("https://example.com/menu", error="m")
qr.save("menu.png", scale=20, border=4)
qr.save("menu.svg", scale=20, border=4)

# A Wi-Fi code: phones offer to join the network when they scan it.
segno.make_qr("WIFI:T:WPA;S:Lobby Guest;P:welcome2027;;", error="q").save("wifi.png", scale=20)

Serve a code from a web view

To show a code on a page, you don’t need to save a file. Save the image into an io.BytesIO buffer and return the bytes with an image/png content type. The sample uses Flask, and the same idea works in a Django or FastAPI view.

Codes made this way are drawn fresh on every request, which is cheap. If the same text is asked for often, cache the result.

# pip install flask "qrcode[pil]"
# Run with: flask --app server run
# then open http://localhost:5000/qr?text=hello
import io

import qrcode
from flask import Flask, request, send_file

app = Flask(__name__)


@app.get("/qr")
def qr_image():
    text = request.args.get("text")
    if not text:
        return "Add ?text= to the address", 400
    buffer = io.BytesIO()
    qrcode.make(text, border=4).save(buffer, format="PNG")
    buffer.seek(0)
    return send_file(buffer, mimetype="image/png")

Dynamic codes with the PikaQR API

Sign up for free, open the Developers page in your dashboard and create an API key. Keep it in an environment variable rather than in your code. A requests session sends the key with every call.

One POST creates the code. The reply has its id and its short_url, which is what the printed code holds. A second request fetches the image as a PNG or an SVG, from 64 to 2048 pixels wide.

# pip install requests
# Run with: PIKAQR_KEY=pk_... python dynamic.py
import os
import requests

BASE = "https://pikaqr.com/api/v1"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['PIKAQR_KEY']}"

res = session.post(f"{BASE}/qr", json={
    "title": "Spring flyer",
    "destination_url": "https://example.com/spring",
    "tags": ["flyers"],
    "metadata": {"campaign": "spring-2027"},
})
code = res.json()
if not res.ok:
    raise SystemExit(f"{code['code']}: {code['error']}")
print(code["id"], code["short_url"])

# The image holds the short link, so it keeps working when the destination changes.
image = session.get(f"{BASE}/qr/{code['id']}/image", params={"format": "png", "size": 1024})
image.raise_for_status()
with open("spring-flyer.png", "wb") as file:
    file.write(image.content)

Change it and count the scans

Send a new destination_url with PATCH, and every printed copy goes to the new address straight away. The old one stays in the code’s history.

Read totals from the analytics endpoint. It returns total and unique scans, and counts by day, device, country and language. The Free plan covers the last 7 days.

# Run with: PIKAQR_KEY=pk_... CODE_ID=... python update.py
import os
import requests

BASE = "https://pikaqr.com/api/v1"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['PIKAQR_KEY']}"
code_id = os.environ["CODE_ID"]

# Point the printed code somewhere new
res = session.patch(f"{BASE}/qr/{code_id}", json={"destination_url": "https://example.com/summer"})
print(res.json())  # {'success': True, 'version': 2}

# How many scans in the last 7 days
stats = session.get(f"{BASE}/qr/{code_id}/analytics", params={"days": 7}).json()
print(stats["total_scans"], "scans,", stats["unique_scans"], "unique")
for row in stats["by_country"]:
    print(row["country"], row["count"])

Handle errors and limits

Every error has an error sentence for people and a code for programs, such as plan_limit or invalid_destination. Match on the code: it won’t change.

The Free plan allows 1,000 requests an hour and Premium allows 10,000. If you go over, you get a 429 with a Retry-After header, in seconds. Sleep for that long and send the same request again. Making many codes from a CSV file works the same way, one request per row.

On Premium you can also add a webhook, and each scan arrives at your server as a signed POST, with the metadata you attached to the code. A few lines of hmac and hashlib check the signature.

Questions

Which Python library is best for QR codes?

qrcode is the most widely used, and draws PNG files through Pillow. Segno has no dependencies and writes PNG and SVG on its own. Both make static codes, and either is a good choice.

Why does qrcode.make fail with an error about PIL?

PNG output needs Pillow. Install the library with pip install "qrcode[pil]", or save an SVG with the SvgPathImage factory, which doesn’t need it.

How big should the QR code image be?

For screens, 300 to 400 pixels is plenty. For print, make it large, such as a box_size of 20 or more, or use SVG, and keep the printed code at least 2 cm (0.8 in) wide.

Can I change a QR code made with qrcode or segno?

No. The content is in the pattern, so a new destination means a new code. If it might change, create a dynamic code with the API instead.

Make a code you can change

Get a free API key and create dynamic QR codes you can track and point somewhere new at any time.

Get a free API key

More guides

How to generate QR codes in Node.jsDynamic vs static QR codes: which one do you need?How to make a QR code menu for your restaurantWhat size should a QR code be for print?
How to generate QR codes in Python · PikaQR