# API basics

> This page collects the rules every endpoint follows. The first half covers access (environments, API keys, scopes and roles), and the second covers requests: their shape and errors, paging, units, and how to retry safely.

Source: https://docs.releaseapi.com/api-basics.html

**At a glance**

- Send the key in `X-API-KEY`, and check a new key with `GET /v1/me/token`. Sandbox and production are separate, with different base URLs, data and keys.
- As a tenant under RecordJet you only hold **tenant keys**. They never need `tenantId`. Keep keys on your server, and save the secret right away, because it’s shown only once.
- A `401` means the key isn’t valid here (including the wrong scope), and a `403` means its role lacks the permission. Give your backend a `MEMBER` key.
- Requests and responses are JSON under `/v1`, with camelCase fields and UPPER_SNAKE enums. Read an error’s code from `message`, then `error`, then `exception`.
- Lists page with `limit` (max 100) and `offset` until `hasMore` is `false`. Filters that can’t be parsed are silently ignored.
- Money is in integer nano-euros, fees are exact decimals, shares are parts per million, and clocks run on UTC. A `PUT` to your own id is safe to retry, but a `POST` that creates something is not.

## Environments

ReleaseAPI runs two separate environments. They don’t share data, accounts or keys, so a sandbox key returns `401` in production, and a production key returns `401` in sandbox.

| Environment | API base URL | Dashboard |
| --- | --- | --- |
| **Sandbox** | `https://api-sandbox.releaseapi.com/v1` | [app-sandbox.releaseapi.com](https://app-sandbox.releaseapi.com) |
| **Production** | `https://api.releaseapi.com/v1` | [app.releaseapi.com](https://app.releaseapi.com) |

Use sandbox to build and test. Nothing you do there reaches a store, whereas production means real releases, real deliveries and real money. Both run the same API, so you build against sandbox and then switch the base URL and key. ReleaseAPI and `releaseapi.com` (API and dashboard) are the same product, built by RecordJet. There’s no self-service sign-up.

### Getting access

- **As a tenant under RecordJet** (most integrators): your RecordJet contact creates your tenant, in sandbox first and in production when you’re ready. The contact email on the tenant receives an invitation to the dashboard and becomes its `ADMIN`. From there you create your API keys and invite your team.
- **With your own client account** (companies with their own store deals): ReleaseAPI sets up the client and your first dashboard login with you. You then create tenants, members and keys yourself.

Sandbox never reaches a store. Accepted releases are never delivered (their sync stays queued), no store data is imported, and test data can be removed. See [sandbox behaviour](https://docs.releaseapi.com/api-basics.html#sandbox) for the full list.

## API keys

Send the key in the `X-API-KEY` header on every request. A key is a UUID. Any other value, a missing header, or an unknown key gets the same answer: `401 UNAUTHORIZED`.

`GET /v1/me/token`

**cURL**

```bash
curl https://api-sandbox.releaseapi.com/v1/me/token \
  -H "X-API-KEY: $RELEASEAPI_KEY"
```

**Node.js**

```javascript
const BASE = "https://api-sandbox.releaseapi.com/v1";

const res = await fetch(`${BASE}/me/token`, {
  headers: { "X-API-KEY": process.env.RELEASEAPI_KEY },
});
if (!res.ok) throw new Error(`Key rejected: ${res.status}`);
const me = await res.json();
console.log(me.tenant?.displayName ?? me.client.displayName, me.roles);
```

**Python**

```python
import os, requests

BASE = "https://api-sandbox.releaseapi.com/v1"

r = requests.get(f"{BASE}/me/token", headers={"X-API-KEY": os.environ["RELEASEAPI_KEY"]})
r.raise_for_status()
me = r.json()
print(me.get("tenant", me["client"])["displayName"], me["roles"])
```

**Response**

```json
{
  "token": {
    "clientId": "7c4a91e2-5d3b-4f08-a6e1-93b2c0d4e517",
    "tenantId": "b55ec853-f63b-4cb3-9c2f-868b4eb42f95",
    "description": "backend production",
    "accessRights": ["MEMBER"],
    "expiresAt": null,
    "lastUsedAt": "2026-10-04T09:12:40.118Z",
    "id": "0f6a2b9e-6c1d-4e8a-9a51-2b7f3d0c8e44",
    "createdAt": "2026-09-01T10:00:00Z"
  },
  "client": {
    "email": "distribution@recordjet.example",
    "displayName": "RecordJet",
    "id": "7c4a91e2-5d3b-4f08-a6e1-93b2c0d4e517",
    "createdAt": "2024-02-01T08:00:00Z"
  },
  "tenant": {
    "clientId": "7c4a91e2-5d3b-4f08-a6e1-93b2c0d4e517",
    "email": "label@lowtide.example",
    "displayName": "Lowtide Records",
    "webHookUrl": null,
    "avatarFileId": null,
    "accounting": {
      "clientDefaultFeePercentage": 0.15,
      "tenantDefaultFeePercentage": 0.2,
      "billingStatus": "UNBILLED"
    },
    "id": "b55ec853-f63b-4cb3-9c2f-868b4eb42f95",
    "createdAt": "2025-03-10T12:30:00Z"
  },
  "roles": ["MEMBER"],
  "permissions": [
    "ACCOUNTING_READ", "ACCOUNTING_WRITE", "API_TOKEN_READ",
    "ARTIST_READ", "ARTIST_WRITE", "CATALOG_READ", "…"
  ]
}
```

Make `GET /v1/me/token` your first call with a new key. Any valid key may call it, and it returns the key, its client and tenant, its roles and every permission they grant. Read the roles from `token.accessRights`, which every build returns. The top-level `roles` and `permissions` arrays and the tenant’s billing fields are newer and can be missing on an older deployment such as sandbox. If the response has no `tenant`, you hold a client key. As a tenant under RecordJet, `client` is RecordJet.

### When a key is refused

| Status | `message` | Cause |
| --- | --- | --- |
| `401` | `UNAUTHORIZED` | No header, not a UUID, unknown or deleted key, or a key from the other environment. Also returned when the endpoint doesn’t exist for your key’s [scope](https://docs.releaseapi.com/api-basics.html#scopes). |
| `401` | `API_TOKEN_DISABLED` | The key has been disabled. Re-enable it or use a different key. |
| `401` | `API_TOKEN_EXPIRED` | The key’s `expiresAt` date has passed. |
| `403` | `PERMISSION_DENIED` | The key is valid, but its [role](https://docs.releaseapi.com/api-basics.html#roles) doesn’t allow this action. |

## Scopes: client keys and tenant keys

The **client** holds the store contracts (for most integrators, RecordJet). Inside it sit **tenants**, each a separate catalog ([two ways to use ReleaseAPI](https://docs.releaseapi.com/concepts.html#two-ways)). A key belongs to exactly one level, which determines what it can see:

- **Tenant key**: A tenant key sees one tenant’s catalog and nothing else. The tenant is implied on every call, so you never send `tenantId`. As a tenant under RecordJet, this is the only kind of key you have, and the right one for your product backend.
- **Client key**: Client keys exist only for client accounts. A client key sees every tenant in the client. Lists accept a `?tenantId=` filter, and you must name the tenant in the body when you create something that belongs to one. Use it for operations tooling, reviews, statement imports and account administration.

In these docs, `$RELEASEAPI_KEY` (`process.env.RELEASEAPI_KEY`, `os.environ["RELEASEAPI_KEY"]`) is always your tenant key. Examples in the “Client accounts:” sections use `$RELEASEAPI_CLIENT_KEY` for a client key instead. Set it only if you run a client account.

*Diagram: A client contains tenants. A client key sees every tenant; a tenant key sees only its own tenant.* Every key belongs to one level. A tenant key sees only its own tenant and never needs `tenantId`. A client key sees every tenant and names the tenant when it writes.

### The `tenantId` rules

With a tenant key, leave `tenantId` out and the tenant is implied. The rules matter for client accounts.

- **Client key, write:** put `tenantId` in the body of anything tenant-owned. A full draft needs `release.tenantId`, for example. Leave it out and you get a `400`. The exact code depends on the endpoint (tables below).
- **Client key, list:** results span all tenants. Add `?tenantId=` to narrow them to one.
- **Tenant key, write:** leave `tenantId` out, or send your own tenant’s id. On draft writes, any other value gets a `400` (codes in the tables below).
- **Tenant key, list:** results are always limited to your tenant, and a `tenantId` filter is ignored.

There is no tenant header. A client key can’t act as a tenant, so it names the tenant in the body or filters by it instead. The error for a missing or wrong `tenantId` has different names on different endpoints, so treat each group below as one case.

**A client key wrote something tenant-owned without naming the tenant:**

| Code | Returned by |
| --- | --- |
| `TENANT_ID_NEEDED_FOR_CLIENT_REQUEST` | File uploads, customers, wallets, GTIN and ISRC ranges, VAT checks |
| `TENANT_ID_NEEDED_FOR_CLIENT_SCOPE` | Single-object draft writes: release, track, booklet, video |
| `SAME_TENANT_ID_NEEDED_ON_ALL_REQUESTS` | The full-release draft write |
| `CLIENT_REQUEST_NEEDS_TENANT_ID_IN_BODY` | Preview links |

**A tenant key named a different tenant:**

| Code | Returned by |
| --- | --- |
| `TENANT_ID_MUST_BE_EMPTY_OR_SAME_AS_AUTH_SCOPE` | The full-release draft write |
| `TENANT_ID_MUST_BE_EMPTY_OR_AS_AUTH_SCOPE` | Single-object draft writes: release, track, booklet, video |

### Endpoints that exist for one scope only

Some operations exist at one level only, and the wrong kind of key gets `401 UNAUTHORIZED`, not `403`. A tenant key does everything a catalog needs (files, drafts, submits, takedowns, customers, wallets, splits, analytics), but not the operations below. For a tenant under RecordJet that’s by design, because RecordJet does this work for you.

| Client key only | Guide |
| --- | --- |
| List and create tenants | [Client accounts](https://docs.releaseapi.com/client-accounts.html#tenants) |
| Decide a review (accept or reject a draft); read an edit draft’s diff (`GET …/drafts/releases/{id}/changes`) | [Submit and review › Decide reviews](https://docs.releaseapi.com/review.html#client-review) |
| Manual ledger mappings; resolving a GTIN or ISRC in the ledger (`POST …/ledger/resolve-gtin`, `…/resolve-isrc`). A tenant key reads its own ledger commits with `GET …/ledger/releases` and `GET …/ledger/wallets`, filtered by `releaseId`, `gtin` or `trackId` | [Splits and the ledger](https://docs.releaseapi.com/ledger.html) |

Each guide repeats the rule where it applies, and [Client accounts](https://docs.releaseapi.com/client-accounts.html) walks through the client side as a whole.

If a key works for `GET /v1/me/token` but one endpoint returns `401`, that endpoint is almost certainly reserved for the other scope.

*Diagram: Authorization order: key check returns 401, permission check returns 403, scope check returns 401, then the request runs.* ReleaseAPI checks the permission before the scope. A `READER` key on a client-only write gets 403. The 401 for the wrong scope only appears once the role would allow the call. A disabled or expired key gets 401 with `API_TOKEN_DISABLED` or `API_TOKEN_EXPIRED`.

## Roles and permissions

A key carries one or more **roles** in `accessRights`. Each role grants a fixed set of permissions, and each endpoint requires one (the [API reference](https://docs.releaseapi.com/openapi/index.html) shows “Requires `CATALOG_WRITE`”). A missing permission gets `403 PERMISSION_DENIED`.

| Role | Grants | Give it to |
| --- | --- | --- |
| `ADMIN` | Every permission, including minting keys, changing members and creating tenants. | Automation that administers your tenant (keys, members). Keep the number of these keys small. |
| `MEMBER` | Everything except `API_TOKEN_WRITE`, `MEMBERSHIP_WRITE`, `TENANT_WRITE` and `CLIENT_WRITE`. | Your product backend. It can write drafts, upload files, deliver and run accounting, but it can’t create keys or change access. |
| `READER` | Every `*_READ` permission, plus four grants the dashboard needs for a signed-in session (`SESSION`, `CONDUCTOR_USE`, `PUSH_WRITE`, `AVATAR_WRITE`). None of them changes catalog, money or account data. | Dashboards and read-only reporting. A `READER` key can list, read and download exports but can’t order or delete one, which needs `REPORTING_WRITE`. Give a pipeline that orders exports a `MEMBER` key. |

**All permissions and the roles that hold them**

`ADMIN` holds every permission. `MEMBER` holds every permission except the four marked admin-only. `READER` holds the `*_READ` half of each pair and the dashboard session grants. `GET /v1/me/token` lists exactly what your key has.

| Permission | Allows | READER |
| --- | --- | --- |
| `DRAFT_READ` · `DRAFT_WRITE` | Read; create, change and submit draft releases, tracks, booklets and videos | Read |
| `CATALOG_READ` · `CATALOG_WRITE` | Read; change catalog releases and videos (takedowns, syncs), import a catalog | Read |
| `FILE_READ` · `FILE_WRITE` | Read; upload or delete files | Read |
| `DELIVERY_READ` · `DELIVERY_WRITE` | Read; change delivery requests | Read |
| `DELIVERY_PROFILE_READ` · `DELIVERY_PROFILE_WRITE` | Read; create or change delivery profiles | Read |
| `ARTIST_READ` · `ARTIST_WRITE` | Look up artists and store ids; link or create artists | Read |
| `IDENTIFIER_READ` · `IDENTIFIER_WRITE` | Read GTIN and ISRC ranges; create, allocate or delete them | Read |
| `LEDGER_READ` · `LEDGER_WRITE` | Read ledger commits (release, wallet and video); change ledger commits. With a client key, `LEDGER_READ` also covers resolving a GTIN or ISRC; a tenant key reads the commits instead (`GET …/ledger/releases?releaseId=`, `GET …/ledger/wallets?releaseId=`) | Read |
| `ACCOUNTING_READ` · `ACCOUNTING_WRITE` | Read customers, wallets and charges; change customers and wallets | Read |
| `MARKETING_READ` · `MARKETING_WRITE` | Read; create or delete preview links | Read |
| `REPORTING_READ` · `REPORTING_WRITE` | Read analytics, reports and exports; order exports, import reporting data, change reporting configs | Read |
| `FINANCIAL_READ` · `FINANCIAL_WRITE` | Read VAT checks; create them | Read |
| `CLIENT_READ` · `CLIENT_WRITE` | Read the client; change its profile (write is admin-only) | Read |
| `TENANT_READ` · `TENANT_WRITE` | Read tenants; create a tenant or change its profile (write is admin-only) | Read |
| `MEMBERSHIP_READ` · `MEMBERSHIP_WRITE` | Read memberships; add, change or remove them (write is admin-only) | Read |
| `API_TOKEN_READ` · `API_TOKEN_WRITE` | Read keys; create, change or delete them (write is admin-only) | Read |
| `USER_READ` · `USER_WRITE` | Read dashboard users; change a user’s display name or avatar | Read |
| `JOURNAL_READ` | Read the [journal](https://docs.releaseapi.com/events.html) | Yes |
| `ENUM_READ` | Read [reference data](https://docs.releaseapi.com/reference-data.html) | Yes |
| `AVATAR_READ` | Read avatars | Yes |
| `SESSION`, `CONDUCTOR_USE`, `PUSH_WRITE`, `AVATAR_WRITE` | Dashboard session grants: live updates, push registration and avatar uploads. Integrations don’t need them. | Yes |

A few more permissions exist for dashboard-only features. You may see them in `GET /v1/me/token`, and you can ignore them.

A key with several roles gets all of their permissions. A key created without roles is an `ADMIN` key, so always pass `roles` explicitly.

## Create and manage keys

Create keys in the dashboard under your client or tenant settings, or through the API with a key that holds `API_TOKEN_WRITE` (an `ADMIN` key). A new key always has the same scope as the key that creates it. A tenant key mints tenant keys, and a client key mints client keys.

`POST /v1/tokens`

**cURL**

```bash
curl https://api-sandbox.releaseapi.com/v1/tokens \
  -H "X-API-KEY: $RELEASEAPI_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "description": "reporting dashboard",
    "roles": ["READER"],
    "expiresAt": "2027-10-01"
  }'
```

**Node.js**

```javascript
const res = await fetch(`${BASE}/tokens`, {
  method: "POST",
  headers: { "X-API-KEY": process.env.RELEASEAPI_ADMIN_KEY, "Content-Type": "application/json" },
  body: JSON.stringify({
    description: "reporting dashboard",
    roles: ["READER"],
    expiresAt: "2027-10-01",
  }),
});
const { tokenId, tokenSecret } = await res.json();
// Store tokenSecret in your secret manager now. It is never shown again.
```

**Python**

```python
r = requests.post(f"{BASE}/tokens",
                  headers={"X-API-KEY": os.environ["RELEASEAPI_ADMIN_KEY"]},
                  json={"description": "reporting dashboard",
                        "roles": ["READER"],
                        "expiresAt": "2027-10-01"})
token = r.json()  # {"tokenId": ..., "tokenSecret": ...}
```

**Response**

```json
{
  "tokenId": "4a0c7d2e-91b3-4f6a-8e15-0d2c3b4a5e61",
  "tokenSecret": "9d3f6a7e-2b41-4c1a-8f0e-6a5b4c3d2e1f"
}
```

- `description` (string) — What the key is for. Shown in the dashboard. Under 1,000 characters.
- `roles` (array of enum) — Defaults to `["ADMIN"]` when omitted. An unknown role name gets `400 UNKNOWN_ROLE`. An empty array is accepted and creates a key with no permissions: every call except `GET /v1/me/token` answers `403`. Values: `ADMIN`, `MEMBER`, `READER`.
- `expiresAt` (date) — A calendar date, `YYYY-MM-DD`. The key stops working at 00:00 UTC *on* that date, not at the end of it.

> **The secret is shown once:** ReleaseAPI stores only a hash of `tokenSecret`. Copy it into your secret manager straight from the response. `tokenId` isn’t a credential. It identifies the key for management calls and when you ask your RecordJet contact about a key.

### Key management endpoints

**Keys**

- `GET /v1/me/token` — Inspect the calling key
- `POST /v1/tokens` — Create a key in your scope
- `GET /v1/tokens` — List keys (client keys also see tenant keys)
- `GET /v1/tokens/{tokenId}` — Read one key
- `PUT /v1/tokens/{tokenId}/access-rights` — Replace roles: `{"roles": [...]}`
- `PUT /v1/tokens/{tokenId}/disabled` — Disable or re-enable: `{"disabled": true}`
- `DELETE /v1/tokens/{tokenId}` — Delete permanently

Role changes, disabling and deleting take effect at once. `lastUsedAt` updates at most every 10 minutes, which is enough to spot unused keys. A client key can read, re-role, disable and delete every key in the client, but creates only client keys. Tenant keys are created with a tenant key or in the dashboard. The [API reference](https://docs.releaseapi.com/openapi/index.html#post-/tokens) has the full request and response schemas.

## Rotate a key without downtime

Keys don’t expire unless you set `expiresAt`, so rotate them on your own schedule. To rotate without a single failed request, run the old and the new key side by side for a while:

1. **Create the replacement**

   Mint a new key with the same roles and a description that says what it replaces.

2. **Deploy it**

   Roll the new secret out to every service that uses the old one.

3. **Disable the old key**

   `PUT /v1/tokens/{tokenId}/disabled` with `{"disabled": true}`. If something breaks, re-enable it in one call.

4. **Delete it**

   Once `lastUsedAt` has stopped moving for a few days, delete the old key.

## Keep keys safe

- **Server to server only.** The API answers CORS preflights from any origin, so a browser *could* call it, but anyone who opens the page could then read the key. Never ship a key in a browser bundle, a mobile app or a desktop client. To let someone listen to an unreleased release, use a [preview link](https://docs.releaseapi.com/catalog.html#share-before-release).
- **One key per service**, each with the smallest role that works. That way you can revoke one key without affecting the others.
- **Prefer tenant keys.** A leaked tenant key exposes one catalog. A leaked client key exposes all of them.
- **Set an expiry** on keys for contractors, experiments and one-off migrations.
- **Don’t log journal payloads verbatim.** Events about keys include internal fields. See [event payloads](https://docs.releaseapi.com/events.html#payloads).

### If your artists log in to your product

A tenant key sees the whole tenant. ReleaseAPI keeps tenants apart, but it doesn’t know which of your users may see which customer, release or wallet inside the tenant, because customers have no login of their own. In a portal where several artists or labels share one tenant, **your backend is the only guard**.

- Map each of your users to the customers (and wallets) they may see, in your own database.
- Before you return anything to a user, check that it belongs to one of their customers: a release or video through `accounting.ownerCustomerId`, a wallet through its `customerId`, a track through its release.
- Be careful with endpoints that take a bare id in the path, such as analytics for one track or one wallet, and preview links. A tenant key returns any object of the tenant, so check ownership before you pass a user-supplied id through.
- Prefer ids your backend looked up over ids the browser sends.

## Requests and responses

- **Base URL** `https://api.releaseapi.com/v1`, or `https://api-sandbox.releaseapi.com/v1` for sandbox. Prose and code titles show the full path (`GET /v1/me/token`). Code sets `BASE` to the base URL, which already ends in `/v1`, and passes the rest (`/me/token`). The helpers below drop a leading `/v1`, so either form works.
- **JSON over HTTPS**, UTF-8. Bodies need `Content-Type: application/json` (`text/json` also works). Without it you get `415`.
- **Body size** is capped at about 2 MB (`413` above that). The limit applies to every JSON endpoint. Files are never sent inside JSON, because they have their own [upload flow](https://docs.releaseapi.com/files.html). In practice, only a long album with full lyrics on every track comes close to the limit. In that case, write the release and each track with separate `PUT`s ([Build a release](https://docs.releaseapi.com/drafts.html#partial-writes)).
- Field names are **camelCase**, and enum values are **UPPER_SNAKE_CASE**, such as `APPLE_MUSIC` and `FULL_SYNC`.
- **Optional fields usually come back as `null`**, but a few responses leave them out. Treat missing and `null` alike. In requests, `null` for an optional field means the same as leaving it out. The OpenAPI document marks every optional field `nullable`.
- **New fields, endpoints and enum values appear without a version change** within `/v1`. Ignore what you don’t know and give enums a fallback branch. Every change your integration can notice, including deprecations and removals, is announced in the [changelog](https://docs.releaseapi.com/changelog.html).
- Responses can be gzip-compressed. Send `Accept-Encoding: gzip` for large lists and analytics.

### Check that an object exists

`HEAD` is the cheapest way to check that a file still exists or that a draft id is already in use. It returns `200` with an empty body if the object exists and your key can see it, and `404` otherwise. It needs the same read permission as the `GET`. Most single-object endpoints answer it: drafts and catalog objects, customers and wallets, every file kind, delivery requests, trends configs and daily imports, statement imports and exports.

`HEAD /v1/distribution/drafts/full-releases/{draftReleaseId}`

```bash
curl -I https://api-sandbox.releaseapi.com/v1/distribution/drafts/full-releases/$DRAFT_ID \
  -H "X-API-KEY: $RELEASEAPI_KEY"
```

## Errors

Errors are JSON objects with `"status": "error"` and a machine-readable code. The code is an UPPER_SNAKE string such as `RELEASE_LOCKED_IN_REVIEW`. Branch on the code, never on English text.

**400 Bad Request**

```json
{
  "status": "error",
  "message": "TENANT_ID_MUST_BE_EMPTY_OR_SAME_AS_AUTH_SCOPE"
}
```

Most errors put the code in `message`, so read `message`, then `error`, then `exception`:

| Case | Where the code is |
| --- | --- |
| Body isn’t valid JSON or doesn’t match the schema | `error`: `PARSING_FAILED` or `DECODING_FAILED`; `details` says where decoding stopped |
| A value rejected while the body is read (unknown role, fee outside 0–1) | Can be `exception` |
| Paging parameters out of range (`INVALID_LIMIT`, `INVALID_OFFSET`, `INVALID_IDS_LIST_LENGTH`) | `exception` |
| `415` and a malformed path id (`400`) | No code: `error` is an English sentence, such as `Cannot parse parameter releaseId as UUID: …`. Branch on the status. |
| An unknown path (`404`) | No code: `{"status": "error", "error": ""}`. |
| `413` | Not JSON. The gateway returns a small HTML page. Branch on the status. |
| An unknown `sortBy` field (`400`) | `message` is `key not found:` followed by the field name. |
| An unknown code in the path | None: a bare `{"status": "error"}` with `400` |

**400 — body doesn't match the schema**

```json
{
  "status": "error",
  "error": "DECODING_FAILED",
  "details": "DownField(release), DownField(details), DownField(title)"
}
```

**Read the error code**

**Node.js**

```javascript
// path may start with or without /v1: "/me/token" and "/v1/me/token" both work
async function call(path, init = {}) {
  const res = await fetch(BASE + path.replace(/^\/v1(?=\/)/, ""), {
    ...init,
    headers: {
      "X-API-KEY": process.env.RELEASEAPI_KEY,
      "Content-Type": "application/json",
      ...init.headers,
    },
  });
  if (res.ok) return res.json();
  const body = await res.json().catch(() => ({}));
  const code = body.message ?? body.error ?? body.exception ?? `HTTP_${res.status}`;
  throw Object.assign(new Error(code), { status: res.status, code, body });
}
```

**Python**

```python
class ReleaseAPIError(Exception):
    def __init__(self, status, code, body):
        super().__init__(code)
        self.status, self.code, self.body = status, code, body

def call(method, path, **kw):
    if path.startswith("/v1/"):  # "/me/token" and "/v1/me/token" both work
        path = path[3:]
    r = requests.request(method, f"{BASE}{path}",
                         headers={"X-API-KEY": os.environ["RELEASEAPI_KEY"]}, **kw)
    if r.ok:
        return r.json()
    try:
        body = r.json()
    except ValueError:
        body = {}
    code = (body.get("message") or body.get("error") or body.get("exception")
            or f"HTTP_{r.status_code}")
    raise ReleaseAPIError(r.status_code, code, body)
```

**Go**

```go
// apiError covers every error shape: the code is in Message, Error or Exception.
type apiError struct {
	Status    string          `json:"status"`
	Message   string          `json:"message,omitempty"`
	Error     string          `json:"error,omitempty"`
	Exception string          `json:"exception,omitempty"`
	Details   json.RawMessage `json:"details,omitempty"`
}

func errorCode(httpStatus int, body []byte) string {
	var e apiError
	_ = json.Unmarshal(body, &e) // a non-JSON body leaves every field empty
	for _, c := range []string{e.Message, e.Error, e.Exception} {
		if c != "" {
			return c
		}
	}
	return fmt.Sprintf("HTTP_%d", httpStatus)
}
```

Treat every field as optional, and keep `details` as raw JSON, because it is a string for decoding errors and can be an object elsewhere. A `404` body is `{"status": "not found"}` with no code, so the helpers turn it into `HTTP_404`.

### Status codes

| Status | When | What to do |
| --- | --- | --- |
| `200` | Success. The body is the object, or `{"status": "success"}` for actions and deletes that return nothing else. | — |
| `400` | The request breaks a rule: validation, a business rule, bad paging parameters, a wrong `tenantId`. | Fix the request. Retrying the same body won’t help. |
| `401` | Missing, unknown, disabled or expired key, *or* an endpoint that doesn’t exist for your key’s scope. | Check the key with `GET /v1/me/token`, then the [scope](https://docs.releaseapi.com/api-basics.html#scope-only-endpoints). |
| `403` | `PERMISSION_DENIED`: the key is valid, but its role lacks the permission. | Use a key with a stronger [role](https://docs.releaseapi.com/api-basics.html#roles). |
| `404` | `{"status": "not found"}`. The object doesn’t exist *or* isn’t visible to your key. | Check the id and the tenant. A tenant key never sees another tenant’s objects. |
| `409` | Conflict with the current state, for example `RELEASE_LOCKED_IN_REVIEW`, `COVER_FILE_STILL_IN_USE` or `IMPORT_FOR_MONTH_ALREADY_EXISTS`. | Read the state, wait or change it, then try again. |
| `413` | Body over about 2 MB. | Split the request. Upload files through the file endpoints. |
| `415` | Missing or wrong `Content-Type`. | Send `application/json`. |
| `429` | Too many requests, or a store’s own API is throttling ReleaseAPI (`SPOTIFY_RATE_LIMITED`). | Back off and retry. See [rate limits](https://docs.releaseapi.com/api-basics.html#rate-limits). |
| `500` | Unexpected server error. | Retry with backoff. If it persists, send the request and the time to your RecordJet contact (or to ReleaseAPI, if you run a client account). |
| `502` / `503` | A dependency is unavailable, for example `SPOTIFY_UNAVAILABLE` when Spotify’s API is down. | Retry with backoff. |

> **401 versus 403:** `403` means “this key may not do that”. `401` means “this key isn’t valid here”, which includes a perfectly good tenant key calling a client-only endpoint, and the other way round.
>
> The permission is checked before the scope. A `READER` tenant key calling a client-only *write* endpoint therefore gets `403 PERMISSION_DENIED`, not `401`. You only see the scope’s `401` once the key’s role would allow the call.

## Pagination

List endpoints use offset pagination and share the same parameters:

- `limit` (integer, 1–100) — Page size. Defaults to `100`. Outside the range gets `400 INVALID_LIMIT`.
- `offset` (integer, ≥ 0) — How many items to skip. Negative values get `400 INVALID_OFFSET`.
- `sortBy` (string) — A camelCase field of the returned object; the default depends on the endpoint ([default order](https://docs.releaseapi.com/api-basics.html#default-order)). A field the list can’t sort by returns `400` with `"message": "key not found: …"`.
- `sortOrder` (enum) — Most lists default to `desc`, newest first; a few default to `asc` (see below). Casing doesn’t matter. Once you send `sortOrder`, any value other than `desc` means `asc`. Values: `asc`, `desc`.
- `ids` (comma-separated UUIDs) — Fetch specific objects in one call. Up to 100 ids, or you get `400 INVALID_IDS_LIST_LENGTH`.
- `q` (string) — Free-text search. What it matches is described on each endpoint.
- `tenantId` (uuid) — Client keys only: limit the list to one tenant.

**Paged list response**

```json
{
  "items": [
    {
      "id": "0b1c2d3e-4f50-4a61-8b72-93c4d5e6f708",
      "externalId": "artist-4711",
      "…": "…"
    }
  ],
  "hasMore": true,
  "limit": 100,
  "offset": 0
}
```

Keep requesting with `offset += limit` while `hasMore` is `true`. `hasMore` is exact, so don’t infer the end from a short page.

**Walk every page**

**Node.js**

```javascript
async function* listAll(path, params = {}) {
  for (let offset = 0; ; offset += 100) {
    const qs = new URLSearchParams({
      ...params, limit: 100, offset, sortBy: "createdAt", sortOrder: "asc",
    });
    const page = await call(`${path}?${qs}`);
    yield* page.items;
    if (!page.hasMore) return;
  }
}

for await (const customer of listAll("/distribution/accounting/customers")) {
  console.log(customer.externalId);
}
```

**Python**

```python
def list_all(path, **params):
    offset = 0
    while True:
        page = call("GET", path, params={**params, "limit": 100, "offset": offset,
                                         "sortBy": "createdAt", "sortOrder": "asc"})
        yield from page["items"]
        if not page["hasMore"]:
            return
        offset += 100

for customer in list_all("/distribution/accounting/customers"):
    print(customer["externalId"])
```

### Default order

When you send neither `sortBy` nor `sortOrder`, lists come back in this order:

| Lists | Default order |
| --- | --- |
| Customers, wallets, every file kind, preview links, exports, ledger commits (releases, wallets, videos), statement reports, trend reports, trends configs | `createdAt`, newest first |
| Catalog releases, full releases and videos | Release date (`releaseDateTime`), newest first; then `createdAt`, newest first |
| Draft releases and draft videos | Release date (`distributionReleaseDateTime`), newest first; then `createdAt`, newest first |
| Statement imports, trends daily imports | `reportedAt`, newest first; then `createdAt`, newest first |
| Delivery requests | `finishedAt`, newest first; then `createdAt`, newest first |
| Catalog tracks | Volume number, then track number, ascending |
| API keys, catalog booklets, delivery profiles, VAT checks | `createdAt`, oldest first |
| Tenants, user memberships | Always `createdAt`, oldest first. These two ignore `sortBy` and `sortOrder`. |

If you send `sortBy` without `sortOrder`, the list keeps its default direction from the table.

> **For a full read, send `sortBy=createdAt&sortOrder=asc`** (the walkers above do). In newest-first order, every object created while you page pushes the rest down, so you read some items twice. In oldest-first order, new objects are added at the end, so the pages you have already read don’t shift. A deletion can still shift the list, so treat a full read as a snapshot and follow the [journal](https://docs.releaseapi.com/events.html) afterwards.

> **Filters that can’t be parsed are ignored, not rejected:** That covers an unknown enum value (`?status=SUCESS`), a malformed id (`?tenantId=lowtide`), a date in the wrong format (`?dateFrom=05.10.2026`) and a non-numeric `limit`. Each returns the list as if you hadn’t sent that filter. With a client key, a broken `tenantId` therefore returns *every* tenant’s objects. Malformed entries inside `ids=` are dropped from the list. Validate parameters on your side, and check enum values against [reference data](https://docs.releaseapi.com/reference-data.html), before you send them.

A few endpoints return a plain array instead of a page: the journal (up to 100 events per call), reference data and charge reports. Each guide says so.

## Ids and your own references

- **Every id is a UUID** string, for example `3f0c6a1e-8d52-4b7e-9a10-5c2e7f4d8b91`.
- **Some ids are yours to choose.** A draft release is created with `PUT …/drafts/full-releases/{draftReleaseId}` and a UUID you generated. Store it on your own record before you call, so a retry can never create a duplicate. The catalog release keeps the same id.
- **`externalId`** is a free string on drafts, files, customers, wallets and more. Put your primary key there and look objects up with `?externalId=`. On some objects (draft releases, tracks, booklets, files of one kind) it must be unique within the tenant, and a clash returns a `400` such as `DIFFERENT_DRAFT_RELEASE_WITH_SAME_EXTERNAL_ID_EXISTS_ALREADY`.
- Industry identifiers have their own fields and formats. A GTIN (the release barcode) is 13 digits. An ISRC (the recording code) looks like `DEXW92600001`. See [Identifiers and artists](https://docs.releaseapi.com/identifiers.html).

## Dates and times

| Kind | Format | Example |
| --- | --- | --- |
| Timestamp | ISO 8601 in UTC. Precision varies between milliseconds and microseconds. | `2026-10-05T07:31:02.114210Z` |
| Calendar date | `YYYY-MM-DD`, no time zone | `2026-11-20` |
| Month | `YYYY-MM` in bodies; integers in paths | `2026-09`, `/charge/monthly/2026/9` |

Parse timestamps with a real ISO 8601 parser, because the number of fractional digits varies. Release dates are calendar dates, and each store decides at what local time a release appears. ReleaseAPI’s own clock is UTC: scheduled jobs run on UTC, and dated rules such as ledger effective dates use the UTC calendar date.

## Money, fees and shares

Numbers that represent money come in four forms. Which one a field uses depends on what it’s for:

| Where | Unit | Example |
| --- | --- | --- |
| Revenue and earnings: statements, analytics, exports, ledger amounts | **Integer nano-euros**: billionths of a euro | `1230000000` = €1.23 |
| Billing: charges and invoices, fields ending in `Eur` such as `totalEur` | Decimal euros with up to four decimal places, each line rounded half-up before it is added to the total | `881.4091` = €881.41 |
| Fees such as `tenantFeePercentage` | Decimal fraction from 0 to 1 | `0.2` = 20% |
| Revenue splits: `sharePerMio` | Integer parts per million; a rule’s shares add up to 1,000,000 | `520000` = 52% |

> **Never sum money as floats:** A JavaScript number holds integers exactly up to 253, about €9 million in nano-euros. Single tracks, releases and wallets stay far below that, but totals for a whole client or a large tenant can exceed it. Parse those with a lossless JSON parser (for example `json-bigint`) into `BigInt`, and divide by 109 only for display. Python’s integers have no such limit. [How money flows](https://docs.releaseapi.com/royalties.html) walks through the calculation.

**Read fees as exact decimals.** Fees arrive as JSON numbers but are calculated as exact decimals, never as binary floats, and the API doesn’t cap how many decimal places you send. Parse them losslessly so `0.15` stays `0.15`. In Python, use `json.loads(text, parse_float=Decimal)` (or `r.json(parse_float=Decimal)`), and in JavaScript a decimal library. Display fields ending in `_fee_per_mio` are rounded to whole parts per million, so don’t recompute money from them.

## Codes and enums

Countries are ISO 3166-1 alpha-2 (`DE`), languages are ISO 639-1 in upper case (`EN`), and stores, genres and contributor roles are UPPER_SNAKE codes. Fetch the current lists from [reference data](https://docs.releaseapi.com/reference-data.html) rather than hard-coding them, because stores and genres change.

## Retries and idempotency

There’s no idempotency-key header. Retry safety comes from how each kind of call is designed:

| Kind of call | Safe to retry? | Why |
| --- | --- | --- |
| `GET`, `HEAD` | Yes | Reads only. |
| `PUT` to an id you chose (drafts, tracks) | Yes | The write replaces the whole object, so the same body gives the same result however often you send it. Send the *complete* object every time, because anything you leave out is removed. |
| `PUT` on a sub-resource (`…/status`, `…/sync-request`) | Mostly | Sets a state. A repeat usually sets the same state again, but some endpoints refuse a repeat while the first request is pending. For example, a second `…/sync-request` returns `SYNC_REQUEST_ALREADY_SET`. Treat that as success. |
| `POST` that creates (customers, wallets, keys, exports) | **No** | A retry after a timeout can create a second object. Set `externalId`, then look it up with `?externalId=` before you retry. |
| `DELETE` | Yes | A second delete returns `404`. Treat that as done. |

Retry `429`, `500`, `502`, `503` and network errors with exponential backoff and jitter, for example 1, 2, 4 and 8 seconds. Don’t retry `400`, `401`, `403` or `404`. Retry a `409` only after the state that caused it has changed.

*Diagram: Retry decision: 2xx is done; 429, 5xx and network errors back off and retry; 409 retries only after the state changes; 400, 401, 403 and 404 are not retried.* Only transient failures are retried. Before retrying a `POST` that creates something, look it up by `externalId` first so a timeout doesn’t leave you with two objects.

## Rate limits

A `429 Too Many Requests` means you’re sending requests too quickly. Back off exponentially and retry. Some endpoints also return `429` when a store’s own API throttles ReleaseAPI. These practices help you avoid it:

- Poll the [journal](https://docs.releaseapi.com/events.html) instead of polling individual objects. One journal call covers your whole account.
- Fetch objects in batches with `?ids=` (up to 100) instead of one by one.
- Cache reference data, since it rarely changes.
- Spread bulk work (back-catalog writes, mass exports) over time with a small, fixed number of workers instead of firing everything at once.

## Sandbox behaviour

Sandbox runs the same code as production, but it never touches the outside world:

- **No deliveries.** Sync requests aren’t processed. An accepted release keeps `storeSnapshot.syncRequest` set and `isSynced: false`, and no delivery requests are created.
- **No store ids or links** unless you request a lookup with `request-store-id-crawl`, which searches the real stores by GTIN and so only finds releases that are actually live ([Is it live?](https://docs.releaseapi.com/delivery.html#is-it-live)).
- **No reporting data.** No trend imports or statements arrive, so analytics and reports stay empty unless your RecordJet contact imports test data. Your RecordJet contact provides sample report files. Build parsers against them and the column tables in [Monthly statements](https://docs.releaseapi.com/statements.html#report-columns) and [Raw reports](https://docs.releaseapi.com/reports.html#raw-reports), then run them in production with a `READER` key.
- **Reviews.** RecordJet reviews releases, so ask your RecordJet contact to review a test release. Client accounts accept their own ([quickstart](https://docs.releaseapi.com/quickstart.html#step-submit)).
- **No local webhooks.** `localhost`, private and loopback URLs are rejected (`BLOCKED_URL_HOST`, `BLOCKED_URL_HOST_RESOLVES_PRIVATE`). Use a tunnel, or drain the journal on a timer ([webhooks](https://docs.releaseapi.com/events.html#webhooks)).
- **Test data may be removed.** Don’t keep anything in sandbox you can’t recreate.

Validation, the catalog, the ledger, the journal and webhooks behave as in production, which is enough to test the happy path end to end. Rejections, delivery failures and retries can’t be triggered on demand, so cover your handling of them with tests against recorded events from the [event catalog](https://docs.releaseapi.com/events.html#event-catalog).

## Generate a client

There is no official client library. Generate one from the [OpenAPI document](https://docs.releaseapi.com/openapi/releaseapi-openapi.yml) (`openapi/releaseapi-openapi.yml`, OpenAPI 3.0) with any generator you like. [OpenAPI Generator](https://openapi-generator.tech) covers most languages. The document lists the production, staging and sandbox servers and one security scheme, `ApiKeyAuth`, which sends your key in the `X-API-KEY` header.

**Generate a TypeScript or Python client**

**TypeScript**

```bash
npx @openapitools/openapi-generator-cli generate \
  -i https://docs.releaseapi.com/openapi/releaseapi-openapi.yml \
  -g typescript-fetch \
  -o ./releaseapi-client
```

**Python**

```bash
npx @openapitools/openapi-generator-cli generate \
  -i https://docs.releaseapi.com/openapi/releaseapi-openapi.yml \
  -g python \
  -o ./releaseapi-client-python \
  --additional-properties=packageName=releaseapi_client
```

Point the generated client at sandbox and give it your key:

**Configure the generated client**

**Node.js**

```javascript
import { Configuration } from "./releaseapi-client";

const config = new Configuration({
  basePath: "https://api-sandbox.releaseapi.com/v1",
  apiKey: process.env.RELEASEAPI_KEY,
});
// Pass `config` to the generated API classes.
```

**Python**

```python
import os
import releaseapi_client

config = releaseapi_client.Configuration(
    host="https://api-sandbox.releaseapi.com/v1",
    api_key={"ApiKeyAuth": os.environ["RELEASEAPI_KEY"]},
)
client = releaseapi_client.ApiClient(config)
```

Money amounts in the generated models are integers in nano-euros (see [Money, fees and shares](https://docs.releaseapi.com/api-basics.html#money)).

## Next steps

- [Quickstart](https://docs.releaseapi.com/quickstart.html): Use your new key to take a single from files to stores.
- [Events and webhooks](https://docs.releaseapi.com/events.html): Follow every change in your account from one cursor.
- [Your account](https://docs.releaseapi.com/account.html): Manage your tenant and team, see what each role can do, and check your billing.
- [Reference data](https://docs.releaseapi.com/reference-data.html): Look up stores, genres, languages, roles and every other code list.
