SDKs
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.
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
npm install levelfourClient setup
import { LevelFourClient } from "levelfour";
const client = new LevelFourClient({
apiKey: "l4_live_...",
baseURL: "https://api.levelfour.ai",
timeoutInSeconds: 30,
maxRetries: 2,
});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 covers the rest.Called with no arguments, the client reads LEVELFOUR_API_KEY from the environment.
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 |
client.recommendations.audit | Savings |
client.costs | Costs |
client.providers | Providers |
client.webhooks | Webhooks |
client.auth | Authentication |
Pagination
Methods that return paginated results resolve to a Page object that implements AsyncIterable.
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 has page-level iteration, manual navigation and collectAll.
Errors
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 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.
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.
Raw responses
Every method returns an HttpResponsePromise. Await it for the parsed data, or call .withRawResponse() to get the status and headers alongside it.
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.
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 has every method with its parameters and response shapes, in TypeScript alongside Python and Go
- Pagination walks through page-level iteration, manual navigation and
collectAll - Error Handling is the full error hierarchy and which failures the client retries
- Webhooks is the event types, the payloads and the signature contract
- Authentication covers key formats, scopes, rotation and the
whoamicheck - SDK Overview compares the three clients option by option