graphql
Query Cloudflare's GraphQL Analytics API with schema-aware chaining, batched requests and raw GraphQL
from datetime import datetime, timezone, timedelta
from fastcore.test import *
from pyskills import xdir, doc
Cloudflare exposes R2 storage and operations, Workers, KV, D1, DNS, HTTP, and firewall analytics exclusively through its GraphQL Analytics API.
CfGql wraps fastspec's GraphQL client with Cloudflare's distilled schema and the same CLOUDFLARE_* credentials as CloudflareApi. Explore datasets offline with xdir, doc, and gql.t, chain attributes with keyword arguments to build field-checked queries, or pass raw GraphQL text directly.
The distilled schema
build_gql_spec introspects Cloudflare's GraphQL endpoint and writes compact lookup tables to fastcflare/gql_spec.py. CfGql loads those tables offline with no startup request.
build_gql_spec
def build_gql_spec(
nm:str='fastcflare/gql_spec.py', # Output module path
url:str='https://api.cloudflare.com/client/v4/graphql', # Cloudflare GraphQL endpoint
token=None, # API token; defaults to `CLOUDFLARE_API_TOKEN` when `api_key` and `email` aren't given
email=None, # Account email for a global API key; defaults to `CLOUDFLARE_EMAIL`
api_key=None, # Global API key; defaults to `CLOUDFLARE_API_KEY` when no token is given or set
):
Regenerate the distilled GraphQL schema tables shipped as fastcflare.gql_spec.
from fastcflare.gql_spec import gqlspec
len(gqlspec['types']), gqlspec['query']
CfGql
CfGql configures GqlClient with Cloudflare's GraphQL endpoint, the bundled schema, and CLOUDFLARE_* authentication. account() and zone() build filtered viewer.accounts and viewer.zones fragments.
CfGql
def CfGql(
token=None, # API token; defaults to `CLOUDFLARE_API_TOKEN` when `api_key` and `email` aren't given
account_id=None, # Account ID; defaults to `CLOUDFLARE_ACCOUNT_ID`
email=None, # Account email for a global API key; defaults to `CLOUDFLARE_EMAIL`
api_key=None, # Global API key; defaults to `CLOUDFLARE_API_KEY` when no token is given or set
):
Cloudflare GraphQL Analytics client using the shipped distilled schema
Discovery and R2 analytics
Use xdir and doc to inspect available datasets and filter arguments offline without sending a request:
api_key = os.getenv('CLOUDFLARE_API_KEY')
gql = CfGql(api_key=api_key) if api_key else CfGql()
xdir(gql.account(), 'r2')
doc(gql.account().r2StorageAdaptiveGroups)
Inspect filter input objects and orderBy enums with gql.t:
doc(gql.t.AccountR2StorageAdaptiveGroupsOrderBy)
Query per-bucket R2 storage usage over the last two days:
if api_key and gql.account_id:
since = (datetime.now(timezone.utc) - timedelta(days=2)).strftime('%Y-%m-%d')
f = gql.account().r2StorageAdaptiveGroups(filter={'date_geq': since}, limit=20, orderBy=['max_payloadSize_DESC'])
rows = (await f('dimensions { bucketName } max { payloadSize objectCount }'))[0]
assert isinstance(rows, (list, L))
[(r.dimensions.bucketName, r.max.payloadSize, r.max.objectCount) for r in rows]
Validation and raw queries
Unfinished fragments and unknown fields fail locally before any network request:
with expect_fail(TypeError, contains='needs a selection'): await gql.account()
with expect_fail(AttributeError, contains='has no field'): gql.account().no_such_dataset