Call operations
Create a client, send requests, read responses and errors, and share or cancel requests.
These examples use the ProviderClient that Generate an SDK creates. You can use the same operations from your own API.
The client is the only door to the API. It checks and converts each request and each response by itself:
- A response body is a plain object of the SDK type. A
dateordate-timevalue is already aDateor aTemporalvalue (dates). - A request takes plain values. The client writes them in their JSON form.
- The SDK has no model classes. A class with methods is your own model over the SDK type (SDK types in your models).
- Both SDK modes give the same calls.
| Operation | Request | Declared responses |
|---|---|---|
listCharges | GET /charges, optional limit and cursor query | 200: array of charges |
getCharge | GET /charges/{id} | 200: charge. 404: { message } |
createCharge | POST /charges, body { amount, currency } | 201: charge |
export async function logChargeIds(client: ProviderClient): Promise<string[]> {
const response = await client.listCharges().execute({});
for (const charge of response.body) {
console.log(charge.id); // "charge-1"
}
return response.body.map(charge => charge.id);
}A response holds the HTTP status and the decoded body. This includes declared error statuses.
Create a client
export function createProviderClient(options: ProviderClientOptions): ProviderClient {
return new ProviderClient(options);
}| Option | Value |
|---|---|
baseUrl | the API address; required when the document lists no servers, and it wins over server and over the servers of an operation |
server | a number is the index of a document server; a string is its name or description. The first server by default |
serverVariables | values for the {variables} of that server URL |
fetchImpl | the fetch function, global fetch by default |
headers | headers for every request |
auth | credentials by security-scheme name (Authentication) |
operationValidators | validators that replace generated ones (Runtime API) |
validate | the check level of the calls of this client (Lower the checks); only when the client validates |
- An empty
baseUrlis an error. - The client has
serverandserverVariablesonly when the document listsservers. serverandserverVariableschoose from theserverslist of the document root.- An operation, or a path item, that lists its own
serversuses the first server of that list with its variable defaults, whateverserveris.baseUrlstill wins. - A variable that you leave out uses its default. A value outside its
enum, or a variable that the server does not declare, is an error. - A relative server URL such as
/apiis used as written. It works wherefetchaccepts a relative URL, such as a browser. - A value of
authcan be a function that returns the credentials. operationValidatorsreplaces the generated validator of each named operation.
Pass parameters and a body
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' } });
}path,query,headerandcookiehold the operation's parameters.bodyholds the request data, encoded by the body format of the operation.- The input type has a group only when the operation declares it. A group is optional when none of its members is required. Pass
{}when nothing is required. - When the operation accepts several media types, set
bodyto{ contentType, value }. - Pass plain values. A
DateorTemporalvalue goes out as its JSON text. An instance of your own model over the SDK type is a valid body: the client writes its declared fields only. - With validation on, the client checks the input before it calls
fetch.
Import one operation
A feature that uses one endpoint imports its operation factory:
import { getCharge } from './sdk/operations/getCharge.js';
export function readChargeDirectly(baseUrl: string, token: string, id: string) {
const chargeRequest = getCharge({ baseUrl, auth: { bearerAuth: token } });
return chargeRequest.execute({ path: { id } });
}The factory has the name of the operation and takes the client options. It returns the same operation as client.getCharge(), with loading when MobX is on. Create the operation once and call .execute() for each request. If .execute() fails with a ValidationUnavailable error and the message Missing generated input validator for <operation>, run golem generate again.
The SDK names each schema in PascalCase (Generated SDK names). The schema Charge gives the type Charge. A response body is a plain Charge, with converted values:
export async function readChargeData(client: ProviderClient, id: string): Promise<Charge | undefined> {
const response = await client.getCharge().execute({ path: { id } });
return response.status === 200 ? response.body : undefined; // A plain Charge: settlesOn is a Temporal.PlainDate.
}sdk/index.js exports the client, its types and the data types. Import an operation from its own file to let your bundler drop what you do not use. Find the paths in Generated files.
Read responses and handle failures
getCharge declares 200 (charge) and 404 ({ message: string }).
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.
}- Read response data from
body. The response also holdscontentTypeand the declared responseheaders. - Connection failures, undeclared status or media types, and validation failures reject
.execute(). - When several declared responses fit one reply, the client picks one in a fixed order.
Money.amount declares a decimal pattern, so '12,50' fails before fetch runs:
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;
}
}Turn the checks on or off with the validation key. To lower them for one client or one call, use the validate option. Errors and issues shows how to read error.issues. The runtime API holds the issue codes.
Lower the checks
A client that validates checks each request and each response at the level of its SDK. The validate option lowers that level. Set it on the client for all its calls, or in the second argument of .execute() for one call.
| Value | Checks |
|---|---|
true | everything |
'sanity' | the shape only: types, required fields and extra keys. Value limits are skipped |
false | nothing |
{ request, response } | the request and the response apart. Each side takes one of the three levels above |
{ requestHeaders, responseHeaders } | the header checks of the request and of the response, each apart |
- Conversion always runs. A
DateorTemporalvalue is converted at every level, also when the checks are off. requestcovers the body and thepath,queryandcookievalues.responsecovers the body and the stream items.- A level alone sets
requestandresponse. It does not switch the header checks. - The header checks are off unless you name them. A request header that breaks its schema is sent, and a response header is returned without a check. Set
requestHeadersorresponseHeadersto a level to check them. - A side that you leave out takes the level of the next source: the call, then the client, then the SDK.
- You can lower the level, but you cannot raise it. A level above the level of the SDK rejects
.execute()with aLibErrorof kindValidationUnavailable. A sanity SDK has no full checks to switch on. - Any other value rejects
.execute()with aTypeError. - With
response: false, the client does not check the response body, but it still converts it. A date that cannot convert rejects.execute()with aDeserializationerror. - An SDK generated without validation has no
validateoption.
A client that checks only the shape of responses, and one call that does not check its response:
export function createLenientClient(baseUrl: string, token: string) {
return new ProviderClient({ baseUrl, auth: { bearerAuth: token }, validate: { response: 'sanity' } }); // The default of every call.
}
export async function readChargeUnchecked(client: ProviderClient, id: string) {
return client.getCharge().execute({ path: { id } }, { validate: { response: false } }); // This call only; the date still converts.
}Handle errors
An undeclared status or media type rejects .execute() with LibErrorKind.Response. Check it with the generated guard:
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.
}
}A network failure rejects with the fetch error.
Streaming responses
Read the items of a streaming response one at a time instead of waiting for one body.
An operation that declares itemSchema in an OpenAPI 3.2 document has a response.body that is an AsyncIterable of decoded items. Read it with for await.
export async function readEvents(client: ProviderClient): Promise<number[]> {
// Provider response: {"id":1} followed by a newline, then {"id":2}.
const response = await client.readEvents().execute({});
const ids: number[] = [];
for await (const event of response.body) {
ids.push(event.id); // 1, then 2 as those items arrive.
}
return ids;
}Describe the items
For an API that sends one JSON object per line, describe the response in provider.yaml:
/events:
get:
operationId: readEvents
responses:
'200':
description: Events as they happen
content:
application/x-ndjson:
itemSchema:
type: object
required: [id]
properties:
id: { type: integer }The SDK job in golem.yaml reads that document, as in Generate an SDK. Run npx golem generate to update the client.
Read items
.execute()returns the response. Reading the items is a separate step.- A connection, decoding or validation failure throws inside the loop. Wrap the loop in
tryandcatch. - With validation on, the client checks each item before your loop receives it. With validation off, items arrive unchecked.
Stop reading
For the same readEvents operation, provider/events.ts reads one item. Leaving the loop cancels its reader:
export async function firstEvent(client: ProviderClient): Promise<number | undefined> {
const response = await client.readEvents().execute({});
for await (const event of response.body) {
return event.id; // Returning closes the iterator and cancels its reader.
}
}provider/events.ts also cancels from outside the loop:
export async function readUntilClosed(client: ProviderClient, controller: AbortController): Promise<number[]> {
const response = await client.readEvents().execute({}, { signal: controller.signal });
const ids: number[] = [];
try {
for await (const event of response.body) ids.push(event.id);
} catch (error) {
if (!controller.signal.aborted) throw error; // controller.abort() ends the read, for example when the feed closes.
}
return ids;
}Stream formats
| Content type | Items returned |
|---|---|
application/x-ndjson, application/ndjson, application/jsonl, or a media type that ends with +jsonl | a decoded JSON value per line |
application/json-seq, or a media type that ends with +json-seq | a decoded JSON value per record |
text/event-stream | an event object, { data: string, event?, id?, retry? } |
A JSON-seq record can span lines. SSE data stays a string. Parse it in your application if the server sends JSON in that field. A malformed or truncated JSON-seq body fails the iteration and releases the reader. Any other framing needs a streamDecoders entry.
Connect a custom stream decoder
Declare application/vnd.provider.events with itemSchema on a readEventIds operation, then generate ProviderClient again. The decoder below reads integer lines and yields the objects that itemSchema declares. The same file connects it:
// This provider sends one integer per line: "7\n8\n" → { id: 7 }, { id: 8 }.
function eventOf(line: string) {
const id = Number(line);
if (!Number.isInteger(id)) throw new TypeError(`Expected an integer event id, got "${line}"`);
return { id };
}
async function* decodeEventIds(response: Response) {
if (!response.body) return;
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let pending = '';
try {
while (true) {
const chunk = await reader.read();
if (chunk.done) break;
pending += chunk.value; // A line may span several network chunks.
const lines = pending.split('\n');
pending = lines.pop() ?? '';
for (const line of lines) if (line !== '') yield eventOf(line);
}
if (pending !== '') yield eventOf(pending);
} finally {
try { await reader.cancel(); } finally { reader.releaseLock(); }
}
}
export function createEventLinesClient(baseUrl: string, token: string) {
return new ProviderClient({
baseUrl,
auth: { bearerAuth: token },
streamDecoders: { 'application/vnd.provider.events': decodeEventIds },
});
}
export async function firstEventId(client: ReturnType<typeof createEventLinesClient>) {
const response = await client.readEventIds().execute({});
for await (const event of response.body) {
return event.id; // First line "7" returns 7 and closes the stream.
}
}| Decoder contract | Requirement |
|---|---|
| Signature | (response: Response, context: ProviderStreamDecoderContext) => AsyncIterable<unknown> |
| Context | The operation name and the actual response content type |
| Output | Decoded items that match itemSchema |
| Cleanup | Cancel and release each reader you acquire when the iteration ends or fails |
- The client uses the exact media-type key first. This is the actual content type, then the declared one. Next it tries the type and subtype in lowercase without parameters, then
*/*. - A configured decoder replaces the built-in framing.
Reuse an operation
export async function readTwoCharges(client: ProviderClient, firstId: string, secondId: string) {
const getOne = client.getCharge();
const first = await getOne.execute({ path: { id: firstId } });
const second = await getOne.execute({ path: { id: secondId } });
return { first, second };
}- Each
.execute()sends a new request and reads the current credentials. The client caches no responses or errors. - You can call
.execute()again before the first call ends. The client then logsConcurrent execute() invocation for <operation>and sends both requests. To avoid the warning, wait for the first call. - A second
client.getCharge()creates an independent operation.
Observe loading with MobX
Turn on the mobx extension in the openapi-ts block of golem.yaml, install mobx and @exprtlabs/golem-openapi-ts, and generate again.
public get sending(): boolean {
return this.createPayment.loading; // True from execute until the response settles.
}loadingis observable without more setup.- It stays true until every pending call ends, including failed and cancelled calls.
- Without the extension, the operation has no
loadingproperty. - For a streaming response,
loadingends whenexecuteresolves, before you read the body (Streaming responses).
Share headers
export function createClientWithSharedHeaders(baseUrl: string, token: string): ProviderClient {
return new ProviderClient({
baseUrl,
auth: { bearerAuth: token },
headers: { 'X-Client-Name': 'payments-example' }, // Sent with every request from this client.
});
}Set headers for a header that belongs on every request. For credentials, use Authentication.
Send a header parameter
createCharge declares an optional Idempotency-Key header parameter in the document:
post:
operationId: createCharge
parameters:
- in: header
name: Idempotency-Key
schema: { type: string }
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/Money'
responses:
'201':
description: Created charge
content:
application/json:
schema:
$ref: '#/components/schemas/Charge'Pass the value in the header argument of the operation. It applies to that call only, so one client serves every call:
export async function createChargeWithKey(client: ProviderClient, money: Money, idempotencyKey: string) {
return client.createCharge().execute({
header: { 'Idempotency-Key': idempotencyKey }, // Sent with this call only.
body: money,
});
}Cancel a request
export async function listWithCancelButton(client: ProviderClient, button: { onclick: (() => void) | null }) {
const controller = new AbortController();
const request = client.listCharges().execute({}, { signal: controller.signal });
button.onclick = () => controller.abort(); // Rejects the pending request; does not cancel other operations.
try {
return await request;
} catch (error) {
if (!controller.signal.aborted) throw error;
return undefined;
}
}Check controller.signal.aborted before you rethrow a caught error. An error that has nothing to do with the abort must still propagate.
Full example: examples/payments.
