Clokeep Clokeep Docs
Documentation API Reference
DevelopersHandle errors and rate limits
Developers View as Markdown

Handle errors and rate limits

Decide for each error whether a script retries, waits or stops, and stay inside the rate limit.

Every error answer from the API is JSON with a message. The full list of statuses and messages is under Errors in the API introduction. This page says what a script should do with each.

React to each status

Status Retry? What the script does
401 No Stop. The token is missing, wrong, revoked or expired. Log it and alert a person: a new token is needed.
403 No Stop and log message. It says why, such as a read token calling a change, or a role that does not allow the call.
404 No Log the URL. The id is wrong, the record was deleted, or it belongs to another client.
409 Not in a loop Something is already in progress. See A conflict below.
422 Not unchanged Log message and errors. Fix the body or the setup first. Sending the same request again gets the same answer.
429 Yes Wait the seconds in Retry-After, then send it again.
503 Yes, a few times The backup or its file list cannot be read from storage. message says why. storage unreachable and still being fetched by another request can pass: wait, then try again, with a longer wait each time. Other reasons, such as missing from storage, do not: give up after a few tries and log it.

Log the status, the method, the path and the message of every error. Never log the Authorization header.

A conflict

A 409 from POST /plans/{plan}/run means the plan already has a run that is queued or running. Find it with GET /backup-runs?plan_id=41&status=running, or status=queued, pick the run whose kind is backup, and follow it. A 409 from POST /artifacts/{artifact}/restore means the server already runs a restore. Wait until it ends. See Run a backup through the API.

Stay inside the rate limit

Each user may make 120 requests a minute in each client, counted over all of their tokens for that client together. Two scripts that use two tokens of the same user in the same client share the 120. A token in another client has its own 120.

Following a run does not count. GET /backup-runs/{backupRun}, its logs and the backup list endpoints are not limited. The exact list is under Rate limit.

An answer from a limited endpoint carries two headers:

X-RateLimit-Limit: 120
X-RateLimit-Remaining: 119

When X-RateLimit-Remaining nears 0, slow down. Past the limit, the answer is 429 with a Retry-After header: the number of seconds to wait before the next request.

Retry with a wait

This Python function sends a request and resends it after a 429 or a 503. After a 429 it waits as long as Retry-After says. After a 503 it waits 2 seconds, then twice as long each time, up to 60. It gives up after five tries.

import time

import requests

API = "https://app.clokeep.com/api/v1"
HEADERS = {
    "Authorization": "Bearer YOUR_API_TOKEN",
    "Accept": "application/json",
}


def call(method, path, tries=5, **kwargs):
    delay = 2

    for attempt in range(1, tries + 1):
        response = requests.request(
            method, API + path, headers=HEADERS, timeout=30, **kwargs
        )

        if response.status_code == 429:
            wait = int(response.headers.get("Retry-After", delay))
        elif response.status_code == 503:
            wait = delay
            delay = min(delay * 2, 60)
        else:
            return response

        if attempt < tries:
            print(f"{method} {path}: {response.status_code}, retrying in {wait} seconds")
            time.sleep(wait)

    return response


response = call("GET", "/servers")
response.raise_for_status()
print(response.json()["meta"]["total"])

A 429 or a 503 means the request was not carried out, so the function may resend a POST too.

Resend a request that timed out

The API has no idempotency keys. When a request times out or the connection drops, you do not know whether it was carried out. Resending a GET is always safe. Before you resend anything else, check what happened:

  • POST /plans/{plan}/run. Look for the run first: GET /backup-runs?plan_id=41 lists the plan's runs, newest first. If a run with kind backup and trigger api was created after you sent the request, follow it. If you resend while that run is queued or running, the answer is 409 and nothing new is queued. If it has already ended, a resend starts a second backup.
  • POST /artifacts/{artifact}/restore. Look for the restore with GET /backup-runs?server_id=12: its kind is restore and restore.source_artifact_id is your backup's id. Do not resend without looking. A second restore after the first has ended writes the backup onto the server again.
  • POST /backup-runs/{backupRun}/cancel. Safe to resend. If the run has ended in the meantime, the answer is 422 with Backup run is not active and cannot be cancelled.
  • Creating a record, such as POST /servers. List the records first. If the first request went through, resending it can create a second record.

Next steps

Esc
↑↓to navigate↵to openEscto close