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 want | Golem gives you |
|---|---|
To call an operation such as getCharge | A ProviderClient method for each operation, with typed input and a typed response |
| To send a bearer token | An auth option on the client, keyed by the name of the security scheme |
To use a schema such as Charge | A TypeScript type for each schema. The client returns plain objects of that type |
| Dates as dates | Temporal.Instant and Temporal.PlainDate values in the response, from format: date-time and format: date |
| To know when the partner breaks the contract | A 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 data | Your own model over the SDK types, with methods |
Step 1: Install
npm install @exprtlabs/golem temporal-polyfill
npm install --save-dev @exprtlabs/golem-openapi-ts @exprtlabs/golem-model typescript@~7.1.0-beta@exprtlabs/golem-modelis 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 rungolem generate, and to build your own models. - Check the requirements and the project settings, such as
"type": "module". - Add
"esnext.temporal"tocompilerOptions.libintsconfig.json. Or setskipLibCheck: true. The SDK types name the globalTemporalwhen you setdates: 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.yamlat the project root. Start it withversion: 1. Paths in it are relative to the file.
- input: provider/provider.yaml
output: provider/sdk
name: Provider
dates: temporal| Key | Meaning |
|---|---|
input | The partner's document |
output | The directory that golem fills with the client |
name | The prefix of the client, so Provider gives ProviderClient |
dates: temporal | Temporal values for dates and times in place of Date (the openapi-ts block) |
mode | Leave 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):
model: {}Golem reads OpenAPI 3.1 and 3.2 documents (OpenAPI support).
Step 3: Generate the client
npx golem generateThe 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.
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
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>bearerAuthis 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
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,cookieandbody. Pass{}when nothing is required.
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
statusand the decodedbody. 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. Checkstatusbefore you readbody.
Reuse, shared headers and cancel are in Call operations.
Step 6: Read dates as Temporal values
dates: temporalin Step 2 makesformat: date-timeaTemporal.Instant,format: dateaTemporal.PlainDateandformat: durationaTemporal.Duration.- A
Temporalmust exist when golem converts a value. Installtemporal-polyfilland importtemporal-polyfill/globalonce, before the first conversion. A runtime that has a globalTemporalneeds 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
bodyholds the Temporal values:
Schema format | JSON text | In your code |
|---|---|---|
date-time | 2025-01-02T03:04:05Z | Temporal.Instant |
date | 2025-02-01 | Temporal.PlainDate |
duration | PT1H30M | Temporal.Duration |
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';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:
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.
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 ofCharge.- Your class extends
model<T>()from@exprtlabs/golem/modeland adds methods with zero imports from generated files. - The model is yours. The client still returns the plain
Charge.
export type TChargeRecord = IModel<{ charge: Charge }>;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: Chargeholds a plainCharge. ItssettlesOnis aTemporal.PlainDate. isOverduetakes today's date as an argument, so a test can fix the date. The settlement day itself is not overdue.- The
temporal-polyfill/globalimport gives the globalTemporal(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 rungolem 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:
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 tool | Command |
|---|---|
| Build, then run the JavaScript | npx golem build, then node on the compiled entry file under your outDir |
| Let Node load the TypeScript | node --import @exprtlabs/golem/register src/main.ts |
- Node.js 22.15 or newer. Before 22.18, add
--experimental-strip-typesto the loader command (Node versions). - The loader needs ES modules and the generated files, so run
npx golem generateonce first. - The build command writes into the
outDirof your tsconfig. Which file is the entry depends on yourrootDirand your entry file (Build with golem build).
Reference
- the
openapi-tsblock: every key of the SDK job. - Generated client: options, results and failures of the client.
- Client authentication: the schemes and what the client sends.
- Generated SDK names: the names for each schema.
- SDK modes: standalone and golem.
- Temporal types: the six types and their JSON strings.
- OpenAPI support: the features that the generator reads.
- Guides: Call operations, Authentication, Dates and times, SDK types in your models, Build tools.
Full example: examples/payments.
