# The REST API from Node.js

Every `/v1` operation is a method on a resource of the client, named as in the [API reference](https://developer.watchtower15.com/api/reference/): `wt15.servers.list()`, `wt15.customMetrics.series(uuid, { period: '1h' })`. You need an API key: see [authentication and keys](https://developer.watchtower15.com/api/authentication/). A method takes its path parameters positionally, in path order and percent-encoded (an empty one is refused), then one `params` object, then the call’s options:

```ts
const server = await wt15.servers.view(serverUuid);
await wt15.domains.runScan(domainUuid, 'dns', {}, { idempotencyKey: 'scan-dns-42' });
```

`params` is typed by a generated interface (`ServersListParams`); a query parameter goes in the query, the body’s properties in the JSON body. A list goes as `name[]=v` once per value, a boolean as `1` or `0`, a `Date` as epoch milliseconds; `null` and `undefined` are left out; any other value is refused naming the parameter.

## Models

Models are plain objects with the wire’s names (`health_status`), typed by generated interfaces. Unknown fields stay on the object, so a model read, changed and sent back keeps every field. Enums are open: `'critical' | 'warning' | … | (string & {})`, with a constant object (`Health.Critical`), so a new server value never breaks you. An instant is epoch milliseconds (`EpochMillis`); `toDate(ms)` gives a `Date`.

## Lists

A list returns a `PagePromise`. `await` it for the first `Page` (`data`, `total`, `meta`, its paging fields, `hasNextPage()`, `getNextPage()`), or `for await` it for every item, a page fetched only when the last is used up. Most lists page by number: a page carries `currentPage`, `perPage` and `lastPage`, and the next one is asked for with `page`, your other params kept (`per_page` sets the page size; `limit` is the same). Log search and a service’s scans and runs page by time: a page carries `nextCursor`, sent back as `cursor`. `hasNextPage()`, `getNextPage()` and `for await` follow whichever form the answer has:

```ts
for await (const server of wt15.servers.list({ per_page: 100, health: ['critical'] })) { … }
const page = await wt15.incidents.list({ per_page: 25 });
if (page.hasNextPage()) await page.getNextPage();
```

Paging is paced: when an answer says no request is left, the next page waits for the limit’s reset if that is within `maxRetryWait`, and otherwise throws a `RateLimitError` without sending.

## Options of a call

`RequestOptions`: `timeout` (ms), `maxRetries`, `maxRetryWait` (ms, 60,000 by default: a longer wait is not taken and the answer is thrown), `signal` (an `AbortSignal`; an abort is never retried), and on a write `idempotencyKey` (1 to 255 visible ASCII characters). Each is checked before anything is sent.

## Errors

Everything the SDK throws is a `WatchTower15Error`. A `ConfigurationError` or `InvalidPayloadError` is thrown before anything is sent. An `APIError` carries `status`, `code`, `detail`, `requestID`, `headers`, `problem`, `retryAfter` (seconds), `operation` and `response` (the answer’s facts, with its rate limit). Its subclasses: `AuthenticationError` (401, and an ingest 403), `PermissionDeniedError`, `NotFoundError`, `InvalidRequestError` (`errors`), `LimitReachedError` (`limit`, `used`), `PaymentRequiredError`, `PayloadTooLargeError`, `RateLimitError` (`DailyLimitError`, `LogVolumeLimitError` with `resumesAt`), `ServiceUnavailableError`, `ServerError`, `UnexpectedResponseError` (an edge or proxy answered, or a redirect: `cfRay`, `contentType`), `APIConnectionError` (`wasSent`, `responseTooLarge`) and its `APIConnectionTimeoutError`, `APIUserAbortError`, and `WaiterTimeoutError`. `instanceof` works across the ES-module and CommonJS builds.

```ts
try {
  await wt15.servers.view(uuid);
} catch (error) {
  if (error instanceof NotFoundError) console.log(error.status, error.code, error.requestID);
  else if (error instanceof RateLimitError) console.log(error.retryAfter);
  else throw error;
}
```

## Retries and idempotency

Every POST, PUT and DELETE carries an `Idempotency-Key`: yours, or one made for the call and reused on each retry, so a retried write is never done twice, and a replayed answer (`Idempotent-Replayed: true`) is a success.

## Raw responses

Every call returns an `APIPromise`: `.withResponse()` gives `{ data, response }` (status, headers, request id, `replayed`, `rateLimit`), `.asResponse()` the unread `Response`. The request is made when the promise is first consumed.

## Waiting for a scan, and newer operations

`await wt15.scans.waitUntilFinished(scanUuid, { timeoutMs: 120_000, pollIntervalMs: 5000 })` polls until the scan is neither `queued` nor `running`, else throws a `WaiterTimeoutError` carrying the scan. `wt15.request(method, path, params?, options?)` calls an operation newer than the installed SDK with the same auth, retries and errors: `path` is relative to `/v1`, `{name}` placeholders are filled from `params`, the rest goes in the query (GET, DELETE) or the JSON body; a 204 answers `{ data: null }`. `wt15.me()` is `GET /v1/me`.

A `Deprecation` or `Sunset` header on an operation is logged once per operation per process at `warn`, through the client’s `logger`.

Source: https://developer.watchtower15.com/sdks/node/api/
