---
title: graphql
description: Query Cloudflare's GraphQL Analytics API with schema-aware chaining,
  batched requests and raw GraphQL
---
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

```python
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`](graphql.md#cfgql) wraps [fastspec's GraphQL client](https://answerdotai.github.io/fastspec/gql.html) with Cloudflare's distilled schema and the same `CLOUDFLARE_*` credentials as [`CloudflareApi`](core.md#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`](graphql.md#build_gql_spec) introspects Cloudflare's GraphQL endpoint and writes compact lookup tables to `fastcflare/gql_spec.py`. [`CfGql`](graphql.md#cfgql) loads those tables offline with no startup request.

[source](https://github.com/AnswerDotAI/fastcflare/blob/main/fastcflare/graphql.py#L28)

### build\_gql\_spec

```python
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`.*

```python
from fastcflare.gql_spec import gqlspec
```

```python
len(gqlspec['types']), gqlspec['query']
```

## CfGql

[`CfGql`](graphql.md#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.

[source](https://github.com/AnswerDotAI/fastcflare/blob/main/fastcflare/graphql.py#L42)

### CfGql

```python
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:

```python
api_key = os.getenv('CLOUDFLARE_API_KEY')
gql = CfGql(api_key=api_key) if api_key else CfGql()
xdir(gql.account(), 'r2')
```

```python
doc(gql.account().r2StorageAdaptiveGroups)
```

Inspect filter input objects and `orderBy` enums with `gql.t`:

```python
doc(gql.t.AccountR2StorageAdaptiveGroupsOrderBy)
```

Query per-bucket R2 storage usage over the last two days:

```python
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:

```python
with expect_fail(TypeError, contains='needs a selection'): await gql.account()
with expect_fail(AttributeError, contains='has no field'): gql.account().no_such_dataset
```
