Unit 1.1: IONOS CLOUD API, Authentication, and Async Model
Introduction
Throughout this course you build TaskBoard, a task management API with a web frontend, provisioned and deployed entirely with code from a Git repository.
Before you write any Terraform, you need to understand the layer every tool talks to: the IONOS CLOUD API. Terraform, ionosctl and the SDKs send the same HTTP requests you can send with curl. When a pipeline fails, the cause is often an authentication problem, a request that ran before its predecessor finished, or a client that ignored a rate limit.
In this unit you mint access tokens, call the API v6 directly, handle its asynchronous request model, and add backoff and pagination to a small Python client. In the Code Lab you provision TaskBoard's first data center and servers three ways.
1. The IONOS CLOUD API v6
The IONOS CLOUD API v6 is the core infrastructure REST API. It covers compute, containers, networking and backup resources in a single OpenAPI specification, version 6.0.
curl --request GET 'https://api.ionos.com/cloudapi/v6/datacenters' \
--header 'Authorization: Bearer <access_token>'
1.1 Base URLs and Versioning
The base URL for the API v6 is https://api.ionos.com/cloudapi/v6. Products such as Managed Kubernetes, Cross Connect, Flow Logs and Backup Service are managed through endpoints under /cloudapi/v6. Newer services, such as CDN, VPN Gateway and the database services, are published as separate standalone API specifications with their own base URLs and versioning.
For DBaaS for PostgreSQL, DBaaS for MariaDB and DBaaS for In-Memory DB, use the v2 APIs. They run on regional hosts with a /v2 path:
export PG_API="https://postgresql.de-txl.ionos.com/v2"
export MARIADB_API="https://mariadb.de-txl.ionos.com/v2"
You use these APIs in Module 2. The rule for now: check the base URL of each API before you call it.
1.2 Request Shape and Query Parameters
Send JSON with Content-Type: application/json. On GET requests, depth (0 to 10, default 0) controls how many levels of child objects the response expands, and pretty (default true) pretty-prints it.
curl --silent 'https://api.ionos.com/cloudapi/v6/datacenters?depth=1' \
--header "Authorization: Bearer ${IONOS_TOKEN}" | jq '.items[].properties.name'
2. Authentication
The API v6 accepts two methods: a bearer token (Authorization: Bearer <access_token>) and Basic Auth (Authorization: Basic <base64(username:password)>). Use bearer tokens for every automated workload.
2.1 Minting an Access Token
Both methods call the same Auth API endpoint, GET https://api.ionos.com/auth/v1/tokens/generate. The response contains a JSON Web Token (JWT) in the token field.
# Option A: bootstrap with your credentials (Basic Auth)
BASIC=$(printf '%s' 'username:password' | base64)
curl --silent --request GET 'https://api.ionos.com/auth/v1/tokens/generate?ttl=86400' \
--header "Authorization: Basic ${BASIC}" | jq -r '.token'
# Option B: mint a new access token with an existing secure token
curl --silent --request GET 'https://api.ionos.com/auth/v1/tokens/generate?ttl=86400' \
--header "Authorization: Bearer ${SECURE_TOKEN}" | jq -r '.token'
The ttl query parameter sets the token lifetime in seconds: minimum 60, maximum 31536000, and by default a generated token expires after one year. Short lifetimes limit damage from a leak.
Two rules limit Basic Auth. Accounts with 2-Factor Authentication enabled or forced must use bearer token authentication. The Basic Authentication method will also be discontinued in the near future, so do not build new automation on it.
2.2 Token Manager and Token Lifecycle
In the Data Center Designer (DCD), the Token Manager lives under Menu > Management > Token Manager. It generates tokens with one of these Time to Live (TTL) values: 1 Hour, 4 Hours, 1 Day, 7 Days, 30 Days, 60 Days, 90 Days, 180 Days or 365 Days.
Three facts shape token handling:
- The token value is displayed only once, on generation. You can download it as a text file at that moment.
- You can have up to 100 active tokens per user. When you reach this limit, the API returns an error for new tokens.
- Deleting a token in the Token Manager deactivates it immediately, even when it has not expired.
Keep the value in a secret store and inject it as an environment variable:
export IONOS_TOKEN="$(vault kv get -field=token secret/taskboard/ionos)"
2.3 Least-Privilege Scoping
To narrow what a token can do, generate it under a dedicated sub-user whose groups grant only the privileges that service needs. Privileges are grants for specific actions, such as createDatacenter, createSnapshot or reserveIp. Resource authorizations are Read, Edit and Sharing.
For TaskBoard, create taskboard-ci for infrastructure changes and a read-only user for monitoring scripts. A leaked monitoring token then cannot create resources.
3. The Asynchronous Provisioning Model
For the API v6, resources are created asynchronously. A POST that creates a resource returns 202 Accepted while provisioning is still running, and the Location response header holds a callback URL to poll the status of the operation.
curl --include --request POST 'https://api.ionos.com/cloudapi/v6/datacenters' \
--header "Authorization: Bearer ${IONOS_TOKEN}" \
--header 'Content-Type: application/json' \
--data '{"properties": {"name": "taskboard-dev", "location": "de/txl"}}'
HTTP/1.1 202 Accepted
Location: https://api.ionos.com/cloudapi/v6/requests/<requestId>/status
...
"metadata": { "state": "BUSY" }
3.1 Polling Request Status
GET /requests/{requestId}/status returns metadata.status, which is one of QUEUED, RUNNING, DONE or FAILED. Polling is not optional: a BUSY resource has at least one modification request pending, and all following requests are queued behind it.
import time
import requests
def wait_for_request(session, status_url, timeout=600):
"""Poll a request status URL until DONE; raise on FAILED or timeout."""
deadline = time.monotonic() + timeout
delay = 2
while time.monotonic() < deadline:
resp = session.get(status_url)
resp.raise_for_status()
meta = resp.json()["metadata"]
if meta["status"] == "DONE":
return
if meta["status"] == "FAILED":
raise RuntimeError(f"Request failed: {meta.get('message')}")
time.sleep(delay)
delay = min(delay * 2, 30)
raise TimeoutError(f"Request not DONE after {timeout}s: {status_url}")
3.2 Two Kinds of Errors
Fail-fast validation runs first: authorization, contract resources, and whether the configuration fits the product and location. These errors return synchronously, and the API returns only the first validation error it finds, so a retry can reveal the next one.
Provisioning errors happen later and appear in the request status, with an error code in the format VDC-x-xxx. Check both the POST response and the final request status.
4. Building a Resilient Client
4.1 Rate Limiting and Backoff
When you exceed the request rate limit, the API returns 429. Three response headers let you throttle before that happens:
| Header | Meaning |
|---|---|
X-RateLimit-Remaining |
Requests that can still be made without triggering a failure response |
X-RateLimit-Limit |
The average number of requests per minute allowed |
X-RateLimit-Burst |
The maximum number of concurrent API requests allowed |
Wrap every call in a retry with exponential backoff and jitter:
import random
RETRYABLE = {429, 500, 503}
def call(session, method, url, max_attempts=6, **kwargs):
for attempt in range(max_attempts):
resp = session.request(method, url, **kwargs)
if resp.status_code not in RETRYABLE:
return resp
retry_after = resp.headers.get("Retry-After")
delay = float(retry_after) if retry_after else min(2 ** attempt, 60)
time.sleep(delay + random.uniform(0, 1))
resp.raise_for_status()
return resp
4.2 Pagination
Collections accept offset (default 0) and limit (minimum 1, maximum 10000). The response contains _links.next only when offset + limit is less than the total number of elements.
def list_all(session, url, page_size=100):
params = {"offset": 0, "limit": page_size}
while url:
page = call(session, "GET", url, params=params).json()
yield from page.get("items", [])
url = page.get("_links", {}).get("next")
params = None # the next URL already carries offset and limit
4.3 Status Codes and Error Bodies
Error responses carry httpStatus and a messages array of errorCode and message:
{ "httpStatus": 422, "messages": [ { "errorCode": "200", "message": "[VDC-yy-xxxx] ..." } ] }
| Code | Client action |
|---|---|
401 |
Mint a new token; check its expiry |
403 |
Check the user's group privileges |
404 |
Check the UUID, and that the create request is DONE |
409 |
Wait for the resource to leave BUSY, then retry |
422 |
Fix the request body |
429, 500, 503 |
Retry with backoff; contact support if a 500 persists |
5. SDKs and ionosctl
5.1 The SDKs
The SDKs that wrap the API v6 are available for Go, Java, Ruby, Python and NodeJS, published at github.com/ionos-cloud/sdk-go, sdk-java, sdk-ruby, sdk-python and sdk-nodejs. Their documentation lives at https://docs.ionos.com/cloud/sdk-tools-home. The SDKs wrap the same API, so the async rule from Section 3 applies unchanged. This unit uses plain HTTP in Python so every header stays visible.
5.2 ionosctl
Install ionosctl with a package manager:
brew tap ionos-cloud/homebrew-ionos-cloud && brew install ionosctl # Homebrew
snap install ionosctl # snap
scoop install ionos-cloud/ionosctl # Scoop
ionosctl checks the environment variables first (IONOS_TOKEN, or IONOS_USERNAME and IONOS_PASSWORD), then its config file. To write a config file, run ionosctl config login --token "$IONOS_TOKEN".
ionosctl compute datacenter list
ionosctl compute server list --all
ionosctl compute request list --cols RequestId,Method,Status,Message,Targets
ionosctl compute request wait --request-id REQUEST_ID --timeout 120
Create commands accept --wait (-w) to block until the resource is AVAILABLE. --timeout caps the wait, 600 seconds by default.
API Reference Quick Card
Key API endpoints for this unit's topic:
| Method | Endpoint | Description |
|---|---|---|
GET |
https://api.ionos.com/auth/v1/tokens/generate |
Mint a new access token (ttl in seconds) |
GET |
/datacenters |
List data centers (offset, limit, depth) |
POST |
/datacenters |
Create a data center (returns 202 and Location) |
POST |
/datacenters/{datacenterId}/servers |
Create a server |
GET |
/requests/{requestId}/status |
Poll an async request: QUEUED, RUNNING, DONE, FAILED |
Base URL: https://api.ionos.com/cloudapi/v6
Authentication: Authorization: Bearer <token>
Code Lab
Objective: Provision TaskBoard's development data center with curl, add one server with Python and one with ionosctl, and verify async completion for each.
Prerequisites:
- IONOS CLOUD account with an API token in
IONOS_TOKEN - curl, jq and Python 3 with the
requestspackage ionosctlinstalled (Section 5.2)
Step 1: Create the data center with curl and capture the request URL
RESP=$(curl --silent --dump-header headers.txt --request POST \
'https://api.ionos.com/cloudapi/v6/datacenters' \
--header "Authorization: Bearer ${IONOS_TOKEN}" \
--header 'Content-Type: application/json' \
--data '{"properties": {"name": "taskboard-dev", "location": "de/txl"}}')
export DC_ID=$(echo "$RESP" | jq -r '.id')
export STATUS_URL=$(grep -i '^location:' headers.txt | awk '{print $2}' | tr -d '\r')
echo "$DC_ID $STATUS_URL"
Expected output:
<datacenter-uuid> https://api.ionos.com/cloudapi/v6/requests/<requestId>/status
Step 2: Poll until DONE
until [ "$(curl -s "$STATUS_URL" -H "Authorization: Bearer ${IONOS_TOKEN}" | jq -r '.metadata.status')" = "DONE" ]; do
sleep 5
done; echo "datacenter ready"
Expected output:
datacenter ready
Step 3: Create a server with Python
Save as create_server.py, reusing wait_for_request and call from Sections 3.1 and 4.1:
import os, requests
API = "https://api.ionos.com/cloudapi/v6"
s = requests.Session()
s.headers.update({"Authorization": f"Bearer {os.environ['IONOS_TOKEN']}",
"Content-Type": "application/json"})
body = {"properties": {"name": "taskboard-api-py", "type": "VCPU",
"availabilityZone": "AUTO", "cores": 1, "ram": 2048}}
resp = call(s, "POST", f"{API}/datacenters/{os.environ['DC_ID']}/servers", json=body)
resp.raise_for_status()
wait_for_request(s, resp.headers["Location"])
print("server ready:", resp.json()["id"])
Expected output:
server ready: <server-uuid>
Step 4: Create a server with ionosctl
ionosctl compute server create --datacenter-id "$DC_ID" --name taskboard-api-cli \
--type VCPU --cores 1 --ram 2GB --wait
Expected output:
ServerId Name Type ... State
<server-uuid> taskboard-api-cli VCPU ... AVAILABLE
Step 5: Compare the results
ionosctl compute server list --datacenter-id "$DC_ID" --cols ServerId,Name,Type,Cores,State
Expected output:
ServerId Name Type Cores State
<uuid> taskboard-api-py VCPU 1 AVAILABLE
<uuid> taskboard-api-cli VCPU 1 AVAILABLE
Validation Checklist:
- [ ] Data center created via curl and its request reached
DONE - [ ] Python server created and
wait_for_requestreturned without error - [ ]
ionosctlserver reachedAVAILABLEwith--wait - [ ] Both servers show the same type and core count in Step 5
Cleanup:
# Deletes the data center and every resource it contains
ionosctl compute datacenter delete --datacenter-id "$DC_ID" --force --wait
Common Pitfalls
Developer mistakes to avoid with this unit's topic:
-
Skipping the request poll
- Problem: Your script creates a data center and immediately creates a server in it, then reads the server before it exists. The follow-up logic fails or times out.
- Why it happens: The
202response only means "accepted". The data center isBUSYuntil its request isDONE. - Fix: Read the
Locationheader and callwait_for_request()(Section 3.1) before every dependent operation, or use--waitinionosctl.
-
Treating a 202 as success
- Problem: The pipeline reports green, but the resource never appears.
- Why it happens: Provisioning errors appear only in the request status (Section 3.2).
- Fix: Fail the job when the request status is
FAILED, and logmetadata.message.
-
Hard-coding a long-lived personal token
- Problem: A token in a CI variable leaks, or stops working when it expires and nobody knows who owns it.
- Why it happens: Tokens are generated with a default lifetime of one year, and a token generated under a personal administrator account is not scoped to one service.
- Fix: Generate the token under a dedicated sub-user with minimal privileges, set an explicit
ttl, and store it in a secret store.
Summary
You can now talk to IONOS CLOUD the way every tool does: mint a bearer token, call the API v6, and wait for asynchronous requests to finish before you build on them. Your Python client retries with backoff, walks paginated collections and reads structured error bodies. In Unit 1.2, Terraform takes over this polling for you, and knowing it here lets you debug it there.
Key Points:
- The API v6 base URL is
https://api.ionos.com/cloudapi/v6; DBaaS APIs have their own regional hosts - Mint access tokens with
GET /auth/v1/tokens/generate, setttl, and store the value at once - A create returns
202plus aLocationheader; poll/requests/{id}/statusuntilDONE - Fail-fast validation errors are synchronous; provisioning errors appear only in the request status
- Use backoff for
429, and page withoffset,limitand_links.next
Important Terminology:
- Access token: A JWT sent as
Authorization: Bearer <token>; its lifetime is set withttlat generation - Request status: The resource behind the
Locationheader; reportsQUEUED,RUNNING,DONEorFAILED - BUSY: Resource state meaning at least one modification request is pending; further requests are queued
- Fail-fast validation: Synchronous checks before queuing; the API returns only the first error it finds
- depth: Query parameter (0 to 10) that controls how many levels of child objects a response expands
Next Steps
Continue Learning: Unit 1.2: Terraform Provider and Core Patterns
Related Topics: