# TypeScript SDK

> Installing and constructing the TypeScript client, and the behavior that is specific to it. Constructor and per-request options, raw responses, pagination, errors and webhook verification.

Source: https://docs.levelfour.ai/sdks/typescript


`levelfour` is the LevelFour client for TypeScript. This page covers installing it, constructing it, and the behavior that belongs to the client rather than to the API. Every method, with its parameters and response shapes, is on the page that owns its sub-client, listed below.

## Installation

```bash
npm install levelfour
```

## Client setup

```typescript
import { LevelFourClient } from "levelfour";

const client = new LevelFourClient({
    apiKey: "l4_live_...",
    baseURL: "https://api.levelfour.ai",
    timeoutInSeconds: 30,
    maxRetries: 2,
});
```

> **Tip**
>
> The `apiKey` literal above is for illustration. A key committed to source stays in the history after you delete the line, so read it from the environment or a secrets manager instead. [Authentication](/authentication#security-best-practices) covers the rest.

Called with no arguments, the client reads `LEVELFOUR_API_KEY` from the environment.

```typescript
const client = new LevelFourClient();
```

### Constructor options

| Parameter          | Type                     | Default                     |
| ------------------ | ------------------------ | --------------------------- |
| `apiKey`           | `string`                 | `LEVELFOUR_API_KEY` env var |
| `baseURL`          | `string`                 | `https://api.levelfour.ai`  |
| `timeoutInSeconds` | `number`                 | `30`                        |
| `maxRetries`       | `number`                 | `2`                         |
| `fetch`            | `typeof fetch`           | Built-in                    |
| `defaultHeaders`   | `Record<string, string>` | `undefined`                 |

## What the client exposes

Each resource hangs off the client as a sub-client. Its owning page carries the methods, their parameters and their response shapes.

| Attribute                      | Reference                                     |
| ------------------------------ | --------------------------------------------- |
| `client.recommendations`       | [Recommendations](/resources/recommendations) |
| `client.recommendations.audit` | [Savings](/resources/savings)                 |
| `client.costs`                 | [Costs](/resources/costs)                     |
| `client.providers`             | [Providers](/resources/providers)             |
| `client.webhooks`              | [Webhooks](/webhooks)                         |
| `client.auth`                  | [Authentication](/authentication)             |
| `client.costAlerts`            | [Cost Alerts](/resources/cost-alerts)         |

## Pagination

Methods that return paginated results resolve to a `Page` object that implements `AsyncIterable`.

```typescript
for await (const rec of await client.recommendations.list({ page_size: 50 })) {
    console.log(rec.recommendation_id);
}
```

Await the call once to get the `Page`, then let `for await` pull each item from it. [Pagination](/pagination) has page-level iteration, manual navigation and `collectAll`.

## Errors

```typescript
import { LevelFourClient, NotFoundError, LevelFourError } from "levelfour";

const client = new LevelFourClient();

try {
    await client.recommendations.get({ recommendation_id: "rec_nonexistent" });
} catch (err) {
    if (err instanceof NotFoundError) {
        console.log("Not found:", err.message);
    } else if (err instanceof LevelFourError) {
        console.log(`API error ${err.statusCode}: ${err.message}`);
    }
}
```

Every error class extends `LevelFourError`, so the last branch catches whatever the earlier ones miss. [Error Handling](/error-handling) is the full hierarchy, the properties an error carries, and which failures the client retries.

## Webhook verification

`WebhookVerifier` checks the signature on an incoming request and throws `WebhookVerificationError` when it does not match.

```typescript
import { WebhookVerifier, WebhookVerificationError } from "levelfour";

const verifier = new WebhookVerifier("whsec_your_signing_secret");

try {
    const payload = verifier.verify(requestBody, {
        "webhook-id": headers["webhook-id"],
        "webhook-timestamp": headers["webhook-timestamp"],
        "webhook-signature": headers["webhook-signature"],
    });
    console.log("Verified event:", payload.type);
} catch (err) {
    if (err instanceof WebhookVerificationError) {
        console.log("Verification failed:", err.message);
    }
}
```

The header contract, the signature algorithm, the timestamp tolerance and the event payloads are on [Webhooks](/webhooks).

## Raw responses

Every method returns an `HttpResponsePromise`. Await it for the parsed data, or call `.withRawResponse()` to get the status and headers alongside it.

```typescript
const data = await client.costs.getSummary();

const { data: costs, rawResponse } = await client.costs
    .getSummary()
    .withRawResponse();

console.log(rawResponse.status);
console.log(rawResponse.headers);
```

## Request options

A request options object overrides the client defaults for one call. When a method takes parameters, the options object goes second. `getSavingsByProvider` takes none, so here it is the only argument.

```typescript
const controller = new AbortController();

const summary = await client.recommendations.getSavingsByProvider({
    timeoutInSeconds: 60,
    maxRetries: 5,
    headers: { "X-Request-Id": "abc123" },
    abortSignal: controller.signal,
});
```

| Option             | Type                     | Description                    |
| ------------------ | ------------------------ | ------------------------------ |
| `timeoutInSeconds` | `number`                 | Override request timeout       |
| `maxRetries`       | `number`                 | Override max retry attempts    |
| `headers`          | `Record<string, string>` | Extra headers for this request |
| `abortSignal`      | `AbortSignal`            | Cancel the request             |

## Next

* [Resources](/resources) has every method with its parameters and response shapes, in TypeScript alongside Python and Go
* [Pagination](/pagination) walks through page-level iteration, manual navigation and `collectAll`
* [Error Handling](/error-handling) is the full error hierarchy and which failures the client retries
* [Webhooks](/webhooks) is the event types, the payloads and the signature contract
* [Authentication](/authentication) covers key formats, scopes, rotation and the `whoami` check
* [SDK Overview](/sdks) compares the three clients option by option
