# TypeScript SDK (/reference/typescript-sdk)

Call your instance from TypeScript or JavaScript with a typed client generated from Marfa's API description.



The TypeScript SDK, `@withmarfa/client`, is a typed client for the API, for a script, a server or a web page. **It's generated from Marfa's API description**, so a path the API doesn't serve, or a required parameter you leave out, fails to compile. Its version is the Marfa release it was generated from.

Each call is one API request, and the SDK keeps nothing between them. An app that should keep working while the instance is out of reach needs a [device](/build/devices), such as one built on the [Swift SDK](/reference/swift-sdk).

## Install the SDK [#install-the-sdk]

The SDK is on npm, for `import` or `require`:

```bash
npm install @withmarfa/client
```

## Create a client [#create-a-client]

Pass the URL your instance is served at and a credential: a key ([Manage keys](/run/manage-keys)) or an app's access token ([Authenticate](/build/authenticate)).

```ts title="client.ts"
import { createClient } from "@withmarfa/client";

export const marfa = createClient({
  baseUrl: process.env.MARFA_API_URL ?? "",
  credential: process.env.MARFA_API_KEY ?? "",
});
```

| Option | What it is |
| - | - |
| `baseUrl` | The instance's `http` or `https` URL, with a path where the instance is served under one, and no query or fragment |
| `credential` | A key or an access token, sent as `Authorization: Bearer <credential>` |
| `fetch` | Optional. A `fetch` to use instead of the global one |

**The client sends the credential only to URLs under `baseUrl`, and never follows a redirect**, so the credential can't reach another server. `createClient` throws a `TypeError` for a credential a bearer token can't hold or a `baseUrl` it can't use, never repeating the credential.

## Upload a file [#upload-a-file]

[Upload a blob](/reference/api/blobs/uploadBlob) takes a file's bytes, not JSON. Pass a `Blob`, an `ArrayBuffer`, a typed array such as a Node `Buffer`, or a `ReadableStream`, and name the file's type in `Content-Type`, which the instance keeps with the blob. Without it, the client sends a `Blob`'s own type, or the type the operation declares. The answer is the blob's hash, type and size:

```ts
import { readFile } from "node:fs/promises";

const { data: blob, error } = await marfa.POST("/blobs", {
  body: await readFile("tide-chart.png"),
  headers: { "Content-Type": "image/png" },
});
if (error) throw new Error(error.error.message);
console.log(blob);
```

Output:

```text
{
  hash: 'sha256:2bab1df2e7e3d2614e09a7dcb7f4adbf67c96cb6efaa0f1068ca19caed5610c8',
  mime_type: 'image/png',
  size_bytes: 69
}
```

The next section makes the blob a file item, and [Handle files](/build/handle-files) covers the rest.

## Call an operation [#call-an-operation]

Name an operation by its method and path, as the [API reference](/reference/api) lists it. Path parameters go in `params.path`, query parameters in `params.query`, and a JSON body in `body`. Each call returns `data` on success, `error` when the server refuses, and the `response`. This one makes the blob above a file item and tags it:

```ts
const { data, error } = await marfa.POST("/items", {
  body: { type: "core.file", properties: { title: "Tide chart", blob_ref: blob.hash, mime_type: blob.mime_type } },
});
if (error) throw new Error(error.error.message);

const { data: tagged } = await marfa.POST("/items/{id}/tags", {
  params: { path: { id: data.item.id } },
  body: { tags: ["coast"] },
});
console.log(tagged?.tags); // [ 'coast' ]
```

Once you've checked `error`, TypeScript knows `data` holds the answer's shape. A path parameter of `.` or `..` throws before anything is sent, because it would name another route.

## Walk every page of a list [#walk-every-page-of-a-list]

A list or a search answers one page at a time, as `{ data, next_cursor }`. `pages` takes a function that fetches the page for a cursor, and yields every entry, fetching each page as you reach it:

```ts
import { pages } from "@withmarfa/client";

const files = pages(async (cursor) => {
  const { data, error } = await marfa.GET("/items", {
    params: { query: { type: "core.file", cursor } },
  });
  if (error) throw new Error(error.error.message);
  return data;
});

for await (const file of files) {
  if ("id" in file) console.log(file.id, file.properties.title);
}
```

* **`pages` follows `next_cursor` until it's `null`.** A page can be short, or empty, and still have more after it, so don't stop a walk early.
* **It throws when a page has no `next_cursor`, or repeats a cursor it already followed**, rather than yield entries it can't trust or walk forever.
* The `"id" in file` check is there because a listing with `include=metadata` returns each item with its metadata instead.

The rows of a [table](/build/tables) page the same way, from `GET /items/{id}/tables/{table}/rows`.

## Handle errors [#handle-errors]

When the server refuses a request, `error` holds its error envelope, `{ error: { code, message } }`, with `details` where the refusal has them. **Write your logic against `code`**, because the wording of `message` can change. Reading an item that doesn't exist prints its status and code:

```ts
const { error, response } = await marfa.GET("/items/{id}", {
  params: { path: { id: "01a12192-a000-76e3-b129-b55027e21dcb" } },
});
if (error) console.log(response.status, error.error.code);
```

Output:

```text
404 item_not_found
```

A refusal that says when to try again, such as `429 rate_limited`, carries a `Retry-After` header in `response`, and the same number of seconds in `error.error.details.retry_after_seconds`. [Errors](/reference/errors) lists every code.

A call throws instead of returning `error` when there's no answer to read: the network failed, the URL is outside `baseUrl`, the server answered with a redirect, or the answer failed the contract check.

## The contract check [#the-contract-check]

The SDK was generated for one version of Marfa's contract, which it exports as `CONTRACT_VERSION`. The version travels in the `X-Marfa-Contract` header, which the SDK exports as `CONTRACT_HEADER`:

* **Every request names the client's version**, except a read of `/` or `/health`, which says which version a server speaks. A server on another version refuses the request with `412 contract_mismatch` before it acts.
* **Every answer is checked.** If an answer names another version, or a success names none, the client throws `ContractMismatchError` instead of reading a body it may not understand. An error answer with no header, such as one from a proxy in front of the server, comes back as `error` like any other.

Against a server on contract 1, this prints:

```ts
import { ContractMismatchError } from "@withmarfa/client";

try {
  await marfa.GET("/items", { params: { query: { type: "core.file" } } });
} catch (thrown) {
  if (thrown instanceof ContractMismatchError) console.log(thrown.message);
  else throw thrown;
}
```

Output:

```text
The server answered with contract "1"; this client was generated for contract 0. Use a client generated for the server's contract.
```

The error also holds `served`, the header as it arrived or `null`, and the answer's `status`. The fix is the `@withmarfa/client` release that matches your instance.

## Exports [#exports]

| Export | What it is |
| - | - |
| `createClient` | Makes a client for one instance |
| `pages` | Walks every page of a list |
| `ContractMismatchError` | Thrown for an answer from another contract version |
| `CONTRACT_VERSION`, `CONTRACT_HEADER` | The contract version the SDK was generated for, and the header that carries it |
| `MarfaClient`, `Page` | The client's type, and one page of a list |
| `paths`, `components`, `operations` | The types generated from the API description, such as `components["schemas"]["Item"]` |

The client is an [openapi-fetch](https://openapi-ts.dev/openapi-fetch/) client. Middleware you add with `client.use` sees each request without the credential, and each answer after the contract check.

## What the SDK doesn't do [#what-the-sdk-doesnt-do]

The SDK sends what the API description declares and returns what the server answered. It doesn't retry a request, even one refused with `Retry-After`, poll a bulk job, read the event stream, verify a webhook's signature or resolve a version conflict. [Write safely](/build/write-safely), [Keep in sync](/build/keep-in-sync) and [Receive webhooks](/build/receive-webhooks) show how to do each with the API.
