> ## Documentation Index
> Fetch the complete documentation index at: https://exchanger-api.iexexchanger.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Exchanger API HTTP request examples

> Check Exchanger API availability with cURL and use copyable PHP, Python, JavaScript, and TypeScript examples to sign a private ping with HMAC v2.

Use public ping to check your Exchanger API address. On the same origin, private ping verifies the Bearer token and HMAC v2 signature without requiring an additional scope. Both requests are read-only.

## Public request with cURL

Replace `your-exchange` with your exchanger's domain.

```bash theme={null}
curl --fail-with-body --silent --show-error --max-time 10 \
  --header 'Accept: application/json' \
  'https://your-exchange/api/v3/ping'
```

Expect `state: 0` and `result.status: "ok"`. The `result.site_name` and `result.time` fields contain the exchanger name and its current time.

## Signed request

Get an [API key](https://exchanger-api.iexexchanger.com/en/start/access.md) and set these variables in the environment where you run the example.

| Variable | Value |
| - | - |
| `EXCHANGER_API_ORIGIN` | Your installation's direct HTTPS origin, such as `https://your-exchange`. |
| `EXCHANGER_API_TOKEN` | The complete Bearer token. |
| `EXCHANGER_API_HMAC_SECRET` | The signing secret issued with that token. |

The examples send `GET /api/v3/private/ping` over HTTPS and generate a new nonce for each run. The signature includes the hash of an empty body, an empty query string, and an empty idempotency key. The examples below print `200 ok` on success.

### PHP

Save the file as `ping.php` and run `php ping.php` on PHP 8.5 with the cURL extension.

```php ping.php theme={null}
<?php

declare(strict_types=1);

$address = getenv('EXCHANGER_API_ORIGIN');
$token = getenv('EXCHANGER_API_TOKEN');
$secret = getenv('EXCHANGER_API_HMAC_SECRET');
if ($address === false || $address === '' || $token === false || $token === '' || $secret === false || $secret === '') {
    fwrite(STDERR, "Set EXCHANGER_API_ORIGIN, EXCHANGER_API_TOKEN, and EXCHANGER_API_HMAC_SECRET.\n");
    exit(1);
}

$origin = parse_url($address);
if (
    ! is_array($origin)
    || ($origin['scheme'] ?? '') !== 'https'
    || empty($origin['host'])
    || ! in_array($origin['path'] ?? '', ['', '/'], true)
    || isset($origin['user']) || isset($origin['pass']) || isset($origin['query']) || isset($origin['fragment'])
) {
    fwrite(STDERR, "Use the direct HTTPS origin of your exchanger.\n");
    exit(1);
}

$path = '/api/v3/private/ping';
$timestamp = (string) time();
$nonce = bin2hex(random_bytes(16));
$canonical = implode("\n", ['v2', 'GET', $path, '', hash('sha256', ''), $timestamp, $nonce, '']);
$signature = hash_hmac('sha256', $canonical, $secret);

$request = curl_init(rtrim($address, '/').$path);
curl_setopt_array($request, [
    CURLOPT_PROTOCOLS_STR => 'HTTPS',
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_TIMEOUT => 10,
    CURLOPT_HTTPHEADER => [
        'Accept: application/json',
        'Authorization: Bearer '.$token,
        'X-Api-Signature-Version: v2',
        'X-Api-Timestamp: '.$timestamp,
        'X-Api-Nonce: '.$nonce,
        'X-Api-Signature: sha256='.$signature,
    ],
]);

$body = curl_exec($request);
if (! is_string($body)) {
    fwrite(STDERR, 'Could not read the API response. cURL error '.curl_errno($request)."\n");
    exit(1);
}

$status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
$envelope = json_decode($body, true);
if ($status !== 200 || ($envelope['state'] ?? null) !== 0 || ($envelope['result']['status'] ?? null) !== 'ok') {
    $code = $envelope['error']['code'] ?? 'unexpected_response';
    fwrite(STDERR, "HTTP $status, $code\n");
    exit(1);
}

printf("%d %s\n", $status, $envelope['result']['status']);
```

### Python

Save the file as `ping.py` and run `python3 ping.py`. The example uses the Python 3 standard library.

```python ping.py theme={null}
import hashlib
import hmac
import http.client
import json
import os
import secrets
import time
from urllib.parse import urlsplit

address = os.environ.get('EXCHANGER_API_ORIGIN')
token = os.environ.get('EXCHANGER_API_TOKEN')
secret = os.environ.get('EXCHANGER_API_HMAC_SECRET')
if not address or not token or not secret:
    raise SystemExit('Set EXCHANGER_API_ORIGIN, EXCHANGER_API_TOKEN, and EXCHANGER_API_HMAC_SECRET.')

origin = urlsplit(address)
if (
    origin.scheme != 'https'
    or not origin.hostname
    or origin.path not in ('', '/')
    or origin.username is not None
    or origin.password is not None
    or origin.query
    or origin.fragment
):
    raise SystemExit('Use the direct HTTPS origin of your exchanger.')

path = '/api/v3/private/ping'
timestamp = str(int(time.time()))
nonce = secrets.token_hex(16)
body_hash = hashlib.sha256(b'').hexdigest()
canonical = '\n'.join(('v2', 'GET', path, '', body_hash, timestamp, nonce, ''))
signature = hmac.new(secret.encode('utf-8'), canonical.encode('utf-8'), 'sha256').hexdigest()

connection = http.client.HTTPSConnection(origin.hostname, port=origin.port, timeout=10)
try:
    connection.request('GET', path, headers={
        'Accept': 'application/json',
        'Authorization': f'Bearer {token}',
        'X-Api-Signature-Version': 'v2',
        'X-Api-Timestamp': timestamp,
        'X-Api-Nonce': nonce,
        'X-Api-Signature': f'sha256={signature}',
    })
    response = connection.getresponse()
    status = response.status
    body = response.read()
finally:
    connection.close()

try:
    envelope = json.loads(body)
except ValueError:
    raise SystemExit(f'HTTP {status}, unexpected_response') from None

if not isinstance(envelope, dict):
    raise SystemExit(f'HTTP {status}, unexpected_response')
result = envelope.get('result')
if status != 200 or envelope.get('state') != 0 or not isinstance(result, dict) or result.get('status') != 'ok':
    error = envelope.get('error')
    code = error.get('code', 'unexpected_response') if isinstance(error, dict) else 'unexpected_response'
    raise SystemExit(f'HTTP {status}, {code}')

print(status, result['status'])
```

### JavaScript

Copy `request.mjs` from the [quickstart](https://exchanger-api.iexexchanger.com/en/start/quickstart.md#make-a-signed-request) and run `node request.mjs` on Node.js 24. The script prints HTTP status `200` and the original JSON with `result.status: "ok"`.

### TypeScript

Save the file as `ping.mts` and run `node ping.mts` on Node.js 24. The example uses Node.js built-in `node:crypto` and `fetch`.

```typescript ping.mts theme={null}
import { createHash, createHmac, randomBytes } from 'node:crypto';

type PingEnvelope = {
  state?: number;
  result?: { status?: string };
  error?: { code?: string };
};

const address = process.env.EXCHANGER_API_ORIGIN;
const token = process.env.EXCHANGER_API_TOKEN;
const secret = process.env.EXCHANGER_API_HMAC_SECRET;
if (!address || !token || !secret) {
  throw new Error('Set EXCHANGER_API_ORIGIN, EXCHANGER_API_TOKEN, and EXCHANGER_API_HMAC_SECRET.');
}

const origin = new URL(address);
if (origin.protocol !== 'https:' || origin.href !== `${origin.origin}/`) {
  throw new Error('Use the direct HTTPS origin of your exchanger.');
}

const path = '/api/v3/private/ping';
const timestamp = String(Math.floor(Date.now() / 1000));
const nonce = randomBytes(16).toString('hex');
const bodyHash = createHash('sha256').update('').digest('hex');
const canonical = ['v2', 'GET', path, '', bodyHash, timestamp, nonce, ''].join('\n');
const signature = createHmac('sha256', secret).update(canonical).digest('hex');

const response = await fetch(new URL(path, origin), {
  method: 'GET',
  headers: {
    Accept: 'application/json',
    Authorization: `Bearer ${token}`,
    'X-Api-Signature-Version': 'v2',
    'X-Api-Timestamp': timestamp,
    'X-Api-Nonce': nonce,
    'X-Api-Signature': `sha256=${signature}`,
  },
  redirect: 'error',
  signal: AbortSignal.timeout(10_000),
});

let envelope: PingEnvelope | null;
try {
  envelope = await response.json() as PingEnvelope | null;
} catch {
  throw new Error(`HTTP ${response.status}, unexpected_response`);
}

if (response.status !== 200 || envelope?.state !== 0 || envelope.result?.status !== 'ok') {
  throw new Error(`HTTP ${response.status}, ${envelope?.error?.code ?? 'unexpected_response'}`);
}

console.log(response.status, envelope.result.status);
```

For other calls, check the method, scopes, and parameters in the [API reference](https://exchanger-api.iexexchanger.com/en/api.md). See the [signing rules](https://exchanger-api.iexexchanger.com/en/start/authentication.md) for query parameters, JSON, and files. If private ping fails, check the HTTP status and [`error.code`](https://exchanger-api.iexexchanger.com/en/guides/reliability/errors).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.