Cloudflare Python SDK
The official Python library for interacting with the Cloudflare API. It provides a comprehensive client for accessing various Cloudflare services. The current stable version is 4.3.1. The library follows a frequent release cadence, often introducing new features and occasionally breaking changes due to underlying API updates.
Warnings
- breaking Version 5.0.0 (currently in beta) introduces a large number of breaking changes due to updates in Cloudflare's OpenAPI definitions and the library's code generation process. Existing code will likely require significant updates.
- breaking Version 4.0.0 introduced specific breaking changes, including reshuffling of the `addressing` namespace and renaming of the `cf-r2-jurisdiction` parameter to `jurisdiction` in R2 operations.
- breaking Versions 3.x marked a complete ground-up rewrite of the SDK, moving to code generation from Cloudflare's OpenAPI spec. This introduced frequent minor breaking changes in method names, types, and client structure compared to 2.x versions.
- gotcha Cloudflare supports different authentication methods: API Tokens (recommended) and Global API Keys. The client can be initialized with `token` (for API Tokens) or `email` and `token` (for Global API Key). Mixing them incorrectly or providing the wrong type of key can lead to authentication failures.
Install
-
pip install cloudflare
Imports
- Cloudflare
import Cloudflare
Quickstart
import os
import Cloudflare
# Ensure CLOUDFLARE_API_TOKEN is set in your environment
# Example: export CLOUDFLARE_API_TOKEN="your_api_token"
cf = Cloudflare.Cloudflare(token=os.environ.get('CLOUDFLARE_API_TOKEN', ''))
try:
# Example: List all zones associated with the API Token
zones = cf.zones.get()
print(f"Found {len(zones)} zones:")
for zone in zones:
print(f"- {zone['name']} (ID: {zone['id']})")
if zones:
# Example: Get details for the first zone
first_zone_id = zones[0]['id']
zone_details = cf.zones.get(first_zone_id)
print(f"\nDetails for {zone_details['name']}: {zone_details['status']}")
except Cloudflare.CloudflareAPIError as e:
print(f"Cloudflare API Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")