Getting started overview
The Cloudflare API enables developers to interact with Cloudflare's suite of services programmatically, from DNS record management and firewall rule configuration to Workers deployment and analytics retrieval. This guide outlines the essential steps to get started: account creation, credential generation, and executing a first API call. Cloudflare's API is primarily RESTful, utilizing HTTP methods (GET, POST, PUT, PATCH, DELETE) over HTTPS to interact with resources, and typically returns responses in JSON format. Understanding these core principles is foundational for effective integration.
To ensure a smooth onboarding experience, Cloudflare provides extensive Cloudflare API getting started documentation, covering various aspects of API usage, authentication, and error handling. Additionally, official client libraries (SDKs) are available for multiple programming languages, including Cloudflare Go SDK and Cloudflare Python SDK, which can simplify development by abstracting HTTP requests and JSON parsing.
This overview focuses on direct API interaction using curl for clarity, but the principles apply across all supported SDKs and programming environments. A quick reference table summarizes the initial steps:
| Step | What to Do | Where |
|---|---|---|
| 1. Sign Up | Create a Cloudflare account. | Cloudflare sign-up page |
| 2. Add Domain | Add a website/domain to your account (optional for some API uses). | Cloudflare Dashboard |
| 3. Get Credentials | Generate an API Token or Global API Key. | Cloudflare API Tokens page |
| 4. First Request | Make an authenticated API call (e.g., list zones). | Terminal (curl) or preferred programming environment |
Create an account and get keys
Accessing the Cloudflare API requires an active Cloudflare account. If you do not have one, you can register for a Cloudflare Free plan, which supports basic website and blog needs, or opt for a paid plan for advanced features. Account creation involves providing an email address and setting a password. After signing up, you may need to add a domain to your account and configure its DNS settings to point to Cloudflare's nameservers, though this step is not strictly necessary for all API operations, especially those related to account-level settings or Workers.
Generating API Credentials
Cloudflare offers two primary methods for API authentication: API Tokens and the Global API Key. API Tokens are the recommended and more secure method, allowing granular permissions and scope specific to the tasks the token will perform. The Global API Key provides full access to your entire Cloudflare account and should be used with extreme caution, ideally only for legacy integrations or specific automation where token-based access is not feasible.
API Tokens (Recommended)
- Navigate to the Cloudflare API Tokens dashboard.
- Click 'Create Token'.
- You can choose from a template (e.g., 'Edit Cloudflare Workers') or create a custom token with specific permissions. For a first request, a token with 'Zone' > 'Zone Settings' > 'Read' permissions might be sufficient to list zones, or 'User' > 'User Details' > 'Read' for account information.
- Select the specific resources (e.g., 'All zones' or a particular zone) the token can access.
- Review the summary and click 'Continue to summary'.
- Click 'Create Token'.
- The token will be displayed once. Copy it immediately, as it will not be shown again. Store it securely.
Global API Key (Legacy/High-Privilege)
- Navigate to your Cloudflare profile page.
- Scroll down to the 'API Tokens' section.
- Locate 'Global API Key' and click 'View'.
- Enter your Cloudflare password to confirm.
- Copy the displayed key. Store it securely.
The choice between an API Token and the Global API Key depends on the security requirements and the scope of access needed. For most applications, API Tokens provide a more secure and manageable approach, adhering to the principle of least privilege. The Cloudflare API token best practices guide offers further recommendations on securing your credentials.
Your first request
Once you have your API credential, you can make your first authenticated request. We'll use curl for this example, which is a common command-line tool for making HTTP requests. This example demonstrates how to list all zones (domains) associated with your Cloudflare account using an API Token.
To use an API Token, you include it in the Authorization header as a Bearer token. The base URL for the Cloudflare API is https://api.cloudflare.com/client/v4/.
Example: Listing Zones with an API Token
curl -X GET "https://api.cloudflare.com/client/v4/zones"
-H "Authorization: Bearer <YOUR_API_TOKEN>"
-H "Content-Type: application/json"
Replace <YOUR_API_TOKEN> with the actual API Token you generated. If successful, the API will return a JSON object containing an array of your zones, their IDs, status, and other details. A successful response will typically include "success": true and a result array.
Example: Listing Zones with the Global API Key
If you are using the Global API Key (not recommended for new integrations), you would include two headers: X-Auth-Email with your Cloudflare account email and X-Auth-Key with your Global API Key.
curl -X GET "https://api.cloudflare.com/client/v4/zones"
-H "X-Auth-Email: <YOUR_CLOUDFLARE_EMAIL>"
-H "X-Auth-Key: <YOUR_GLOBAL_API_KEY>"
-H "Content-Type: application/json"
Replace <YOUR_CLOUDFLARE_EMAIL> and <YOUR_GLOBAL_API_KEY> with your credentials. Both methods should yield similar successful results, demonstrating that your authentication is correctly configured and you can interact with the Cloudflare API.
Common next steps
After successfully making your first API call, several common next steps can help you further integrate with and utilize the Cloudflare API:
- Explore the API Reference: The Cloudflare API reference documentation provides detailed information on all available endpoints, request parameters, and response structures. This is crucial for understanding how to interact with specific Cloudflare services like DNS, Workers, or Firewall rules.
- Use SDKs: For programmatic interaction in your chosen language, consider using one of the official Cloudflare SDKs. These libraries abstract away the complexities of HTTP requests and JSON parsing, making development faster and less error-prone. SDKs are available for Go, Python, Node.js, Java, PHP, and C#.
- Implement Webhooks: For real-time notifications about events within your Cloudflare account (e.g., changes to DNS records, security events), explore Cloudflare webhooks. This allows your applications to react to events without constant polling.
- Error Handling: Implement robust error handling in your applications. The Cloudflare API returns standardized error codes and messages in its JSON responses. Understanding these Cloudflare API error codes is essential for diagnosing and resolving issues. For example, a
10000error typically indicates authentication failure, while10001may point to an invalid API key. - Rate Limits: Be aware of Cloudflare API rate limits to avoid service interruptions. Cloudflare imposes limits on the number of requests you can make within a given timeframe. Implement exponential backoff or token bucket algorithms to manage your request rate effectively.
- Security Best Practices: Always follow security best practices when handling API credentials. This includes using environment variables for keys, restricting token permissions to the minimum necessary, and regularly rotating your API tokens. The OAuth 2.0 Bearer Token Usage specification provides general guidance on securing API tokens.
- Cloudflare Workers: If your project involves serverless functions at the edge, the Cloudflare API is used to deploy and manage Cloudflare Workers. This allows for custom logic to run directly on Cloudflare's global network.
Troubleshooting the first call
When making your first API call, you might encounter issues. Here are common problems and their solutions:
-
Authentication Failure (Error Code 10000):
- Issue: Incorrect API Token or Global API Key, or missing authentication headers.
- Solution: Double-check that your API Token or Global API Key is copied correctly and included in the appropriate HTTP header (
Authorization: Bearer <TOKEN>for tokens, orX-Auth-EmailandX-Auth-Keyfor the Global API Key). Ensure there are no leading or trailing spaces.
-
Insufficient Permissions (Error Code 10001 or similar):
- Issue: The API Token does not have the necessary permissions to perform the requested action. For example, trying to modify DNS records with a token that only has 'Read' access.
- Solution: Review the permissions granted to your API Token on the Cloudflare API Tokens page. Edit the token to include the required permissions for the endpoint you are trying to access. For listing zones, 'Zone' > 'Zone Settings' > 'Read' is usually sufficient.
-
Incorrect Endpoint or Method:
- Issue: Using the wrong URL path or HTTP method (e.g., POST instead of GET).
- Solution: Consult the Cloudflare API documentation to verify the correct endpoint URL and HTTP method for your desired operation. The
/client/v4/zonesendpoint for listing zones requires a GET request.
-
JSON Parsing Errors:
- Issue: The API response is not valid JSON, or your client is failing to parse it.
- Solution: Ensure your
Content-Typeheader is set toapplication/jsonfor requests that send a body. For responses, verify the server is returningContent-Type: application/json. If usingcurl, ensure you are not accidentally truncating the output.
-
Network Connectivity Issues:
- Issue: Your client cannot reach the Cloudflare API servers.
- Solution: Check your internet connection and any firewall rules that might be blocking outbound HTTPS requests to
api.cloudflare.com.
-
Rate Limiting (Error Code 10002):
- Issue: You have exceeded the allowed number of API requests within a specific timeframe.
- Solution: Pause your requests and implement a retry mechanism with exponential backoff. Review Cloudflare API rate limits to understand the thresholds.
By systematically checking these common issues, you can often diagnose and resolve problems with your initial Cloudflare API calls. The Cloudflare developer community forums and support channels are also valuable resources for further assistance.