This tutorial explains how to fetch total request data and requests by country from Cloudflare. It also covers cached and uncached requests in Cloudflare Workers.
Please refer the instructions below to get API key and zone id to use API to fetch details.
Instructions : You can find your API key in the Cloudflare dashboard by clicking on profile icon (top-right) > My Profile > API Tokens. Either you can use global API key or you can create a custom API token with specific permissions. The Zone ID is available on the Overview page of your site in Cloudflare.
The following Python code returns the total requests to your site by country in the past 24 hours.
import requests import json from datetime import datetime, timedelta, timezone # Define the new GraphQL query query = """ query GetZoneAnalytics($zoneTag: String!, $since: String!, $until: String!) { viewer { zones(filter: {zoneTag: $zoneTag}) { totals: httpRequests1hGroups(limit: 10000, filter: {datetime_geq: $since, datetime_lt: $until}) { sum { requests } } zones: httpRequests1hGroups(limit: 10000, filter: {datetime_geq: $since, datetime_lt: $until}) { sum { countryMap { requests key: clientCountryName } } } } } } """ # Define Cloudflare API credentials API_KEY = "xxxxxxxxxxx" ZONE_ID = "xxxxxxxxxxxxx" API_EMAIL = "xxxxxxxx@xxxx.com" # Set up headers headers = { "X-Auth-Email": API_EMAIL, "X-Auth-Key": API_KEY, "Content-Type": "application/json" } # Set the variables for the query now = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0) start_date = now - timedelta(days=1) end_date = now # ISO Format since = start_date.strftime("%Y-%m-%dT%H:%M:%SZ") until = end_date.strftime("%Y-%m-%dT%H:%M:%SZ") # Create the request body with variables payload = { "query": query, "variables": { "zoneTag": ZONE_ID, "since": since, "until": until } } # Make the API request response = requests.post( url="https://api.cloudflare.com/client/v4/graphql", headers=headers, json=payload ) # Process the response if response.status_code >= 400: raise Exception(f"Error: {response.status_code}, {response.text}") data = response.json() mydata = data.get("data", {}).get("viewer", {}).get("zones", [{}])[0] # You can print or process the data as needed print(json.dumps(mydata, indent=4))
Output
{ "totals": [ { "sum": { "requests": 338 } } ], "zones": [ { "sum": { "countryMap": [ { "key": "UNKNOWN", "requests": 7 }, { "key": "BG", "requests": 1 }, { "key": "CA", "requests": 16 }, { "key": "CN", "requests": 25 }, { "key": "DE", "requests": 22 }, { "key": "FI", "requests": 15 }, { "key": "GB", "requests": 1 }, { "key": "IN", "requests": 151 }, { "key": "KR", "requests": 2 }, { "key": "NL", "requests": 1 }, { "key": "SG", "requests": 8 }, { "key": "US", "requests": 89 } ] } } ] }
Workers Analytics Data
The following code returns the number of requests your website is getting using Cloudflare Workers.
import requests import json # Define the GraphQL query query = """ query getAnalyticsQuery($zoneTag: String!, $datetime: String!) { viewer { zones(filter: { zoneTag: $zoneTag }) { workersZoneInvocationsAdaptiveGroups( limit: 10000, filter: { datetime_geq: $datetime } ) { sum { requests } dimensions { status datetimeHour } } } } } """ # Define Cloudflare API credentials API_KEY = "xxxxxxxxxxx" ZONE_ID = "xxxxxxxxxxxxxxx" API_EMAIL = "xxxxxxxxxx@xxxx.com" # Set up headers headers = { "X-Auth-Email": API_EMAIL, "X-Auth-Key": API_KEY, "Content-Type": "application/json" } # Set the variables for the query datetime = "2025-01-24T09:02:51.649Z" # Replace with your desired datetime zoneTag = ZONE_ID # Create the request body with variables payload = { "query": query, "variables": { "zoneTag": zoneTag, "datetime": datetime } } # Make the API request response = requests.post( url="https://api.cloudflare.com/client/v4/graphql", headers=headers, json=payload ) # Process the response if response.status_code >= 400: raise Exception(f"Error: {response.status_code}, {response.text}") data = response.json() # You can print or process the data as needed print(json.dumps(data, indent=4)) # Calculate Total Successful and Failed Requests success_count = 0 failed_count = 0 # Iterate through the groups and sum requests based on status for group in data['data']['viewer']['zones'][0]['workersZoneInvocationsAdaptiveGroups']: status = group['dimensions']['status'] requests = group['sum']['requests'] if status == 'ok': success_count += requests else: failed_count += requests # Output the results print(f"Total Successful Requests (ok): {success_count}") print(f"Total Failed Requests: {failed_count}")
Cached and Uncached Requests
The following code returns the number of cached and uncached subrequests your website is getting using Cloudflare Workers.
import requests import json # Define the GraphQL query query = """ query getAnalyticsQuery($zoneTag: String!, $datetime: String!) { viewer { zones(filter: { zoneTag: $zoneTag }) { workersZoneSubrequestsAdaptiveGroups( limit: 10000, filter: { datetime_geq: $datetime } ) { sum { subrequests } dimensions { cacheStatus datetimeHour } } } } } """ # Define Cloudflare API credentials API_KEY = "xxxxxxxx" ZONE_ID = "xxxxxxxx" API_EMAIL = "xxxx@gmail.com" # Set up headers headers = { "X-Auth-Email": API_EMAIL, "X-Auth-Key": API_KEY, "Content-Type": "application/json" } # Set the variables for the query datetime = "2025-01-24T09:02:51.649Z" # Replace with your desired datetime zoneTag = ZONE_ID # Replace with the correct zoneTag # Create the request body with variables payload = { "query": query, "variables": { "zoneTag": zoneTag, "datetime": datetime } } # Make the API request response = requests.post( url="https://api.cloudflare.com/client/v4/graphql", headers=headers, json=payload ) # Process the response if response.status_code >= 400: raise Exception(f"Error: {response.status_code}, {response.text}") data = response.json() # You can print or process the data as needed print(json.dumps(data, indent=4)) # Calculate Total Successful and Failed Requests success_count = 0 failed_count = 0 for group in data['data']['viewer']['zones'][0]['workersZoneSubrequestsAdaptiveGroups']: status = group['dimensions']['cacheStatus'] requests = group['sum']['subrequests'] if status == 9: success_count += requests else: failed_count += requests # Output the results print(f"Total Uncached subrequests: {success_count}") print(f"Total Cached subrequests: {failed_count}")
Share Share Tweet