import requests
API_KEY = 'YOUR_API_KEY'
response = requests.get(
'https://api.api-ninjas.com/v1/qrcode',
params={'data': 'https://api-ninjas.com', 'format': 'png'},
headers={'X-Api-Key': API_KEY},
)
with open('qr.png', 'wb') as f:
f.write(response.content)Prerequisites
- Python 3.7+ installed
- The
requestslibrary (pip install requests) - A free API Ninjas API key
Step 1: Get your API key
Sign up at api-ninjas.com/register.
Step 2: Make the API request
Pass the text or URL you want to encode as the data parameter, and format=png for a PNG image:
import requests
API_KEY = 'YOUR_API_KEY'
response = requests.get(
'https://api.api-ninjas.com/v1/qrcode',
params={'data': 'https://api-ninjas.com', 'format': 'png'},
headers={'X-Api-Key': API_KEY},
)
with open('qr.png', 'wb') as f:
f.write(response.content)Step 3: Use the response
The response body is raw image bytes — write them to a file using binary mode ('wb'). Do not call response.json() for image responses.
Complete example with sizing and colors
import os
import requests
API_KEY = os.environ['API_NINJAS_KEY']
URL = 'https://api.api-ninjas.com/v1/qrcode'
def generate_qr(data: str, output: str, size: int = 256, fg: str = '000000', bg: str = 'ffffff') -> None:
response = requests.get(
URL,
params={
'data': data,
'format': 'png',
'size': size,
'fg_color': fg,
'bg_color': bg,
},
headers={'X-Api-Key': API_KEY},
timeout=10,
)
response.raise_for_status()
with open(output, 'wb') as f:
f.write(response.content)
if __name__ == '__main__':
generate_qr('https://api-ninjas.com', 'site.png', size=512)
print('Wrote site.png')Customizing QR code colors
Use fg_color and bg_color (6-digit hex, no leading #):
# Brand-colored QR code (blue on light gray)
generate_qr(
'https://api-ninjas.com',
'brand.png',
size=512,
fg='1664ea',
bg='f6f9fc',
)Encoding a vCard contact
QR codes can encode contact details so a phone scan adds the person to its contacts:
vcard = '''BEGIN:VCARD
VERSION:3.0
FN:Jane Doe
ORG:Acme Inc.
TEL:+1-555-0100
EMAIL:jane@example.com
END:VCARD'''
generate_qr(vcard, 'jane-vcard.png', size=512)Encoding Wi-Fi credentials
Generate a QR code that joins guests to your Wi-Fi network:
# Generate a QR code that connects to a Wi-Fi network when scanned
wifi = 'WIFI:T:WPA;S:GuestNetwork;P:correcthorsebatterystaple;;'
generate_qr(wifi, 'guest-wifi.png')Generating QR codes in bulk
urls = {
'home': 'https://api-ninjas.com',
'pricing': 'https://api-ninjas.com/pricing',
'docs': 'https://api-ninjas.com/api',
}
for name, url in urls.items():
generate_qr(url, f'{name}.png')
print(f'Wrote {name}.png')Related APIs
For barcode generation use the Barcode API. For more developer utilities see Password Generator and Lorem Ipsum.