Skip to content

Call a partner's API ​

Turn a partner's OpenAPI 3.1 document into a typed client for a Node.js service, with bearer auth, Temporal dates, checked and converted responses and your own model class.

What golem gives you ​

Golem reads the partner's document and writes a TypeScript client from it. The examples use a payment provider. Its document is provider.yaml, and name: Provider makes the client ProviderClient.

You wantGolem gives you
To call an operation such as getChargeA ProviderClient method for each operation, with typed input and a typed response
To send a bearer tokenAn auth option on the client, keyed by the name of the security scheme
To use a schema such as ChargeA TypeScript type for each schema. The client returns plain objects of that type
Dates as datesTemporal.Instant and Temporal.PlainDate values in the response, from format: date-time and format: date
To know when the partner breaks the contractA check of each request and response, and a LibError when one fails. You can lower the checks per client or per call
Your own rules on the partner's dataYour own model over the SDK types, with methods

Step 1: Install ​

sh
npm install @exprtlabs/golem temporal-polyfill
npm install --save-dev @exprtlabs/golem-openapi-ts @exprtlabs/golem-model typescript@~7.1.0-beta
  • @exprtlabs/golem-model is for your own model in Step 8. Leave it out when you do not write one.
  • A standalone SDK (the default) carries the golem runtime that it uses. Generated code imports nothing from @exprtlabs/golem. You need the package to run golem generate, and to build your own models.
  • Check the requirements and the project settings, such as "type": "module".
  • Add "esnext.temporal" to compilerOptions.lib in tsconfig.json. Or set skipLibCheck: true. The SDK types name the global Temporal when you set dates: temporal.
  • Include the output directory of the job in the TypeScript program, for example provider/sdk/**/*.ts, so it holds the generated client.

Step 2: Add the document and the job ​

  • Save the partner's document in your project, as YAML or JSON. The example keeps it in provider/provider.yaml.
  • Add golem.yaml at the project root. Start it with version: 1. Paths in it are relative to the file.
yaml
- input: provider/provider.yaml
  output: provider/sdk
  name: Provider
  dates: temporal
KeyMeaning
inputThe partner's document
outputThe directory that golem fills with the client
nameThe prefix of the client, so Provider gives ProviderClient
dates: temporalTemporal values for dates and times in place of Date (the openapi-ts block)
modeLeave it out for a standalone SDK, which runs alone. golem leaves checks and conversions to the models job (SDK modes)

The models job lets your own model class use the SDK types (Step 8):

yaml
model: {}

Golem reads OpenAPI 3.1 and 3.2 documents (OpenAPI support).

Step 3: Generate the client ​

sh
npx golem generate

The command writes provider/sdk/. You choose whether to ignore or commit the generated files (ignore or commit them). Run the command again when the partner publishes a new version of the document.

Import from sdk/index.js. Each schema in components.schemas gives a type. The schema Charge gives the type Charge. The SDK has no model classes. The other names are in Generated SDK names.

ts
import { LibError, LibErrorKind } from '@exprtlabs/golem/errors';
import { type Charge, isProviderUndeclaredResponseError, type Money, ProviderClient } from './sdk/index.js';

Step 4: Create the client with bearer auth ​

ts
export function createAuthorizedClient(baseUrl: string, token: string): ProviderClient {
  return new ProviderClient({
    baseUrl,
    auth: { bearerAuth: token }, // Keyed by security scheme name.
  });
}
// The request includes: Authorization: Bearer <token>
  • bearerAuth is the name of the security scheme in the document.
  • The client sends Authorization: Bearer <token> with each request.
  • Pass a function instead of a string when the token changes while the client lives. The client calls it for each request.

The client has an auth option only when the document declares the security scheme and requires it. Other schemes, a document that lacks the security scheme, and mutual TLS are in Authentication.

Step 5: Call an operation and read the response ​

ts
export async function readChargePage(client: ProviderClient, cursor?: string) {
  return client.listCharges().execute({ query: { limit: 20, cursor } });
}

export async function createCharge(client: ProviderClient, amount: string) {
  return client.createCharge().execute({ body: { amount, currency: 'USD' } });
}
  • client.listCharges() makes an operation. .execute(input) sends the request.
  • The input has a group for each kind of parameter that the operation declares: path, query, header, cookie and body. Pass {} when nothing is required.
ts
export async function readCharge(client: ProviderClient, id: string) {
  const response = await client.getCharge().execute({ path: { id } });
  if (response.status === 404) {
    return response.body.message; // Declared 404: data from the provider, not a thrown failure.
  }
  return response.body.money.amount; // Status 200 narrows body to the charge type.
}
  • A response holds status and the decoded body. The client has checked and converted the body: it is a plain object of the SDK type.
  • A status that the document declares, such as 404, gives you a response, not an error. Check status before you read body.

Reuse, shared headers and cancel are in Call operations.

Step 6: Read dates as Temporal values ​

  • dates: temporal in Step 2 makes format: date-time a Temporal.Instant, format: date a Temporal.PlainDate and format: duration a Temporal.Duration.
  • A Temporal must exist when golem converts a value. Install temporal-polyfill and import temporal-polyfill/global once, before the first conversion. A runtime that has a global Temporal needs no polyfill. Without any, conversion fails with "Temporal is not available".
  • The JSON form stays an ISO 8601 string. The client converts it for you, so the response body holds the Temporal values:
Schema formatJSON textIn your code
date-time2025-01-02T03:04:05ZTemporal.Instant
date2025-02-01Temporal.PlainDate
durationPT1H30MTemporal.Duration
ts
import 'temporal-polyfill/global';
import { fromWireFormat, toWireFormat } from '@exprtlabs/golem/serde';
import type { ProviderClient } from './sdk/index.js';
import type { ChargeRecord, TChargeRecord } from './charge-record.model.js';
ts
export async function readSettlementDate(client: ProviderClient, id: string): Promise<Temporal.PlainDate | undefined> {
  const response = await client.getCharge().execute({ path: { id } });
  if (response.status !== 200) return undefined;
  return response.body.settlesOn; // settlesOn is `format: date`, so the client returns a Temporal.PlainDate
}

The client writes a Temporal value in a request as its ISO 8601 string. A Temporal.Instant is written with Z. A model of your own writes the strings back with toWireFormat<T> (Dates and times).

Step 7: Handle a reply that breaks the contract ​

A request or a response that breaks its schema rejects .execute(). This catch block handles both. The example sends an amount that breaks a pattern:

ts
export async function chargeAmountIssues(client: ProviderClient, amount: string) {
  try {
    await client.createCharge().execute({ body: { amount, currency: 'USD' } });
    return [];
  } catch (error) {
    if (error instanceof LibError && error.kind === LibErrorKind.Validation) {
      return error.issues; // "12,50" violates the amount pattern; issue.path identifies the field.
    }
    throw error;
  }
}

A request or a response that breaks its schema gives a LibError of kind Validation. To lower or switch off the checks for one client or one call, use the validate option. An undeclared status or media type gives kind Response. A network failure rejects with the error of fetch. Each failure, the guard isProviderUndeclaredResponseError and the issue fields are in Read responses and handle failures.

ts
export async function fetchCharge(client: ProviderClient, id: string) {
  try {
    return await client.getCharge().execute({ path: { id } });
  } catch (error) {
    if (isProviderUndeclaredResponseError(error)) {
      // error.kind === LibErrorKind.Response
      console.error(`Undeclared response for ${id}: HTTP ${error.status}`);
      return undefined;
    }
    throw error; // Network failures reject with the underlying fetch error.
  }
}

Every failure and its result are in the generated client reference. The issue codes are in the errors reference.

Step 8: Add your own model ​

The SDK has no model classes. Put your rules in a model of your own, over the SDK type:

  • IModel<Charge> makes a model with the fields of Charge.
  • Your class extends model<T>() from @exprtlabs/golem/model and adds methods with zero imports from generated files.
  • The model is yours. The client still returns the plain Charge.
ts
export type TChargeRecord = IModel<{ charge: Charge }>;
ts
export class ChargeRecord extends model<TChargeRecord>() {
  public isOverdue(today: Temporal.PlainDate): boolean {
    return Temporal.PlainDate.compare(this.charge.settlesOn, today) < 0; // The settlement day itself is not overdue.
  }
}
  • The field charge: Charge holds a plain Charge. Its settlesOn is a Temporal.PlainDate.
  • isOverdue takes today's date as an argument, so a test can fix the date. The settlement day itself is not overdue.
  • The temporal-polyfill/global import gives the global Temporal (Step 6).
  • Golem links a class to its model through extends model<T>() (generated names). Keep methods in that class.
  • Because extends model<T>() needs no generated import, your editor type-checks the class before you run golem generate.

Build the model from the body of a response with the constructor. The client has checked the body, so the constructor runs no second check:

ts
export type TChargeView = IModel<Charge>; // A model over the type itself: its fields are the fields of Charge.

export class ChargeView extends model<TChargeView>() {
  public readonly fetchedAt: Temporal.Instant; // App state: not a field of Charge, so it is never sent or checked.

  public constructor(values: Partial<ModelInit<TChargeView>>, fetchedAt = Temporal.Now.instant()) {
    super(values); // Assigns the fields of Charge first.
    this.fetchedAt = fetchedAt;
  }
}

SDK types in your models shows custom constructors, golem mode and the whole flow, with validation and sending.

Step 9: Run with Node ​

fromWireFormat<T>, toWireFormat<T> and four more calls need a build tool that rewrites them (Build tools). Choose one:

Build toolCommand
Build, then run the JavaScriptnpx golem build, then node on the compiled entry file under your outDir
Let Node load the TypeScriptnode --import @exprtlabs/golem/register src/main.ts
  • Node.js 22.15 or newer. Before 22.18, add --experimental-strip-types to the loader command (Node versions).
  • The loader needs ES modules and the generated files, so run npx golem generate once first.
  • The build command writes into the outDir of your tsconfig. Which file is the entry depends on your rootDir and your entry file (Build with golem build).

Reference ​

Full example: examples/payments.