Skip to content

API Authentication

All requests to the Ruby Public Developer REST API must be authenticated. Ruby supports two enterprise-grade authentication mechanisms:

  • Bearer Token Authentication — the standard and recommended mechanism for most backend server-to-server integrations.
  • HMAC-SHA256 Request Signing — provides request integrity verification, payload tamper resistance, and automatic defense against replay attacks when heightened security controls are required.

1. Generating API Keys

API keys are created and managed in the Ruby CMS:

  1. Log in to the Ruby dashboard and navigate to Settings > Developer > API Keys. This requires the Owner or Admin role.
  2. Click Create API Key.
  3. Enter a descriptive label for the key, such as Production Backend or Staging Marketing Bot.
  4. Select the authentication method (Bearer or HMAC) and assign the required API scopes.
  5. Click Create Key and securely copy the generated Key ID (ak_...) and Secret (as_... or hs_...).

Store Secrets Securely

API secrets are displayed only once when the key is created. Ruby stores secret hashes securely and does not allow them to be retrieved later through the CMS or API.

If a secret is lost or compromised, revoke the affected API key immediately in Settings > Developer and create a new one.

Never Expose API Secrets

API credentials are intended strictly for secure server-to-server communication. Never expose API secrets in client-side JavaScript, mobile applications, web browsers, source repositories, or publicly accessible environments.


2. Authentication Methods

Bearer Token Authentication is straightforward to implement and recommended for most server-side integrations.

Include the API credentials in the standard HTTP Authorization header formatted as <key_id>:<key_secret>:

Authorization: Bearer <key_id>:<key_secret>

Example Request

curl -X GET "https://api.rby.one/v1/domains" \
  -H "Authorization: Bearer ak_01J8K92M4:as_9f8a7b6c5d4e3f2a1b0c"
import requests

API_KEY = "ak_01J8K92M4:as_9f8a7b6c5d4e3f2a1b0c"

response = requests.get(
    "https://api.rby.one/v1/domains",
    headers={
        "Authorization": f"Bearer {API_KEY}"
    }
)
print(response.status_code, response.json())
const API_KEY = "ak_01J8K92M4:as_9f8a7b6c5d4e3f2a1b0c";

const response = await fetch("https://api.rby.one/v1/domains", {
  headers: {
    "Authorization": `Bearer ${API_KEY}`
  }
});

const data = await response.json();
console.log(response.status, data);

Method 2: HMAC-SHA256 Request Signing

For enterprise environments requiring message integrity verification and defense against intercepted replay attacks, Ruby supports HMAC-SHA256 request signing.

Required Headers

Every HMAC-signed request must supply three custom headers:

Header Description Example
X-Rby-Key-Id The public Key ID associated with your HMAC API key. ak_01J8K92M4
X-Rby-Timestamp Current Unix timestamp in seconds (UTC). Must be within 60 seconds of server time. 1731024000
X-Rby-Signature Hex-encoded HMAC-SHA256 signature calculated over the canonical payload. sha256=a1b2c3d4... or a1b2c3d4...

Signature Canonical String

The signature is computed over a newline-delimited canonical string:

{timestamp}\n{METHOD}\n{path}\n{body_sha256}

Where:

  • {timestamp}: The exact integer timestamp string sent in the X-Rby-Timestamp header.
  • {METHOD}: The uppercase HTTP verb (GET, POST, PUT, DELETE).
  • {path}: The absolute request path including leading slash (e.g. /v1/domains or /v1/links).
  • {body_sha256}: The lowercase hexadecimal SHA-256 hash of the exact raw body bytes. For requests without a body (GET, DELETE), use the SHA-256 hash of an empty byte string (e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855).

Replay Attack Window

The X-Rby-Timestamp header must be within 60 seconds of Ruby server time (UTC). Requests outside this validity window return 401 Unauthorized (Request expired).

Signing Implementation Examples

import hashlib
import hmac
import json
import time
from typing import Any, Dict, Optional
import requests

KEY_ID = "ak_01J8K92M4"
HMAC_SECRET = "hs_9f8a7b6c5d4e3f2a1b0c"
BASE_URL = "https://api.rby.one"


def build_hmac_headers(method: str, path: str, body_bytes: bytes) -> dict[str, str]:
    timestamp = str(int(time.time()))
    body_hash = hashlib.sha256(body_bytes).hexdigest()

    # Canonical string: {timestamp}\n{METHOD}\n{path}\n{body_hash}
    sig_string = f"{timestamp}\n{method.upper()}\n{path}\n{body_hash}"

    signature = hmac.new(
        key=HMAC_SECRET.encode("utf-8"),
        msg=sig_string.encode("utf-8"),
        digestmod=hashlib.sha256
    ).hexdigest()

    return {
        "X-Rby-Key-Id": KEY_ID,
        "X-Rby-Timestamp": timestamp,
        "X-Rby-Signature": signature,
        "Content-Type": "application/json"
    }


def send_authenticated_request(
    method: str,
    path: str,
    payload: Optional[Dict[str, Any]] = None
) -> requests.Response:
    url = f"{BASE_URL}{path}"

    if payload is not None and method.upper() not in ["GET", "HEAD", "DELETE"]:
        # Use separators=(',', ':') to serialize compact JSON without extra whitespace
        body_bytes = json.dumps(payload, separators=(',', ':')).encode("utf-8")
    else:
        body_bytes = b""

    headers = build_hmac_headers(method, path, body_bytes)
    return requests.request(method=method, url=url, data=body_bytes if body_bytes else None, headers=headers)


# Example 1: GET request without body
res_get = send_authenticated_request("GET", "/v1/domains")
print("GET /v1/domains:", res_get.status_code, res_get.json())

# Example 2: POST request with JSON payload
new_link = {
    "destination_url": "https://example.com/summer-promo",
    "domain": "rby.one",
    "title": "Summer Campaign"
}
res_post = send_authenticated_request("POST", "/v1/links", payload=new_link)
print("POST /v1/links:", res_post.status_code, res_post.json())
import { createHash, createHmac } from "crypto";

const KEY_ID = "ak_01J8K92M4";
const HMAC_SECRET = "hs_9f8a7b6c5d4e3f2a1b0c";
const BASE_URL = "https://api.rby.one";

async function sendSignedRequest(
  method: string,
  path: string,
  payload?: Record<string, unknown>
) {
  const timestamp = Math.floor(Date.now() / 1000).toString();
  const bodyBytes = payload && !["GET", "HEAD", "DELETE"].includes(method.toUpperCase())
    ? Buffer.from(JSON.stringify(payload))
    : Buffer.alloc(0);

  const bodyHash = createHash("sha256").update(bodyBytes).digest("hex");
  const sigString = `${timestamp}\n${method.toUpperCase()}\n${path}\n${bodyHash}`;

  const signature = createHmac("sha256", HMAC_SECRET)
    .update(sigString)
    .digest("hex");

  const headers: Record<string, string> = {
    "X-Rby-Key-Id": KEY_ID,
    "X-Rby-Timestamp": timestamp,
    "X-Rby-Signature": signature,
    "Content-Type": "application/json"
  };

  const response = await fetch(`${BASE_URL}${path}`, {
    method,
    headers,
    body: bodyBytes.length > 0 ? bodyBytes : undefined
  });

  return { status: response.status, data: await response.json() };
}

// Execute signed calls
const domains = await sendSignedRequest("GET", "/v1/domains");
console.log("Domains:", domains.status, domains.data);

3. API Scopes & Access Control

Each API key is assigned one or more granular scopes upon creation. Requests to endpoints outside an API key's authorized scopes are rejected with 403 Forbidden.

Scope Description Granted Endpoints
links:read Read short link metadata, QR codes, and available domains GET /v1/links
GET /v1/links/lookup
GET /v1/links/{public_id}
GET /v1/domains
GET /v1/groups/{public_id}/links
links:write Create, update, delete short links, and run batch creations POST /v1/links
PUT /v1/links/{public_id}
DELETE /v1/links/{public_id}
POST /v1/groups/{public_id}/links/batch
groups:read Query campaign groups and export files GET /v1/groups
GET /v1/groups/{public_id}
GET /v1/groups/{public_id}/export
groups:write Create, update, and delete campaign groups POST /v1/groups
PUT /v1/groups/{public_id}
DELETE /v1/groups/{public_id}
analytics:read Retrieve aggregated analytics and click statistics GET /v1/links/{public_id}/stats
GET /v1/groups/{public_id}/stats

4. Error Responses

When an authentication check fails, Ruby returns standard HTTP error status codes wrapped in the standardized error envelope:

  • 401 Unauthorized: Missing, malformed, expired, or invalid credentials.

    {
      "error": {
        "code": "UNAUTHORIZED",
        "message": "Invalid token format. Expected {key_id}:{key_secret}",
        "param": null
      }
    }
    
    {
      "error": {
        "code": "UNAUTHORIZED",
        "message": "Request expired",
        "param": null
      }
    }
    
    {
      "error": {
        "code": "UNAUTHORIZED",
        "message": "Invalid HMAC signature",
        "param": null
      }
    }
    

  • 403 Forbidden: Valid credentials, but lacking the required scope for the target endpoint, or API access is not enabled on your plan.

    {
      "error": {
        "code": "FORBIDDEN",
        "message": "API key missing required scope: links:write",
        "param": null
      }
    }