How-to › Operate integrations in production

How to call an endpoint your SDK does not model with direct()#

Reach an endpoint a generated client has no method for through direct(), keeping its base URL, key, and headers, and add the idempotency key its features skip.

Audience
API consumer
Level
intermediate
Topic
Evaluate, adopt and upgrade SDKs
Languages
TypeScript, Go and Python
Verified

The API ships a beta endpoint, POST /invoices/{id}/reminders, and the SDK you installed has no method for it. You write a fetch call beside the client, with the host from the API reference and the key from your settings. It answers 202 on your laptop. In production the account lives in the EU region, the hand-built URL still goes to the default host, and the answer is 401.

What you get

You will end up with the missing call made through the client’s own direct() method, a wrapper that adds what direct() leaves out, and tests for both. This is for you if you consume an SDK that sdkgen generated and need one endpoint it lacks.

Short answer

Call an endpoint that an sdkgen-generated SDK does not model with client.direct({ path, method, params, body }). The request goes out with the client’s base URL, credentials, configured headers, and transport features such as retry, and resolves to { ok, status, headers, data } instead of throwing. Features that hook entity operations do not run: on a write, pass the Idempotency-Key header yourself. client.prepare() builds the same request without sending it.

You will need

Node 22.6 or later and an SDK that sdkgen generated. The one here comes from api.json, a three-operation description of an invoicing API called Ledger, with the retry, idempotency, and telemetry features added. sdkgen’s documentation says every SDK it generates exposes direct and prepare. The stand-in for the API runs on 127.0.0.1 as two regions, us and eu, each with its own key. It serves two endpoints the document leaves out: POST /invoices/{id}/reminders and GET /invoices/{id}/pdf. Verified 2026-11-19 against Node 22.23.5 and @voxgig/sdkgen 4.44.3.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
NSwag extension codeYou generate the NSwag client yourself and want the endpoint as a typed method on itA hand-written method, URL building included, and a regeneration each time it changesThe client arrives as a package you cannot regenerate
octokit.request()The API is GitHub’s and the installed octokit.rest has no method for the endpointA route string and parameters you must get right yourself, in a client for GitHub aloneAn octokit.rest method already covers the endpoint
openapi-typescript and openapi-fetchA TypeScript client where the missing path can be declared by hand and stay typedA hand-kept type that can disagree with the real endpoint until the document catches upYou need retries, idempotency keys, or a second language from the client
plain fetch beside the SDKA one-off script against one host, with a key you holdA second copy of the base URL, key, and headers that drifts from the client’sThe base URL, a proxy, or the credentials differ between environments
sdkgen direct() and prepare()The SDK is generated by sdkgen and the endpoint answers JSONNo types on path, query, or body, and no idempotency key or trace span on the callYou need the call typed, or covered by the features that hook entity operations
stripe-node rawRequestThe API is Stripe’s and the endpoint is undocumented or in a private betaA method, a path, and parameters passed as plain values, for Stripe aloneThe installed version already has a method for the endpoint

Voxgig maintains sdkgen. It is this page’s subject, and the fifth row states what its escape hatch gives up.

Every row but the plain fetch keeps the request inside the client, so the base URL and the key have one home. The rows differ in what happens to the types. NSwag and openapi-fetch let you write the missing type down, and you then keep it true by hand. direct(), octokit.request(),1 and rawRequest2 send the path you pass, so nothing checks an endpoint they were never told about.

Send the request through the client

direct() takes one object: path, method, params for the placeholders in the path, query, headers, and body. It resolves to a result envelope and does not throw, so a function around it is the place to turn a refusal into an error. reminders.mjs holds that function:

export async function sendReminder(client, invoiceId, { channel = 'email', key = randomUUID() } = {}) {
  // An empty value would build /invoices//reminders, which is another route.
  if (typeof invoiceId !== 'string' || invoiceId === '') {
    throw new TypeError('invoiceId must be a non-empty string')
  }
  const result = await client.direct({
    path: '/invoices/{id}/reminders',
    method: 'POST',
    params: { id: invoiceId },
    // The idempotency feature runs on entity operations only, so the key is passed by hand.
    headers: { 'idempotency-key': key },
    body: { channel },
  })
  // direct() does not throw. A failure is ok: false, with a status or an err.
  if (!result.ok) throw new ReminderError(result)
  return result.data
}

demo.mjs creates an invoice through the modeled Invoice().create(), sends a reminder through sendReminder(), and prints what the eu region received each time:

node demo.mjs
sendReminder(client, 'inv_2') returned {"id":"rem_1","invoice":"inv_2","channel":"email"}

what the eu region received
                    client.Invoice().create()                sendReminder(), through client.direct()
  request           POST /v1/invoices                        POST /v1/invoices/inv_2/reminders
  authorization     Bearer sk-test-eu-1                      Bearer sk-test-eu-1
  x-ledger-account  acct_42                                  acct_42
  user-agent        Mozilla/5.0 (compatible; LedgerSDK/1.0)  Mozilla/5.0 (compatible; LedgerSDK/1.0)
  idempotency-key   minted by the feature                    passed by sendReminder()
  traceparent       set by the feature                       none
  span exported     invoice.create                           none

requests that reached the us region: 0

The base path, the key, the account header, and the user agent are the client’s in both columns.3 The SDK also percent-encodes each value in params as one path segment and refuses . and ... It sends an empty value as an empty segment, which is why the wrapper checks for one.

Pass the idempotency key the features skip

sdkgen features attach at two seams, and direct() passes through only one of them. A transport feature such as retry wraps every HTTP attempt, a direct call included. A feature that hooks the operation pipeline runs on entity operations only, so the direct call in that output carries no traceparent and exports no span. The feature reference names the seam of each feature.

The two seams meet on a write. retry sends a direct POST again, and the idempotency feature has given it no key. lost-response.mjs has the region do the write and then answer 503 once:

node lost-response.mjs
the first response is lost after the write lands
  call                        attempts  idempotency-key      records written
  client.direct(), no key     2         none                 2
  sendReminder()              2         one key, sent twice  1
  client.Invoice().create()   2         one key, sent twice  1

The bare direct call sent one customer two reminders. sendReminder() mints a key per call with randomUUID() and passes it in headers, where both attempts reuse it. The header comes from an IETF draft, so confirm that your API honors it. This stand-in does.

Build the request with prepare() when the answer is not JSON

direct() reads every response body as JSON. GET /invoices/{id}/pdf answers with bytes, so direct() reports a failure for a 200. prepare() takes the same arguments, sends nothing, and resolves to the request direct() would have sent: url, method, headers, and body. pdf.mjs sends it with fetch and reads the bytes itself:

const request = await client.prepare({
  path: '/invoices/{id}/pdf',
  params: { id: invoiceId },
  headers: { accept: 'application/pdf' },
})
// prepare() returns an Error rather than throwing one.
if (request instanceof Error) throw request
const response = await fetch(request.url, request)

prepare.mjs runs the three steps against the eu region:

node prepare.mjs
client.direct() on GET /invoices/{id}/pdf
  ok false, status 200, err.code response_content_type
client.prepare() with the same arguments
  requests sent  0
  method         GET
  path           /v1/invoices/inv_2/pdf
  headers        accept, authorization, content-type, x-ledger-account
invoicePdf(), which sends the prepared request with fetch
  application/pdf, 43 bytes, starting "%PDF-1.4"
  user-agent the region saw: node

The prepared request carries the client’s URL and credentials, but your fetch skips the client’s transport. No feature retries it, and the user agent is Node’s. Keep the prepared request out of logs: headers.authorization holds the key in the clear.

Make the same call in the other two targets

The Go and Python targets generate the same pair of methods. Go’s Direct takes and returns map[string]any, and it reports a refusal or a lost connection inside that map, with a nil error:

result, err := client.Direct(map[string]any{
	"path":   "/invoices/{id}/reminders",
	"method": "POST",
	"params": map[string]any{"id": "inv_2"},
	"body":   map[string]any{"channel": "email"},
})

Python’s direct() returns a dict with the same keys:

result = client.direct({
    "path": "/invoices/{id}/reminders",
    "method": "POST",
    "params": {"id": "inv_2"},
    "body": {"channel": "email"},
})

Run against the same stand-in, each program printed 202 and the reminder.

Add the method to the generated class in NSwag

NSwag generates no method that takes an arbitrary path. Its documented route is to add your own method to the generated client class. In C# the class is partial, so the method goes in a second file. In TypeScript, extension code does that job: name the class in /extendedClasses and give a file as /extensionCode. NSwag copies the body of your class into the generated one, where it can use the private baseUrl and http fields:

sendReminder(invoiceId: string, channel: "email" | "post"): Promise<Reminder> {
    if (invoiceId === undefined || invoiceId === null || invoiceId === "" || invoiceId === "." || invoiceId === "..")
        throw new globalThis.Error("The parameter 'invoiceId' must name one invoice.");
    let url_ = this.baseUrl + "/invoices/{invoiceId}/reminders";
    url_ = url_.replace("{invoiceId}", encodeURIComponent("" + invoiceId));

The result is a typed method that callers cannot tell from a generated one, which direct() does not offer. It costs a regeneration for every change, and a URL and a status check written by hand. The extension file also fails to compile until NSwag has merged it, because the two fields are private. NSwag generated no credential code for this document, so the key rides on the fetch you hand the constructor.

Declare the path by hand for openapi-fetch

openapi-typescript writes types, and openapi-fetch accepts only the paths those types list, so a call to any other path is a compile error. Neither package’s documentation describes a call outside those types. The client’s type parameter is ordinary TypeScript, though. Declare the missing path in the shape the generator uses, and intersect it with the generated paths:

export interface BetaPaths {
  '/invoices/{invoiceId}/reminders': {
    parameters: { query?: never; header?: never; path: { invoiceId: string }; cookie?: never }
    post: {
      parameters: { query?: never; header?: never; path: { invoiceId: string }; cookie?: never }
      requestBody: { content: { 'application/json': { channel: 'email' | 'post' } } }
      responses: {
        202: {
          headers: { [name: string]: unknown }
          content: { 'application/json': { id: string; invoice: string; channel: string } }
        }
      }
    }
  }
}

/** One client for the generated paths and the declared one: same base URL, same headers. */
export const ledgerFetch = (baseUrl: string, key: string) =>
  createClient<paths & BetaPaths>({ baseUrl, headers: { authorization: `Bearer ${key}` } })

other-generators.mjs type-checks both generators’ files and sends one reminder through each client. The flag is Node’s type stripping, which lets the script import the two .ts files as they are:

node --experimental-strip-types other-generators.mjs
tsc -p tsconfig.json, which names three files
  openapi-fetch/undeclared.ts  error TS2345: Argument of type '"/invoices/{invoiceId}/reminders"' is not assignable to parameter of type '"/invoices"'.
  openapi-fetch/declared.ts    ok
  nswag/LedgerClient.ts        ok

one reminder through each client, as the eu region received it
  sdkgen, client.direct()        POST /v1/invoices/inv_2/reminders  Bearer sk-test-eu-1  rem_1
  NSwag, client.sendReminder()   POST /v1/invoices/inv_2/reminders  Bearer sk-test-eu-1  rem_2
  openapi-fetch, client.POST()   POST /v1/invoices/inv_2/reminders  Bearer sk-test-eu-1  rem_3

The declared call compiles with its answer typed, and it goes through the same client. The base URL, the header, and any middleware apply to it as to a generated path. That is more than direct() gives you on types and less on behavior: openapi-fetch documents no retry and no idempotency feature for a raw call to skip.

Check it worked

Run the suite:

node --experimental-strip-types --test direct.test.mjs
1..13
# tests 13
# suites 0
# pass 13
# fail 0
# cancelled 0
# skipped 0
# todo 0

The second test is the one to copy. It asserts that the eu region received authorization: Bearer sk-test-eu-1 on POST /v1/invoices/inv_2/reminders, and that the us region received no request at all.

When it goes wrong

The call answers 202 in development and 401 in production. The request was assembled beside the client, with the host typed in from the API reference, so it ignored the base URL the client was given. pitfall.mjs moves the account to another region and changes the client’s settings alone:

node pitfall.mjs
the account is in the us region, the host the document names
  sendReminder(client)  202 {"id":"rem_1","invoice":"inv_1","channel":"email"}
  hand-built fetch      202 {"id":"rem_2","invoice":"inv_1","channel":"email"}
the account is in the eu region, and only the client was given the new base URL
  sendReminder(client)  202 {"id":"rem_1","invoice":"inv_2","channel":"email"}
  hand-built fetch      401 {"error":"this key is not valid in region us"}

Send the request through direct(), which reads the base URL and the key from the client.

A typo in the path raises no error. direct() resolves with ok: false and status: 404, and a body the endpoint rejects comes back as a 422 the same way. Check ok on every call, or throw from a wrapper as sendReminder() does.

A direct call resolves with ok: false and no status. The request got no answer or was never sent, and err says why. One cause is the SDK’s allow.op and allow.method options, which let whoever configures the client switch raw access off.

When not to do this

Do not call direct() for an endpoint the SDK models. The entity operation gets typed fields and every feature. The direct call gets no types and the transport features alone.

Do not keep the wrapper after the API’s document describes the endpoint. Regenerate or upgrade, and call the modeled operation.

Do not send a write through direct() under retry without an idempotency key, and do not use it for an endpoint that answers anything but JSON.

Do not adopt sdkgen to get an escape hatch: every client in the table has one or can be given one. NSwag’s extension code is the better choice when you own the generation step and the endpoint will stay out of the document for months, because a typed method costs one regeneration. openapi-fetch is the better choice in a TypeScript-only project where a compile error on a mistyped path matters more than built-in retries.

Last verified

Verified 2026-11-19 against Node 22.23.5, @voxgig/create-sdkgen 0.31.9, @voxgig/sdkgen 4.44.3, NSwag 14.8.0, openapi-typescript 7.13.0, openapi-fetch 0.17.0, and TypeScript 5.9.3. Every output block is what the command preceding it printed, against a stand-in on 127.0.0.1. sdkgen, NSwag, and openapi-typescript each ran once, through generate.sh, and what they wrote is committed. NSwag ran on the .NET 10 runtime. The Go and Python programs ran once against the same stand-in and are not re-run on each build, because their generated trees are not committed. Octokit and stripe-node were not run. Their methods come from their READMEs.

Footnotes

  1. Octokit has the order reversed. Its README says that under the covers every endpoint method is octokit.request with defaults set. The escape hatch is the client, and the typed methods are a convenience laid over it. ↩︎ Back to text

  2. The stripe-node README offers rawRequest for an undocumented API, giving a private beta as its example, below a line saying the feature is only available from version 17 of the SDK. Its example passes 2022-11-15; feature_beta=v3 as the apiVersion, because some preview features are named in the Stripe-Version header, beside the date that pins the API. ↩︎ Back to text

  3. The SDK announces itself as Mozilla/5.0 (compatible; LedgerSDK/1.0), and a comment in the generated transport gives the reason: several content delivery networks refuse a library’s own user agent. MDN calls Mozilla/5.0 the general token that says the browser is Mozilla-compatible, and adds that almost every browser sends it for historical reasons. Here a client that is not a browser sends it for a practical one. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.