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, such as one built on the Swift SDK.
Install the SDK
The SDK is on npm, for import or require:
npm install @withmarfa/clientCreate a client
Pass the URL your instance is served at and a credential: a key (Manage keys) or an app's access token (Authenticate).
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 blob 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:
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);{
hash: 'sha256:2bab1df2e7e3d2614e09a7dcb7f4adbf67c96cb6efaa0f1068ca19caed5610c8',
mime_type: 'image/png',
size_bytes: 69
}The next section makes the blob a file item, and Handle files covers the rest.
Call an operation
Name an operation by its method and path, as the API reference 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:
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
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:
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);
}pagesfollowsnext_cursoruntil it'snull. 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 filecheck is there because a listing withinclude=metadatareturns each item with its metadata instead.
The rows of a table page the same way, from GET /items/{id}/tables/{table}/rows.
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:
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);404 item_not_foundA 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 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 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 with412 contract_mismatchbefore it acts. - Every answer is checked. If an answer names another version, or a success names none, the client throws
ContractMismatchErrorinstead 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 aserrorlike any other.
Against a server on contract 1, this prints:
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;
}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
| 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 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
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, Keep in sync and Receive webhooks show how to do each with the API.