Testing the Cloudflare API with a scoped API token

Teams script Cloudflare for DNS records in preview environments, cache purges after a deploy, and firewall rules. These scripts run rarely and break silently, often because a token expired or lost a permission. A small test collection that runs before the deploy tells you first.

Step 1: A scoped token

In the Cloudflare dashboard, My Profile ▸ API Tokens ▸ Create Token, start from Edit zone DNS, and limit it to a test zone. Set an expiry and, if you can, restrict it to your CI's IP addresses.

VariableValue
cfBasehttps://api.cloudflare.com/client/v4
cfTokenthe token, marked as secret
zoneNameexample-staging.com

Authorization: Bearer token with {{cfToken}}.

Step 2: Verify the token

HTTP
GET {{cfBase}}/user/tokens/verify
JavaScript
const body = pm.response.json();
pm.test('token active', () => {
  pm.expect(body.success).to.equal(true);
  pm.expect(body.result.status).to.equal('active');
});

Put the success check in the collection's post-response script, and log errors when it's false:

JavaScript
const b = pm.response.json();
if (!b.success) console.log(JSON.stringify(b.errors));

Step 3: Find the zone

HTTP
GET {{cfBase}}/zones?name={{zoneName}}
JavaScript
const zones = pm.response.json().result;
pm.test('one zone found', () => pm.expect(zones).to.have.lengthOf(1));
pm.environment.set('zoneId', zones[0].id);

Step 4: Create, read and delete a DNS record

HTTP
POST {{cfBase}}/zones/{{zoneId}}/dns_records
Content-Type: application/json

{"type": "CNAME", "name": "pr-123.{{zoneName}}", "content": "preview.example.net", "ttl": 1, "proxied": true, "comment": "API test"}
JavaScript
const rec = pm.response.json().result;
pm.test('record created', () => {
  pm.expect(rec.name).to.equal(`pr-123.${pm.environment.get('zoneName')}`);
  pm.expect(rec.proxied).to.equal(true);
});
pm.environment.set('recordId', rec.id);

ttl: 1 means "automatic". Creating the same record twice fails with success: false and an error code in errors, which is worth a test if your preview script isn't idempotent.

HTTP
GET {{cfBase}}/zones/{{zoneId}}/dns_records?name=pr-123.{{zoneName}}
HTTP
DELETE {{cfBase}}/zones/{{zoneId}}/dns_records/{{recordId}}

This is exactly the flow of a preview environment for each pull request, and the delete belongs in a cleanup step.

Step 5: Errors

StatusUsually means
400invalid record: wrong type, bad content, a duplicate
403the token lacks the permission or the zone (errors[0].code is 10000 for authentication)
404wrong zone or record id
429rate limited

A 403 with a valid token usually means its scope doesn't include that zone. The token verify call still answers active, so test a real zone call too.