Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 35 ยท Automation and Terraform

The DigitalOcean REST API and Automation

Call the DigitalOcean API v2 directly: bearer tokens, JSON requests, pagination links, rate limits with backoff, actions and a safe pattern for automation scripts.

Everything in the control panel, in doctl and in Terraform goes through one HTTP API. Knowing it helps when you write your own tools, use a language SDK, debug a failing automation, or need a feature a wrapper does not cover yet. The base URL is https://api.digitalocean.com/v2/, requests and responses are JSON, and every request needs an Authorization: Bearer <token> header.

DigitalOcean cannot be called from this site, so request examples are text, and the Python blocks are stand-ins that run against fake, in-memory responses to teach the client logic (pagination, rate limiting, polling).

Your first requests

Terminal
export DIGITALOCEAN_ACCESS_TOKEN=...   # from a secret store, never hard-code it

curl -s -H "Authorization: Bearer $DIGITALOCEAN_ACCESS_TOKEN" \
  "https://api.digitalocean.com/v2/account"

curl -s -H "Authorization: Bearer $DIGITALOCEAN_ACCESS_TOKEN" \
  "https://api.digitalocean.com/v2/droplets?tag_name=web&per_page=50"

Resources are plural nouns (/droplets, /volumes, /firewalls, /domains) and follow ordinary HTTP verbs: GET reads, POST creates, PUT or PATCH updates, DELETE removes (a successful delete returns 204 No Content). Creating a Droplet:

Terminal
curl -s -X POST -H "Content-Type: application/json" \
  -H "Authorization: Bearer $DIGITALOCEAN_ACCESS_TOKEN" \
  -d '{"name":"web-1","region":"nyc1","size":"s-1vcpu-1gb",
       "image":"ubuntu-24-04-x64","ssh_keys":[12345678],"tags":["web"]}' \
  "https://api.digitalocean.com/v2/droplets"

A 202 Accepted response contains the new Droplet in state new. Provisioning continues in the background, so scripts must poll until the status is active (or check the related action, which has its own status: in-progress, completed or errored).

Error responses carry an HTTP status and a JSON body with id and message: 401 bad token, 403 missing scope, 404 unknown resource, 422 invalid request (for example a size not offered in that region), 429 rate limited, 5xx try again later.

Pagination

List endpoints return one page at a time (default 20 items, maximum per_page of 200). The response has links.pages.next when there is more, and meta.total. Walk the next links until none is left.

Python Stand-in: follow pagination links

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Never assume the first page is everything: a script that reads only page one silently ignores resource number 21.

Rate limits and retries

Each token is limited to a number of requests per hour and per minute (about 5,000 per hour and 250 per minute at the time of writing; check the documentation). Responses include RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset headers. When you get 429, wait until the reset time or use exponential backoff with jitter: wait 1 s, then 2, 4, 8, plus a small random amount so many clients do not retry together.

Python Stand-in: exponential backoff

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The stand-in only adds up the waits instead of actually sleeping. In real code use time.sleep, and honour RateLimit-Reset when you have it.

Polling an action

flowchart LR
  A["POST /droplets"] --> B["202 + droplet id"]
  B --> C{"GET /droplets/id<br/>status?"}
  C -->|"new"| D["wait 5 s"]
  D --> C
  C -->|"active"| E["Continue: tag, firewall, DNS"]

Creation is asynchronous: poll with a timeout rather than assuming the resource is ready.

Using an SDK

You rarely need raw curl. Official and community clients exist for Go (godo, which doctl and the Terraform provider use) and Python (pydo), and many others. A client handles authentication, pagination helpers and retries, but understanding the HTTP model above makes errors readable.

A safe automation pattern

  • Idempotent steps. Check whether a resource exists (by name or tag) before creating it, so a rerun does not make duplicates.
  • Tag everything you create from automation (for example managed-by:script) so you can find and clean it up.
  • Timeouts and limits. Poll with a deadline, cap retries and cap the number of resources a script may create.
  • Least-privilege tokens with custom scopes, and an expiry.
  • Webhooks and events: the API does not push you events for every change, so for notifications use monitoring alerts or poll sparingly.
  • For anything long-lived, prefer declarative tools such as Terraform.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How is every API request authenticated?

    The API uses bearer tokens created in the control panel.
  2. 2. Creating a Droplet returns 202. What should your script do next?

    Provisioning is asynchronous, so poll the Droplet or its action.
  3. 3. How do you read all pages of a list endpoint?

    per_page is capped, so follow the next links until none remain.
  4. 4. What is the right reaction to a 429 response?

    Backoff spreads retries out and respects the rate limit.

Summary

  • The API is JSON over HTTPS at /v2/ with bearer tokens; doctl and Terraform both use it.
  • Creation is asynchronous: poll the resource or action until it is ready.
  • Follow pagination links and handle 429 with exponential backoff.
  • Make automation idempotent, tagged, bounded and least-privilege.

Next: Terraform on DigitalOcean