> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stockshift.io/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript

> A TypeScript client for the StockShift API. Its types are generated from the API's OpenAPI document, so paths, parameters, bodies and responses are checked when you compile.

It runs on Node.js 20 or later and in browsers. It has no runtime dependencies.

## Install

```bash theme={null}
npm install @stockshift/sdk
```

## Quickstart

Create an item, then list stock on hand:

```ts theme={null}
import { StockShift } from "@stockshift/sdk";

const stockshift = new StockShift({ token: process.env.STOCKSHIFT_TOKEN! });

await stockshift.post("/catalog/items", {
  body: { sku: "BOLT-M4", name: "M4 hex bolt", type: "stocked", make_or_buy: "buy" },
});

for await (const row of stockshift.paginate("/inventory/stock")) {
  console.log(row.sku, row.location_code, row.available_to_promise);
}
```

## Authentication

Pass an API key or an OAuth access token as `token`. Create an API key in the app under Settings > Access > API keys. The key acts as the member who made it, and a call needs both the member's permission and one of the key's scopes.

For an OAuth token that expires, pass a function. The client calls it before each request:

```ts theme={null}
const stockshift = new StockShift({ token: () => tokens.current() });
```

Other options:

| Option | Default | Meaning |
| - | - | - |
| `baseUrl` | `https://app.stockshift.io/api/v1` | Where the API is. |
| `maxRetries` | `2` | Retries for a call that can be retried. |
| `timeout` | `60000` | Milliseconds to wait for each attempt. |
| `maxRetryAfter` | `60` | The longest `Retry-After`, in seconds, worth waiting for. |
| `headers` | none | Headers sent on every call. |
| `fetch` | global `fetch` | The `fetch` to use. |

## Making calls

There is one method for each HTTP method: `get`, `post`, `put`, `patch` and `delete`. Each takes a path as the API reference writes it. Fill in path parameters with `path`, the query string with `query` and the JSON body with `body`:

```ts theme={null}
const { data: item } = await stockshift.get("/catalog/items/{item}", {
  path: { item: "01J8QZ4M..." },
});

const { data: page } = await stockshift.get("/catalog/items", {
  query: { search: "bolt", status: "active" },
});
```

A call resolves to the response body. An empty response resolves to `undefined`, a CSV export to its text and a file to the raw `Response`.

Every schema in the reference has a type under `Schemas`:

```ts theme={null}
import type { Schemas } from "@stockshift/sdk";

type Item = Schemas["ItemResource"];
```

## Pagination

A list that can grow returns one page at a time. `paginate()` follows the cursors and yields each record:

```ts theme={null}
for await (const item of stockshift.paginate("/catalog/items", { query: { search: "bolt" } })) {
  console.log(item.sku);
}
```

To page by hand, send each page's `next_cursor` back as `query.after` until it is `null`.

## Errors

A failed call throws an `ApiError` that holds the RFC 9457 problem details body. Branch on `code`, which is stable. `detail` is written for people and may change.

```ts theme={null}
import { ApiError } from "@stockshift/sdk";

try {
  await stockshift.post("/catalog/items", { body });
} catch (error) {
  if (error instanceof ApiError && error.code === "validation_failed") {
    console.log(error.errors); // { sku: ["Another item already has the SKU BOLT-M4."] }
  }
}
```

`ApiError` also has `status`, `problem` and `headers`. A call that gets no answer, because the network failed or the attempt timed out, throws a `ConnectionError`.

## Retries and idempotency keys

The client retries a `429` after the time in `Retry-After`. It does this for every method, because the API did not run the call. If `Retry-After` is longer than `maxRetryAfter`, it throws instead.

A `5xx` or a network failure is retried for `GET`, `PUT` and `DELETE`, with a short backoff. A `POST` or `PATCH` is retried only when you give it an idempotency key, so a retry cannot make the change twice:

```ts theme={null}
await stockshift.post("/integrations/connections/{connection}/channel/stock/push", {
  path: { connection: connectionId },
  idempotencyKey: crypto.randomUUID(),
});
```

Use a new key for each change you mean to make. The endpoints that honor the key say so in the API reference.

## Webhooks

Check the `StockShift-Signature` header before you trust a delivery. `verifyWebhook()` needs the raw body, exactly as it arrived:

```ts theme={null}
import { verifyWebhook, WebhookVerificationError } from "@stockshift/sdk";

export async function POST(request: Request): Promise<Response> {
  try {
    const event = await verifyWebhook({
      payload: await request.text(),
      header: request.headers.get("StockShift-Signature"),
      secret: process.env.STOCKSHIFT_WEBHOOK_SECRET!,
    });
    if (event.type === "inventory.stock.adjusted") {
      console.log(event.data.item_id, event.data.quantity);
    }
    return new Response(null, { status: 204 });
  } catch (error) {
    if (error instanceof WebhookVerificationError) {
      return new Response(null, { status: 400 });
    }
    throw error;
  }
}
```

It refuses a delivery more than five minutes old. Set `tolerance`, in seconds, to change that. Retries of an event keep its `id`, so store it and skip events you have handled.

To test your own receiver, `signWebhook()` signs a payload the same way StockShift does.

## Versions

The major version moves when the API changes in a way that can break your code, such as a removed field or a new required parameter. New endpoints and fields come in minor versions. `API_VERSION` holds the version of the API reference the package was built from.


## Related topics

- [StockShift for developers](https://docs.stockshift.io/index.md)
- [SDKs](https://docs.stockshift.io/sdks/index.md)
- [Save an automation's draft](https://docs.stockshift.io/api-reference/automations/save-an-automations-draft.md)


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