Testing the DigitalOcean API with a scoped token

Infrastructure scripts are the code nobody tests until they fail during an incident. If yours talk to DigitalOcean (to resize a droplet, add a DNS record, rotate a database user), a few requests that check the token and the resources it can see make that failure happen on a Tuesday afternoon instead.

Step 1: Token and environment

In the control panel, API ▸ Tokens ▸ Generate New Token. Choose Custom scopes: for read-only checks, droplet:read, domain:read and account:read are enough. Set an expiry.

VariableValue
doBasehttps://api.digitalocean.com/v2
doTokendop_v1_…, marked as secret

Authorization: Bearer token with {{doToken}}.

Step 2: The account

HTTP
GET {{doBase}}/account
JavaScript
const account = pm.response.json().account;
pm.test('token works and account is active', () => {
  pm.expect(pm.response.code).to.equal(200);
  pm.expect(account.status).to.equal('active');
});
pm.test('enough droplet quota', () => pm.expect(account.droplet_limit).to.be.at.least(5));

A quota check like the second one is the sort of thing that only fails when you're scaling up in a hurry. Better to find out here.

Step 3: Droplets by tag

HTTP
GET {{doBase}}/droplets?tag_name=api&per_page=200
JavaScript
const body = pm.response.json();
pm.test('api droplets running', () => {
  pm.expect(body.droplets.length).to.be.above(0);
  body.droplets.forEach((d) => pm.expect(d.status, d.name).to.equal('active'));
});
console.log('total:', body.meta.total, 'next:', body.links?.pages?.next || 'none');

Pagination is link-based: follow links.pages.next until it's missing. With per_page=200 most accounts fit on one page.

Step 4: DNS records

HTTP
GET {{doBase}}/domains/example.com/records?type=A&name=api.example.com
JavaScript
const records = pm.response.json().domain_records;
pm.test('api.example.com points at the load balancer', () => {
  pm.expect(records.map((r) => r.data)).to.include(pm.environment.get('lbIp'));
});

Step 5: Rate limits and errors

Every response has ratelimit-limit, ratelimit-remaining and ratelimit-reset (a Unix timestamp):

JavaScript
const left = Number(pm.response.headers.get('ratelimit-remaining'));
pm.test('rate limit not nearly used up', () => pm.expect(left).to.be.above(100));

Errors share one shape: {"id": "not_found", "message": "The resource you were accessing could not be found."}.

Statusid
401unauthorized: bad, expired or revoked token
403forbidden: the token's scopes don't allow this
404not_found
422unprocessable_entity: invalid parameters
429too_many_requests