Skip to main content

Cloudflare API Reference Snippets

Learning Focus

Common Cloudflare API commands for automating daily tasks using curl.

Authentication​

All API calls require an API Token. Create one at User Profile → API Tokens.

Set environment variables
export CF_TOKEN="your-token"
export CF_ZONE_ID="your-zone-id"

DNS Management​

List DNS Records​

curl "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/dns_records" \
-H "Authorization: Bearer $CF_TOKEN" \
-H "Content-Type: application/json"

Create A Record​

curl -X POST "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/dns_records" \
-H "Authorization: Bearer $CF_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"type": "A",
"name": "api.example.com",
"content": "203.0.113.10",
"ttl": 3600,
"proxied": true
}'

Cache Purging​

Purge Everything​

curl -X POST "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/purge_cache" \
-H "Authorization: Bearer $CF_TOKEN" \
-H "Content-Type: application/json" \
--data '{"purge_everything":true}'

Purge by URL​

curl -X POST "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/purge_cache" \
-H "Authorization: Bearer $CF_TOKEN" \
-H "Content-Type: application/json" \
--data '{"files":["https://example.com/static/style.css"]}'

Development Mode​

Enable Development Mode (bypasses cache for 3 hours):

curl -X PATCH "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/settings/development_mode" \
-H "Authorization: Bearer $CF_TOKEN" \
-H "Content-Type: application/json" \
--data '{"value":"on"}'

Workers & KV​

List KV Namespaces​

curl "https://api.cloudflare.com/client/v4/accounts/$CF_ACCOUNT_ID/storage/kv/namespaces" \
-H "Authorization: Bearer $CF_TOKEN"

Write to KV​

curl -X PUT "https://api.cloudflare.com/client/v4/accounts/$CF_ACCOUNT_ID/storage/kv/namespaces/$KV_ID/values/my-key" \
-H "Authorization: Bearer $CF_TOKEN" \
-d "my-value"

Common API Paths​

ObjectPath
User/user
Zones/zones
DNS/zones/:id/dns_records
Workers/accounts/:id/workers
R2/accounts/:id/r2
Analytics/zones/:id/analytics

Key Takeaways​

  • Use API Tokens for security instead of the Global API Key.
  • Ensure your token has the correct permissions for the specific API path.
  • The Zone ID is found on the "Overview" page of your domain in the dashboard.
  • Always use -H "Content-Type: application/json" for POST/PUT/PATCH requests.