---
title: FastCF
description: Cloudflare REST client (`CloudflareApi`), token helpers, and `r2_s3_creds`
---
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

```python
import httpx
from collections import Counter
```

```python
tok = os.environ['CLOUDFLARE_API_TOKEN']
acctid = os.getenv('CLOUDFLARE_ACCOUNT_ID')
email = os.getenv('CLOUDFLARE_EMAIL')
api_key = os.getenv('CLOUDFLARE_API_KEY')
```

```python
base = 'https://api.cloudflare.com/client/v4'
```

```python
uhdrs = {'Authorization': f'Bearer {tok}'}
r = httpx.get(f'{base}/user/tokens/verify', headers=uhdrs)
r.json()['success']
```

```output
True
```

```python
if email and api_key:
    ghdrs = {'X-Auth-Email': email, 'X-Auth-Key': api_key, 'Content-Type': 'application/json'}
    r = httpx.get(f'{base}/user', headers=ghdrs)
    print(r.json()['success'])
```

```output
True
```

```python
r = httpx.get(f'{base}/zones', headers=uhdrs)
[(z['name'], z['id'][:8]) for z in r.json()['result'][:1]]
```

```output
[('aaa.as', '6afde8dc')]
```

## CloudflareApi

Cloudflare's operationIds are machine artifacts (`zones-get` vs `zones-0-get` — the `-0-` is a generator's dedup counter), so rather than cleaning them up we name every op mechanically from its verb and path: the group is the path's non-parameter segments, nested (`zones.dns_records`), and the method is the HTTP verb — except that when a group has both a collection GET and a single-item GET they become `list` and `get`. Two fixups keep the whole surface collision-free: sibling paths differing only by an interior parameter gain a `_by_<param>` suffix, and an action segment that would shadow an op folds into its parent as `<segment>_<verb>`. So `GET /zones` is `zones.list`, `GET /zones/{zone_id}` is `zones.get`, and `GET /user/tokens/verify` is `user.tokens.verify.get` — a user who knows the URL knows the call.

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

### cf\_names

```python
def cf_names(
    spec
):
```

*Map each op's canonical (verb, snaked-segments) key to (group\_segments, op\_name), collision-free across the surface*

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

### cf\_group\_func

```python
def cf_group_func(
    names
):
```

*A fastspec `group_func` looking up precomputed `names` by canonical verb\+path*

The parsed surface ships with the package as `cf_spec.py`, fastspec's compact form (`SpecParser.save`): 2.6MB instead of the 8MB raw schema, loaded in \~30ms instead of a \~0.3s parse, with the naming machinery above running only at regeneration time. [`build_spec`](core.md#build_spec) refreshes it from Cloudflare's published schema; op names can shift when the spec changes, so review that diff before shipping it.

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

### build\_spec

```python
def build_spec(
    nm:str='fastcflare/cf_spec.py',
    url:str='https://raw.githubusercontent.com/cloudflare/api-schemas/main/openapi.json'
):
```

*Regenerate the compact spec module `cf_spec.py` from Cloudflare's OpenAPI schema.*

```python
cli = OpenAPIClient(_cf_spec(), headers={'Authorization': f'Bearer {tok}', 'Content-Type': 'application/json'})
sorted(cli.groups)
```

```output
['accounts',
 'certificates',
 'internal',
 'ips',
 'live',
 'memberships',
 'organizations',
 'radar',
 'ready',
 'signed_url',
 'system',
 'tenants',
 'user',
 'users',
 'zones']
```

The naming is only trustworthy if it can never silently collide — `OpGroup` exposes ops with `setattr`, so a duplicate name would shadow its sibling (exactly the bug this design replaces). This walk asserts the built tree is clean: within every group, op names are unique (duplicates allowed only for the same endpoint spelled two ways in the spec) and no op shares a name with a subgroup.

```python
def _surface_ok(g):
    nms = [o.name for o in g.ops]
    for n,c in Counter(nms).items():
        if c>1: assert len({tuple(snake(s) for s in o.op_spec.path.strip('/').split('/')) for o in g.ops if o.name==n})==1, f'dup op {g.name}.{n}'
    assert not set(nms)&set(g.subgroups), f'op/subgroup shadow in {g.name}: {set(nms)&set(g.subgroups)}'
    for sg in g.subgroups.values(): _surface_ok(sg)

for grp in cli.groups.values(): _surface_ok(grp)
len(cli.groups), len(cli.groups['zones'].subgroups)
```

```output
(15, 60)
```

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

### CloudflareApi

```python
def CloudflareApi(
    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
    account_token:bool=False, # Is `token` an account-owned token (uses `/accounts/{account_id}/tokens/verify`)?
):
```

*Cloudflare API client supporting user tokens, account tokens, and global API keys*

```python
ucf = CloudflareApi()
(await ucf.verify()).result.status
```

```output
'active'
```

Listing and fetching zones are now distinct calls: `zones.list` filters the collection, `zones.get` takes a `zone_id`.

```python
ucf.zones.list
```

List Zones

Parameters:

- name (str, optional)
- status (str, optional)
- account\_id (str, optional)
- account\_name (str, optional)
- order (str, optional)
- direction (str, optional)
- page (float, default: 1)
- per\_page (float, default: 20)
- match (str, default: 'all')

```python
(await ucf.zones.list(name='answer.ai')).result[0].name
```

```output
'answer.ai'
```

```python
zid = (await ucf.zones.list()).result[0].id
(await ucf.zones.dns_records.list(zone_id=zid)).result[0].name
```

```output
'*.aaa.as'
```

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

### CloudflareApi.create\_token

```python
async def create_token(
    doms, # Domain names the token may act on
    perm_names, # Permission-group names, such as 'Zone Read' or 'DNS Write'. Names that don't match are skipped
    name, # Name for the new token
    grp:str='account.zone.', # Resource prefix after `com.cloudflare.api.`
    account_token:bool=False, # Create an account-owned token (nests zone resources under `account_id`)?
    account_id:str=None, # Account ID for account-owned tokens; defaults to `self.account_id`
):
```

*Create a user or account-owned API token limited to `doms`. The token's value is shown only in this response.*

```python
pgs = (await ucf.user.tokens.permission_groups.get()).result
[p.name for p in pgs if 'DNS' in p.name or 'Zone' in p.name][:20]
```

```output
['Account DNS Settings Read',
 'Account DNS Settings Write',
 'Cloudflare Zero Trust Secure DNS Locations Write',
 'DNS Firewall Read',
 'DNS Firewall Write',
 'DNS Read',
 'DNS View Read',
 'DNS View Write',
 'DNS Write',
 'Zone Custom Asset Read',
 'Zone Custom Asset Write',
 'Zone DNS Settings Read',
 'Zone DNS Settings Write',
 'Zone Read',
 'Zone Security Center Insights Read',
 'Zone Security Center Insights Write',
 'Zone Settings Read',
 'Zone Settings Write',
 'Zone Transform Rules Read',
 'Zone Transform Rules Write']
```

With two domains, the policy must carry two distinct zone resources — under the old colliding surface the `name` filter was silently dropped, every domain resolved to the same zone, and the dict collapsed them to one:

```python
tok = await ucf.create_token(['answer.ai', 'aaa.as'], ['Zone Read'], 'fastcflare-test-token')
assert len(tok.result.policies[0].resources)==2
tok.success, tok.result.name
```

```output
(True, 'fastcflare-test-token')
```

Clean up the token we just created:

```python
res = await ucf.user.tokens.delete(tok.result.id)
assert res.success
```

## R2 tokens and S3 credentials

Cloudflare R2 S3 credentials derive directly from an R2 API token: `access_key_id` is the token ID and `secret_access_key` is the SHA-256 hex digest of the token value. `create_r2_token` creates either an account-owned service token (default) or a user token, scoped to specific buckets or the whole account, and returns both the API response and derived S3 credentials.

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

### r2\_s3\_creds

```python
def r2_s3_creds(
    token_id:str, # Cloudflare API token ID (becomes `access_key_id`)
    token_value:str, # Cloudflare API token secret value (SHA-256 hex becomes `secret_access_key`)
    account_id:str=None, # Account ID; defaults to `CLOUDFLARE_ACCOUNT_ID`
    jurisdiction:str='default', # R2 jurisdiction (`'default'`, `'eu'`, `'fedramp'`)
)->fastcore.basics.AttrDict:
```

*Derive S3-compatible R2 credentials (`access_key_id`, `secret_access_key`, `endpoint`, `region`) from a Cloudflare R2 API token.*

[`r2_s3_creds`](core.md#r2_s3_creds) derives S3 credentials offline from any existing token pair:

```python
creds = r2_s3_creds('tok-id', 'tok-val', account_id='acct123')
assert len(creds.secret_access_key) == 64 and creds.endpoint == 'https://acct123.r2.cloudflarestorage.com'
creds.endpoint, creds.region
```

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

### CloudflareApi.create\_r2\_token

```python
async def create_r2_token(
    name:str, # Name for the new R2 token
    buckets=None, # Bucket name or iterable of bucket names; None grants account-wide R2 access
    write:bool=True, # Grant read/write access (False for read-only)
    account_id:str=None, # Account ID; defaults to `self.account_id`
    account_token:bool=True, # Create an account-owned service token (False for a user-owned token)
    jurisdiction:str='default', # R2 jurisdiction for bucket-scoped resources (`'default'`, `'eu'`, `'fedramp'`)
    expires_on:str=None, # Optional RFC3339 expiration timestamp
)->fastcore.basics.AttrDict:
```

*Create a Cloudflare R2 API token and return both the API response (`token`) and derived S3 credentials (`s3`).*

Global API key authentication fills `email` and `account_id` from `CLOUDFLARE_EMAIL` and `CLOUDFLARE_ACCOUNT_ID`:

```python
if api_key and email and acctid:
    gcf = CloudflareApi(api_key=api_key)
    assert (await gcf.verify()).success
```

```python
if api_key and email and acctid:
    r2 = await gcf.create_r2_token('fastcflare-r2-test-token', buckets='fastcflare-test-bucket', write=False)
    try:
        assert r2.token.success and len(r2.s3.secret_access_key) == 64
        r2_cf = CloudflareApi(token=r2.token.result.value, account_token=True)
        assert (await r2_cf.verify()).result.status == 'active'
    finally: assert (await gcf.accounts.tokens.delete(acctid, r2.token.result.id)).success
    r2.s3.endpoint, r2.s3.region
```
