Sunday, February 16, 2025
No menu items!
HomeData Analytics and VisualizationCloudflare : How to Get Requests Data by Country

Cloudflare : How to Get Requests Data by Country

This tutorial explains how to fetch total requests and requests data by country from cloudflare.

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 = "[email protected]"

# 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
                    }
                ]
            }
        }
    ]
}

Read MoreListenData

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments