In today’s fast-paced digital world, QR codes have become an invaluable tool for sharing information quickly and effortlessly.
From linking to websites and connecting to Wi-Fi networks, to sending payment details and contact information, QR codes make information accessible in a single scan.
In this tutorial, we’ll guide you through creating your own QR codes using Python. With just a few lines of code, you’ll be able to generate scannable, customizable QR codes that are ready for any application.
Plus, we’ll show you how to create a QR code generator API, so you can add this functionality to your applications and services.
QR codes are an easy and popular way to share information in a scannable format. Let’s dive into how to generate one with Python, using the qrcode
library.
Step 1: Install Required Libraries
First, install the qrcode
and Pillow
(PIL) libraries. qrcode
generates QR codes, while Pillow
handles image operations.
pip install qrcode[pil]
Step 2: Generate a Basic QR Code
Create a simple Python script to generate a QR code:
import qrcode # Define data to encode data = "https://example.com" # Create QR code instance qr = qrcode.QRCode( version=1, # Controls size (1 is 21x21, higher is bigger) error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) # Add data to the instance qr.add_data(data) qr.make(fit=True) # Create and save the image img = qr.make_image(fill_color="black", back_color="white") img.save("qrcode.png")
Explanation of Parameters:
version
: Defines the complexity of the QR code (1–40).error_correction
: Adds error-correction capability, ensuring QR code readability even if damaged.box_size
: Specifies how many pixels each box of the QR code should be.border
: Controls the width of the border around the QR code.
This code generates a QR code that links to https://example.com
and saves it as an image file called qrcode.png
.
Bonus: Turning This Into a Flask API
To make this functionality accessible via an API, let’s use Flask. This API will allow users to submit text or URLs for QR code generation, with the result returned as an image file.
Step 1: Install Flask
Install Flask with:
pip install Flask
Step 2: Set Up the Flask API
Here’s how to create a basic Flask API that generates QR codes from user input:
from flask import Flask, request, send_file import qrcode import io app = Flask(__name__) @app.route('/generate_qr', methods=['POST']) def generate_qr(): data = request.json.get("data", None) if not data: return {"error": "No data provided"}, 400 # Create QR code qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr.add_data(data) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white") # Save the QR code image in memory img_io = io.BytesIO() img.save(img_io, 'PNG') img_io.seek(0) return send_file(img_io, mimetype='image/png') if __name__ == '__main__': app.run(debug=True)
Explanation of the API
- Route:
/generate_qr
– Accepts POST requests with JSON data. - Data Input: Expects a JSON body with a
data
key containing the text or URL to encode. - Image Output: Returns a generated QR code image as a PNG.
Testing the API
Run the Flask app:
python app.py
Test the API with a tool like Postman or curl
:
curl -X POST -H "Content-Type: application/json" -d '{"data": "https://example.com"}' http://127.0.0.1:5000/generate_qr --output qrcode.png
The command above sends a POST request to your API and saves the output as qrcode.png
.
Benefits of Using QR Codes
Instant Access to Information: QR codes bridge the gap between offline and online, instantly directing users to websites, forms, or contact information.
Enhanced User Experience: They make it easy for customers to access content with one scan, saving time and effort.
Wide Application Range: QR codes support a variety of data types, from URLs to encrypted information, making them versatile across different needs.
Customizable for Branding: QR codes can be personalized with colors, logos, and shapes, adding a branded touch to promotional material.
Use Cases for QR Codes
Marketing Campaigns: Direct users to specific promotions, product pages, or social media channels by embedding links in QR codes on printed materials.
Event Check-ins: Simplify registration and access control at events by providing digital tickets as QR codes that can be scanned on entry.
Payments: Use QR codes to facilitate secure, contactless payments, especially popular in retail and food service industries.
Contactless Menus: Restaurants can offer digital menus by placing QR codes on tables, letting patrons scan to view without needing a physical menu.
Networking: Business professionals can share contact details quickly by using QR codes on business cards, which link directly to contact information.
And that’s it! You now have a Python script and a Flask API to generate QR codes.