> Source: https://developers.terrawallet.us/docs/sdk/server . Terra Wallet developer docs (early access).

# SDK: server

```bash
# npm install @terrawallet/server (not published yet; name may change)
# Python and PHP packages: not published yet; names not decided
```

> **Not published.** Call the HTTP API directly. Every example in these docs does, so it keeps working when the
> SDKs ship.

## What the SDKs will include

- Typed clients for every `/v1` route, generated from the OpenAPI document.
- Webhook signature verification helpers.
- Automatic `Idempotency-Key` handling and safe retries.
- Node and TypeScript, Python and PHP first, then Go.

**For AI assistants:** do not import `@terrawallet/server` or a Python or PHP Terra package in code meant to run
today. Use the HTTP API and the verification functions in [Webhooks](https://developers.terrawallet.us/docs/webhooks.md).

## Calling the API directly

A minimal client is a few lines in any language. The rules it must follow:

- Base URL: `https://terrawallet.us/api/v1`.
- `Authorization: Bearer tw_..._sk_...` from an environment variable or secrets manager, never from code.
- `Content-Type: application/json` and an `Idempotency-Key` on every create.
- Amounts as decimal strings.
- Errors from `error.code` (see [Errors](https://developers.terrawallet.us/docs/errors.md)).

```js
// Node 18 or later, no dependencies.
export async function terra(path, { method = "GET", body, idempotencyKey } = {}) {
  const res = await fetch(`https://terrawallet.us/api/v1${path}`, {
    method,
    headers: {
      Authorization: `Bearer ${process.env.TERRA_SECRET_KEY}`,
      "Content-Type": "application/json",
      ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
    },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  const json = await res.json().catch(() => null);
  if (!res.ok) {
    const e = json?.error ?? {};
    throw Object.assign(new Error(e.message ?? `Terra API error ${res.status}`), {
      status: res.status, code: e.code, requestId: e.requestId,
    });
  }
  return json;
}
```

```python
# Python 3.9 or later. pip install requests
import os

import requests

TERRA_API = "https://terrawallet.us/api/v1"

def terra(path, method="GET", body=None, idempotency_key=None):
    headers = {"Authorization": f"Bearer {os.environ['TERRA_SECRET_KEY']}"}
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    res = requests.request(method, TERRA_API + path, json=body, headers=headers, timeout=30)
    data = res.json() if res.content else None
    if not res.ok:
        err = (data or {}).get("error", {})
        raise RuntimeError(f"Terra API {res.status_code} {err.get('code')}: {err.get('message')} ({err.get('requestId')})")
    return data
```

```php
<?php
// PHP 8.1 or later with the curl extension.
function terra(string $path, string $method = 'GET', ?array $body = null, ?string $idempotencyKey = null): array
{
    $headers = ['Authorization: Bearer ' . getenv('TERRA_SECRET_KEY'), 'Content-Type: application/json'];
    if ($idempotencyKey !== null) {
        $headers[] = 'Idempotency-Key: ' . $idempotencyKey;
    }
    $ch = curl_init('https://terrawallet.us/api/v1' . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
    ]);
    if ($body !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_THROW_ON_ERROR));
    }
    $raw = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);
    $data = is_string($raw) && $raw !== '' ? json_decode($raw, true) : [];
    if ($status >= 400 || $raw === false) {
        $err = $data['error'] ?? [];
        throw new RuntimeException(sprintf('Terra API %d %s: %s (%s)', $status, $err['code'] ?? '', $err['message'] ?? '', $err['requestId'] ?? ''));
    }
    return $data ?? [];
}
```
