Last modified: Feb 01, 2026 By Alexander Williams
Cloudflare Python API Guide for Automation
Cloudflare is a global network. It makes websites fast and secure. Many developers use its services.
Managing Cloudflare manually is slow. The Cloudflare Python API solves this. It lets you control Cloudflare with code.
This guide will show you how to use it. We will cover setup, core tasks, and best practices.
What is the Cloudflare Python API?
The Cloudflare Python API is a library. It wraps the Cloudflare REST API. You can use it in your Python scripts.
It helps automate tasks. You can manage DNS records, firewall rules, and zones. You can also fetch analytics data.
Automation saves time. It reduces human error. It is essential for modern DevOps.
If you are new to APIs, our Python API Tutorial for Beginners is a great starting point.
Getting Started with the Cloudflare Python API
First, you need to install the library. Use pip, the Python package installer.
pip install cloudflare
Next, get your API credentials. Log into your Cloudflare dashboard. Go to "My Profile" then "API Tokens".
Create a new token. Give it the necessary permissions. For example, "Zone.Zone Read" and "Zone.DNS Edit".
Keep your token secret. Never commit it to public code repositories.
Initializing the Client
You start by creating a client object. This object will handle all API calls.
You can pass your API key and email. Or, you can use an API token. Tokens are the newer, preferred method.
import CloudFlare
# Method 1: Using Global API Key & Email (Legacy)
# cf = CloudFlare.CloudFlare(email='[email protected]', token='your_global_api_key')
# Method 2: Using API Token (Recommended)
cf = CloudFlare.CloudFlare(token='your_api_token_here')
print("Cloudflare client initialized successfully.")
Cloudflare client initialized successfully.
Core Automation Tasks with Examples
Let's explore common tasks. We will use the cf client we just created.
1. Listing Your Zones
A zone is a domain you manage on Cloudflare. Listing them is often the first step.
Use the zones.get method.
# Get all zones (domains) in your account
zones = cf.zones.get()
print(f"Total Zones: {len(zones)}")
for zone in zones:
print(f" - {zone['name']} (ID: {zone['id']})")
Total Zones: 2
- example.com (ID: a1b2c3d4e5f67890123456789abcdef)
- myblog.net (ID: f1e2d3c4b5a69870123456789fedcba)
2. Managing DNS Records
DNS records direct traffic. Automating them is very powerful.
You need the Zone ID for the domain. We'll use the ID from the previous output.
zone_id = 'a1b2c3d4e5f67890123456789abcdef' # Replace with your zone ID
# List all DNS records for a zone
dns_records = cf.zones.dns_records.get(zone_id)
print(f"Found {len(dns_records)} DNS records for zone.")
for record in dns_records[:3]: # Show first 3
print(f" {record['type']} {record['name']} -> {record['content']}")
# Create a new A record
new_record = {
'type': 'A',
'name': 'api.example.com',
'content': '192.0.2.1',
'ttl': 120, # Auto TTL is 1, or set a value like 120
'proxied': False # Whether proxied through Cloudflare
}
try:
response = cf.zones.dns_records.post(zone_id, data=new_record)
print(f"\nSuccessfully created record: {response['name']}")
except Exception as e:
print(f"Error creating record: {e}")
Found 12 DNS records for zone.
A example.com -> 192.0.2.100
CNAME www -> example.com
MX example.com -> mail.example.com
Successfully created record: api.example.com
For more on handling data from APIs, see our Python API Data Pulling Guide.
3. Managing Firewall Rules
Firewall rules block or allow traffic. You can automate security policies.
Let's create a rule to block traffic from a specific country.
# Define a firewall rule to block traffic from a country code
firewall_rule_data = {
"description": "Block traffic from Country X",
"filter": {
"expression": "(ip.geoip.country eq \"XX\")" # Replace XX with country code
},
"action": "block"
}
try:
rule = cf.zones.firewall.rules.post(zone_id, data=[firewall_rule_data])
print(f"Firewall rule created. Rule ID: {rule[0]['id']}")
except Exception as e:
print(f"Error creating firewall rule: {e}")
Firewall rule created. Rule ID: abc123def4567890abc123def4567890
4. Fetching Analytics Data
Cloudflare provides rich analytics. You can pull this data for reports.
Use the zones.analytics.dashboard.get method.
# Get analytics dashboard data for the last 7 days
import datetime
end = datetime.datetime.now()
start = end - datetime.timedelta(days=7)
params = {
'since': start.isoformat(),
'until': end.isoformat(),
'continuous': True
}
analytics = cf.zones.analytics.dashboard.get(zone_id, params=params)
totals = analytics.get('totals', {})
print("Zone Analytics (Last 7 Days):")
print(f" Requests: {totals.get('requests', {}).get('all', 'N/A')}")
print(f" Bandwidth: {totals.get('bandwidth', {}).get('all', 'N/A')} bytes")
print(f" Threats Blocked: {totals.get('threats', {}).get('all', 'N/A')}")
Zone Analytics (Last 7 Days):
Requests: 1548920
Bandwidth: 12547893245 bytes
Threats Blocked: 342
Best Practices and Error Handling
Always use try-except blocks. API calls can fail due to network or authentication issues.
Store your API token securely. Use environment variables