A client that fails usefully instead of throwing KeyError.
Errors covers the shape and the codes. This is how to build a client around them once, rather than checking "error" in payload at four hundred call sites.
One place that unwraps
# One wrapper: non-JSON bodies pass through, an error envelope fails the call.call() { local method="$1" path="$2" shift 2 local body body=$(curl -sS -X "$method" \ -H "X-API-Key: $DASHLINK_API_KEY" \ "https://api.dashlink.ai/api/v1/$path" \ "$@") || return if echo "$body" | jq -e '.error' >/dev/null; then echo "$body" | jq -r '.error | "\(.code // "ERROR"): \(.message)"' >&2 return 1 fi echo "$body" | jq '.data'}
class DashlinkError extends Error { constructor(message, { code, status, details } = {}) { super(message); this.name = "DashlinkError"; this.code = code; this.status = status; this.details = details ?? {}; }}class RateLimited extends DashlinkError { constructor(message, retryAfter, options) { super(message, options); this.name = "RateLimited"; this.retryAfter = retryAfter; }}class Dashlink { static BASE = "https://api.dashlink.ai/api/v1"; constructor(apiKey) { this.headers = { "X-API-Key": apiKey }; } async call(method, path, { query, body } = {}) { const url = new URL(`${Dashlink.BASE}/${path}`); if (query) url.search = new URLSearchParams(query).toString(); const response = await fetch(url, { method, headers: this.headers, body }); // Reports return a file rather than an envelope, so only parse // when we were actually sent JSON. const type = response.headers.get("content-type") ?? ""; if (!type.startsWith("application/json")) { if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.arrayBuffer(); } const payload = await response.json(); if (!payload.error) return payload.data; const { message, code, status_code: status, details } = payload.error; if (code === "RATE_LIMIT_EXCEEDED") { const retryAfter = Number(response.headers.get("Retry-After") ?? 60); throw new RateLimited(message, retryAfter, { code, status, details }); } throw new DashlinkError(message, { code, status, details }); }}
import requestsclass DashlinkError(Exception): def __init__(self, message, code=None, status=None, details=None): super().__init__(message) self.code = code self.status = status self.details = details or {}class RateLimited(DashlinkError): def __init__(self, message, retry_after, **kwargs): super().__init__(message, **kwargs) self.retry_after = retry_afterclass Dashlink: BASE = "https://api.dashlink.ai/api/v1" def __init__(self, api_key, session=None): self.session = session or requests.Session() self.session.headers["X-API-Key"] = api_key def call(self, method, path, **kwargs): response = self.session.request(method, f"{self.BASE}/{path}", **kwargs) # Reports return a file rather than an envelope, so only parse # when we were actually sent JSON. if not response.headers.get("content-type", "").startswith("application/json"): response.raise_for_status() return response.content payload = response.json() if "error" not in payload: return payload["data"] error = payload["error"] cls = RateLimited if error.get("code") == "RATE_LIMIT_EXCEEDED" else DashlinkError extra = ( {"retry_after": int(response.headers.get("Retry-After", 60))} if cls is RateLimited else {} ) raise cls( error["message"], code=error.get("code"), status=error.get("status_code"), details=error.get("details"), **extra, )
package dashlinkconst base = "https://api.dashlink.ai/api/v1"type Error struct { Message string Code string Status int Details map[string]any // Set only when Code is RATE_LIMIT_EXCEEDED. RetryAfter int}func (e *Error) Error() string { return e.Message }type Client struct { APIKey string HTTP *http.Client}func (c *Client) Call(method, path string, body io.Reader) ([]byte, error) { req, err := http.NewRequest(method, base+"/"+path, body) if err != nil { return nil, err } req.Header.Set("X-API-Key", c.APIKey) resp, err := c.HTTP.Do(req) if err != nil { return nil, err } defer resp.Body.Close() raw, err := io.ReadAll(resp.Body) if err != nil { return nil, err } // Reports return a file rather than an envelope, so only parse // when we were actually sent JSON. if !strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") { if resp.StatusCode >= 400 { return nil, fmt.Errorf("http %d", resp.StatusCode) } return raw, nil } var payload struct { Data json.RawMessage `json:"data"` Error *struct { Message string `json:"message"` Code string `json:"code"` StatusCode int `json:"status_code"` Details map[string]any `json:"details"` } `json:"error"` } if err := json.Unmarshal(raw, &payload); err != nil { return nil, err } if payload.Error == nil { return payload.Data, nil } apiErr := &Error{ Message: payload.Error.Message, Code: payload.Error.Code, Status: payload.Error.StatusCode, Details: payload.Error.Details, } if apiErr.Code == "RATE_LIMIT_EXCEEDED" { apiErr.RetryAfter = 60 if after, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil { apiErr.RetryAfter = after } } return nil, apiErr}
require "net/http"require "json"class DashlinkError < StandardError attr_reader :code, :status, :details def initialize(message, code: nil, status: nil, details: nil) super(message) @code = code @status = status @details = details || {} endendclass RateLimited < DashlinkError attr_reader :retry_after def initialize(message, retry_after:, **kwargs) super(message, **kwargs) @retry_after = retry_after endendclass Dashlink BASE = "https://api.dashlink.ai/api/v1".freeze def initialize(api_key) @api_key = api_key end def call(method, path, params = nil) uri = URI("#{BASE}/#{path}") request = Net::HTTP.const_get(method.to_s.capitalize).new(uri) request["X-API-Key"] = @api_key request.set_form_data(params) if params && request.request_body_permitted? response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end # Reports return a file rather than an envelope, so only parse # when we were actually sent JSON. unless response["Content-Type"].to_s.start_with?("application/json") raise "HTTP #{response.code}" if response.code.to_i >= 400 return response.body end payload = JSON.parse(response.body) return payload["data"] unless payload.key?("error") error = payload["error"] attrs = { code: error["code"], status: error["status_code"], details: error["details"], } if error["code"] == "RATE_LIMIT_EXCEEDED" raise RateLimited.new(error["message"], retry_after: (response["Retry-After"] || 60).to_i, **attrs) end raise DashlinkError.new(error["message"], **attrs) endend
<?phpclass DashlinkError extends RuntimeException{ // Named errorCode, not code: Exception already declares an untyped // $code, and redeclaring it with a type is a fatal error. public function __construct( string $message, public readonly ?string $errorCode = null, public readonly ?int $status = null, public readonly array $details = [], ) { parent::__construct($message); }}class RateLimited extends DashlinkError{ public int $retryAfter = 60;}class Dashlink{ private const BASE = "https://api.dashlink.ai/api/v1"; public function __construct(private string $apiKey) { } public function call(string $method, string $path, array $fields = []) { $ch = curl_init(self::BASE . "/$path"); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => ["X-API-Key: {$this->apiKey}"], CURLOPT_HEADER => true, ]); if ($fields) { curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields)); } $raw = curl_exec($ch); $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $contentType = (string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); $headers = substr($raw, 0, $headerSize); $body = substr($raw, $headerSize); // Reports return a file rather than an envelope, so only parse // when we were actually sent JSON. if (!str_starts_with($contentType, 'application/json')) { if ($status >= 400) { throw new RuntimeException("HTTP $status"); } return $body; } $payload = json_decode($body, true); if (!isset($payload['error'])) { return $payload['data']; } $error = $payload['error']; if (($error['code'] ?? null) === 'RATE_LIMIT_EXCEEDED') { preg_match('/retry-after:\s*(\d+)/i', $headers, $m); $limited = new RateLimited( $error['message'], $error['code'], $error['status_code'] ?? null, $error['details'] ?? [], ); $limited->retryAfter = (int) ($m[1] ?? 60); throw $limited; } throw new DashlinkError( $error['message'], $error['code'] ?? null, $error['status_code'] ?? null, $error['details'] ?? [], ); }}
Every call now either returns data or raises something with a code on it.
Deciding what to do with each code
Group by what the caller should do, not by number:
FIX_THE_REQUEST = {"MISSING_PARAMETER", "INVALID_PARAMETER", "VALIDATION_ERROR"}FIX_THE_KEY = {"AUTHENTICATION_REQUIRED", "AUTHENTICATION_FAILED"}FIX_THE_PLAN = { "PERMISSION_DENIED", "FEATURE_LIMIT_EXCEEDED", "FEATURE_ACCESS_DENIED", "FEATURE_NOT_AVAILABLE_IN_PLAN", "SUBSCRIPTION_REQUIRED", "NO_SUBSCRIPTION", "PLAN_NOT_FOUND",}PICK_ANOTHER = {"DUPLICATE_ENTRY"}try: link = client.call("POST", "shortlinks/create_shortlink", files=fields)except DashlinkError as error: if error.code in PICK_ANOTHER: fields["back_half"] = (None, next_available_back_half()) link = client.call("POST", "shortlinks/create_shortlink", files=fields) elif error.code in FIX_THE_PLAN: notify_account_owner(error.message) else: raise
details is the useful part of an INVALID_PARAMETER: it names the parameter and usually lists what would have been accepted, which is exactly what your validation message should say.
Retry only what can change
RETRYABLE_STATUS = {500, 502, 503, 504}def with_retry(fn, attempts=4): for attempt in range(attempts): try: return fn() except RateLimited as error: time.sleep(error.retry_after) except DashlinkError as error: # A 400 will fail identically however many times it is sent. if error.status not in RETRYABLE_STATUS or attempt == attempts - 1: raise time.sleep(2 ** attempt)
Retrying a 403 burns your rate limit on a request that cannot succeed until you change something.
Bulk calls need their own check
A bulk call that partially fails is a 200. Nothing above catches it:
def assert_bulk_ok(result): if result["summary"]["failed"]: failures = [r for r in result["results"] if r["outcome"] == "error"] raise DashlinkError( f"{len(failures)} of {result['summary']['total']} items failed", details={"failures": failures}, ) return result
Or pass stop_on_error=true and let the whole batch roll back instead. Choose per operation: partial application is fine for a cleanup job and usually wrong for anything a user is watching.
Never log the key, and never log a whole request that carries one. Keys are shown once at creation and a leaked one has to be revoked and replaced everywhere it was deployed.