Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 35 ยท Getting Started

doctl and the DigitalOcean API: Tokens, Calls and Pagination

Automate DigitalOcean from the terminal: install doctl, authenticate with a scoped token, list and create resources, call the REST API with curl, paginate and respect rate limits.

Clicking in the control panel is fine for learning, but real infrastructure is created by scripts so it can be repeated, reviewed and shared. DigitalOcean gives you two tools for that: the REST API (https://api.digitalocean.com/v2) and doctl, an official command-line client that wraps the API. Terraform, GitHub Actions and most third-party tools use the same API under the hood.

All commands below are read-only on this site (no account is attached). The runnable examples are stand-ins that simulate the API's paging and rate limiting so you can practice the logic.

Authentication: personal access tokens

The API uses bearer tokens. In the control panel you open API and generate a personal access token. Two details matter:

  • The token is shown once. Copy it into a password manager or a secret store immediately.
  • Tokens can have scopes (custom, per resource type and action such as read or create). Prefer a token with only the scopes a job needs instead of a full-access token. A CI job that only deploys an app should not be able to delete databases.

Treat a token like a password: never commit it to Git, never paste it into a chat, and revoke it from the API page if it leaks. Give automation its own token, so that you can rotate or revoke it without disturbing people.

Installing and authenticating doctl

doctl is a single binary. It is available through package managers (Homebrew, Snap, Scoop, Chocolatey) and as a download from the project's GitHub releases.

Terminal
doctl version
doctl auth init --context my-team     # paste the token when asked
doctl auth list                       # shows saved contexts
doctl auth switch --context my-team
doctl account get                     # confirms the token works

A context is a named token. If you work with a personal team and a company team, create one context for each and switch between them. In CI you skip the interactive step and set the token as an environment variable:

Terminal
export DIGITALOCEAN_ACCESS_TOKEN="<token from your secret store>"
doctl account get

Everyday commands

doctl commands follow the pattern doctl <product> <resource> <action>. Compute resources live under doctl compute:

Terminal
doctl compute region list
doctl compute size list
doctl compute image list --public --format ID,Slug,Distribution

doctl compute droplet list --format ID,Name,PublicIPv4,Region,Status
doctl compute droplet create web-1 --region fra1 --size s-1vcpu-1gb \
  --image ubuntu-24-04-x64 --ssh-keys <fingerprint> --wait
doctl compute droplet delete web-1 --force

Three flags you will use constantly:

  • --format chooses columns, and --no-header removes the header row for scripting.
  • -o json prints raw JSON, which you can filter with jq.
  • --wait makes creation commands block until the resource is ready.

Other top-level groups include doctl databases, doctl apps, doctl kubernetes, doctl projects, doctl serverless and doctl monitoring. Run doctl <group> --help to explore; the help text is excellent.

Calling the API directly

Anything doctl can do, curl can do:

Terminal
curl -s -X GET "https://api.digitalocean.com/v2/droplets?per_page=2" \
  -H "Authorization: Bearer $DIGITALOCEAN_ACCESS_TOKEN" \
  -H "Content-Type: application/json"

A successful list response is a JSON object with the resources, a links section for paging and a meta.total count:

JSON
{
  "droplets": [ { "id": 314159, "name": "web-1", "status": "active" } ],
  "links": { "pages": { "next": "https://api.digitalocean.com/v2/droplets?page=2&per_page=2" } },
  "meta": { "total": 5 }
}

Common status codes: 200 (read OK), 201 or 202 (created or accepted), 204 (deleted, no body), 401 (bad token), 403 (token lacks scope), 404 (no such resource), 422 (invalid input) and 429 (too many requests).

Pagination

List endpoints return a page at a time: you pass page and per_page (the maximum per_page is 200). A client keeps requesting the URL in links.pages.next until that key disappears. Never assume everything fits on page one: accounts with many resources will otherwise look "empty" in your script.

Rate limits

The API limits how fast you can call it. As a guide, expect a limit of about 5,000 requests per hour and a short-burst limit per minute for each token. Responses carry headers such as RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset. When you get 429, wait until the reset time and retry. Good clients also add small random delays and avoid polling in tight loops: poll a new Droplet every few seconds, not every millisecond.

flowchart TD
  A["Request page 1"] --> B{"Status?"}
  B -- "200" --> C["Collect items"]
  C --> D{"links.pages.next?"}
  D -- "yes" --> A
  D -- "no" --> E["Done"]
  B -- "429" --> F["Wait until RateLimit-Reset"] --> A
  B -- "401 / 403" --> G["Stop: fix the token or scope"]

A robust list loop handles paging, rate limits and permission errors.

Stand-in: a fake API with paging and limits

The program simulates a list endpoint with 7 Droplets and a tiny rate limit, then collects everything with a loop. It is a stand-in; there is no network access and no real data.

Python Stand-in: paginate a list endpoint and handle 429

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.

Python Stand-in: build a curl command safely

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 token itself never appears in the command: the shell reads it from the environment variable, which is how you keep it out of your shell history and scripts.

Which tool when?

Need Best tool
Quick look or one-off change Control panel
Repeatable script, CI step doctl
Application code that manages resources REST API or an official client library (Python, Go and others)
Whole environments you can review and reproduce Terraform (Chapter 7)

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How often is a new personal access token displayed in the control panel?

    The token value is shown once, so store it in a secret manager right away.
  2. 2. A script lists Droplets but only ever sees 20 even though you have more. What is the likely bug?

    List endpoints return one page at a time; follow links.pages.next until it is absent.
  3. 3. What should a client do after receiving HTTP 429?

    429 means too many requests. Respect the reset header and retry later.
  4. 4. Why prefer a token with limited scopes for CI?

    Least privilege reduces the impact of a leaked token.
  5. 5. Which doctl flag blocks until a new resource is ready?

    --wait is used with create commands such as droplet create.

Summary

  • The REST API at /v2 uses bearer tokens; doctl is the official CLI built on it.
  • Generate scoped tokens, store them in a secret manager and keep them out of Git.
  • Use contexts to switch teams; use --format, -o json and --wait in scripts.
  • Follow links.pages.next for pagination and back off on 429.

Next: Droplet Sizes, Plans and Pricing