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.
| Variable | Value |
|---|---|
doBase | https://api.digitalocean.com/v2 |
doToken | dop_v1_…, marked as secret |
Authorization: Bearer token with {{doToken}}.
Step 2: The account
GET {{doBase}}/accountconst 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
GET {{doBase}}/droplets?tag_name=api&per_page=200const 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
GET {{doBase}}/domains/example.com/records?type=A&name=api.example.comconst 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):
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."}.
| Status | id |
|---|---|
401 | unauthorized: bad, expired or revoked token |
403 | forbidden: the token's scopes don't allow this |
404 | not_found |
422 | unprocessable_entity: invalid parameters |
429 | too_many_requests |