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.
| Variable | Value |
|---|---|
cfBase | https://api.cloudflare.com/client/v4 |
cfToken | the token, marked as secret |
zoneName | example-staging.com |
Authorization: Bearer token with {{cfToken}}.
Step 2: Verify the token
GET {{cfBase}}/user/tokens/verifyconst 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:
const b = pm.response.json();
if (!b.success) console.log(JSON.stringify(b.errors));Step 3: Find the zone
GET {{cfBase}}/zones?name={{zoneName}}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
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"}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.
GET {{cfBase}}/zones/{{zoneId}}/dns_records?name=pr-123.{{zoneName}}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
| Status | Usually means |
|---|---|
400 | invalid record: wrong type, bad content, a duplicate |
403 | the token lacks the permission or the zone (errors[0].code is 10000 for authentication) |
404 | wrong zone or record id |
429 | rate 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.