---
title: "Authentication"
description: "Every request to the Stablegate API must be authenticated using an API key."
canonical_url: "https://docs.stablegate.com/docs/guide/getting-started/authentication"
---
# Authentication

> Every request to the Stablegate API must be authenticated using an API key.

Every request to the Stablegate API must be authenticated using an API key.

## API Key Authentication

Include your API key in the `X-Api-Key` header with every request:

<table>
<thead>
  <tr>
    <th>
      Header
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        X-Api-Key
      </code>
    </td>
    
    <td>
      Your API key, generated in the <dev-portal-link label="Developers">
        
      </dev-portal-link>
      
       section
    </td>
  </tr>
</tbody>
</table>

**Example request:**

::code-switcher{method="GET" path="/v1/exchange-routes/"}
```bash
curl https://api.stablegate.com/v1/exchange-routes/ \
  --header 'X-Api-Key: YOUR_API_KEY'
```
::

## Request Paths

Every endpoint path ends with a slash, for example `/v1/customers/`, not `/v1/customers`. Call the exact path from the API reference: a path without the trailing slash is answered with a `307` redirect to the same path with the slash instead of the response, which costs an extra round trip, and a client that does not follow redirects gets the `307` itself.

## Creating an API Key

1. Sign in to the Stablegate app and open :dev-portal-link{label="Developers"}.
2. Open the **API keys** tab.
3. Click **Create key** and provide a descriptive name.
4. Copy and store the key and the secret; the secret is shown once, at creation. Only the key goes
into `X-Api-Key`; the secret is for [request signing](#request-signing), which is optional today.

You can create multiple API keys to separate environments or services (e.g., one for staging, one for production).

## Request Signing

A request can carry a signature that proves it was built by someone who knows the API secret and that it
was sent recently. Signing is optional today: a request with only `X-Api-Key` is still accepted. Add the
two headers when you sign:

<table>
<thead>
  <tr>
    <th>
      Header
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        X-Api-Ts
      </code>
    </td>
    
    <td>
      Current time in seconds since the Unix epoch, UTC
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        X-Api-Sig
      </code>
    </td>
    
    <td>
      HMAC-SHA512 of the string below, hex, lowercase
    </td>
  </tr>
</tbody>
</table>

`X-Api-Sig` is `HMAC-SHA512(secret, ts + METHOD + path + body)`: the timestamp as a string, the method in
upper case, the path with its query string exactly as sent, then the request body bytes, and nothing
between them. A GET with no body signs only the three tokens — for example, at `1714352232` the string is
`1714352232GET/v1/exchange-routes/`.

**Python:**

```python
import hashlib
import hmac
import time

def signed_headers(key: str, secret: str, method: str, path: str, body: bytes = b"") -> dict[str, str]:
    ts = str(int(time.time()))
    data = f"{ts}{method.upper()}{path}".encode() + body
    signature = hmac.new(secret.encode(), data, hashlib.sha512).hexdigest()
    return {"X-Api-Key": key, "X-Api-Ts": ts, "X-Api-Sig": signature}
```

**Node.js:**

```javascript
import { createHmac } from 'node:crypto'

function signedHeaders(key, secret, method, path, body = '') {
  const ts = String(Math.floor(Date.now() / 1000))
  const signature = createHmac('sha512', secret).update(ts + method.toUpperCase() + path + body).digest('hex')
  return { 'X-Api-Key': key, 'X-Api-Ts': ts, 'X-Api-Sig': signature }
}
```

:note[Sign the bytes you actually send. Serialize the JSON body once and sign that exact string — a signature
over a re-serialized body with different spacing or key order will not match. The same holds for multipart
requests: sign the body as it goes on the wire.]The API accepts a timestamp within one minute of its own clock, so keep the server time synchronised. A
signature protects against replaying a captured request and against a modified body or query.

Do not send the secret itself: a request that carries an `X-Api-Secret` header answers `400`.

::warning
Signing is not enforced yet. Requests without `X-Api-Ts` and `X-Api-Sig` are accepted, and a signature the
API cannot verify is logged without failing the request. When enforcement starts, an unsigned or stale
request will answer `401` with `devapi_unauthorized_error`; the start date will be announced in the
[changelog](https://docs.stablegate.com/docs/changelog). Test your signature against this page before then.
::

## Security Best Practices

- **Keep your API key secret.** Never expose it in client-side code, browser requests, or version control.
- **Use environment variables** to store API keys in your application.
- **Rotate keys periodically.** Create a new key, switch your integration over to it, then delete the old one. Deletion takes effect immediately, so delete only after the new key is in use.
- **Use separate keys** for different environments (development, staging, production).

## Code Examples

### JavaScript (Node.js)

```javascript
const API_KEY = process.env.STABLEGATE_API_KEY;
const BASE_URL = "https://api.stablegate.com";

async function request(method, path, body = null) {
  const options = {
    method,
    headers: {
      "X-Api-Key": API_KEY,
      "Content-Type": "application/json",
    },
  };

  if (body) {
    options.body = JSON.stringify(body);
  }

  const response = await fetch(`${BASE_URL}${path}`, options);

  if (!response.ok) {
    throw new Error(`API error: ${response.status} ${response.statusText}`);
  }

  if (response.status === 204) return null;
  return response.json();
}

// Usage
const routes = await request("GET", "/v1/exchange-routes/");
```

### Python

```python
import os
import requests

API_KEY = os.environ["STABLEGATE_API_KEY"]
BASE_URL = "https://api.stablegate.com"

def request(method, path, json=None):
    response = requests.request(
        method,
        f"{BASE_URL}{path}",
        headers={
            "X-Api-Key": API_KEY,
            "Content-Type": "application/json",
        },
        json=json,
    )
    response.raise_for_status()
    if response.status_code == 204:
        return None
    return response.json()

# Usage
routes = request("GET", "/v1/exchange-routes/")
```

### cURL

```bash
# GET request
curl -X GET https://api.stablegate.com/v1/exchange-routes/ \
  -H "X-Api-Key: YOUR_API_KEY"

# POST request with JSON body
curl -X POST https://api.stablegate.com/v1/exchange-routes/check/ \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "source": { "rail": "sepa", "asset_code": "EUR" },
    "destination": { "rail": "ethereum", "asset_code": "USDC" }
  }'
```

## Error Responses

If authentication fails, the API returns a `401 Unauthorized` or `403 Forbidden` response:

```json
{
  "trace_id": "3f2504e0-4f89-11d3-9a0c-0305e82c3301",
  "error_code": "devapi_unauthorized_error",
  "message": "Unauthorized"
}
```

The body of every error, the codes and what to do about them are on [Errors](https://docs.stablegate.com/docs/guide/getting-started/errors).

**Common causes:**

- Missing `X-Api-Key` header
- Invalid or revoked API key
- API key does not have access to the requested resource
- The Partner API is not enabled for your account — the API answers `403`

A `503` on an authenticated request means Stablegate could not verify the key because an internal service was unavailable. The key itself is fine: retry the request.


## Sitemap

See the full [sitemap](https://docs.stablegate.com/sitemap.md) for all pages.
