# How to expose an escape hatch for endpoints an SDK does not model

> Give callers one raw request method that shares the transport of the modeled methods, measure what a raw call carries, and decide how wide the hatch opens.

Source: https://voxgig.com/howto/escape-hatch-for-unmodelled-endpoints

- Audience: api-producer
- Level: intermediate
- Languages: typescript, go
- Verified: 2026-11-19
- Published: 2026-11-19

## Short answer

Expose one raw request method on the client and send it through the transport the modeled operations use, never through an HTTP client of its own. An SDK generated by sdkgen has it as `direct()`, with `prepare()` to build the request unsent. Then test what a raw call carries: it gets the base URL, headers, retries, and token refresh, and skips features that hook the operation pipeline, such as tracing. `allow.op` and `allow.method` narrow or close it.

---
## You will need

Node 22.7 or later, an OpenAPI 3 document, and the SDK you generate from it. The SDK here is
generated by sdkgen from `api.json`, a three-operation description of a parcel API called
Courier, with the `retry`, `telemetry`, and `secrets` features. The stand-in API on 127.0.0.1
sells short-lived access tokens for a refresh token. It also serves one endpoint the document
leaves out, `POST /parcels/{id}/reroute`. Verified 2026-11-19 against Node 22.23.5 and
`@voxgig/sdkgen` 4.44.3.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [NSwag extension code](https://github.com/RicoSuter/NSwag/wiki/TypeScriptClientGenerator) | You generate C# or TypeScript with NSwag and can add one method to the client class | A raw method you write and keep, which must call the hook the generated methods call | You publish in more languages than NSwag's two |
| [Octokit `request()` with route strings](https://github.com/octokit/octokit.js#octokitrequest) | You design the client around one request function and build each endpoint method on it | A decision made at the start: an SDK built method by method needs a rewrite to adopt it | The SDK exists and its methods do not share one request function |
| [OpenAPI Generator `BaseAPI.request()`](https://openapi-generator.tech/docs/generators/typescript-fetch/) | You generate with OpenAPI Generator and can ship one hand-written subclass beside its output | `request()` is protected and adds no credential, so the subclass repeats lines every generated method carries | You want the raw method generated, the same in every language |
| [sdkgen `direct()` and `prepare()`](https://github.com/voxgig/sdkgen/blob/main/docs/explanation/operation-pipeline.md) | The SDK is generated by sdkgen, which emits both methods in every target | Raw calls skip every feature at the pipeline-hook seam, tracing included, and return untyped data | Raw calls must be traced or validated exactly as modeled calls are |

Voxgig maintains sdkgen. It is one of four options here, not the recommendation.

All four put the raw call on the client, which keeps the base URL and the credential out of the
caller's hands. They differ in how much a raw call shares with a modeled one. In Octokit the
modeled methods are built on the raw one, so the two share one path. OpenAPI Generator and
NSwag share what your hand-written method remembers to call. sdkgen shares the transport and
skips the pipeline hooks. Stainless is absent from the table: it
[announced](https://www.stainless.com/blog/stainless-is-joining-anthropic/) that it is winding
down its hosted SDK generator.

## Compare a raw call with a modeled call

An escape hatch is worth what it shares with the modeled methods. `parity.mjs` builds one client,
makes a modeled call and a raw call, and compares what the API received. It then fails the API
once, and expires the access token once, under each kind of call:

```bash
node parity.mjs
```

```text output
                      modeled: client.Parcel().load()           raw: client.direct()
request               GET /v1/parcels/pcl_1                     POST /v1/parcels/pcl_1/reroute
authorization         Bearer at-1                               Bearer at-1                               same
x-courier-tenant      tnt_7                                     tnt_7                                     same
user-agent            Mozilla/5.0 (compatible; CourierSDK/1.0)  Mozilla/5.0 (compatible; CourierSDK/1.0)  same
traceparent header    sent                                      none                                      DIFFERENT
span exported         parcel.load                               none                                      DIFFERENT
one 503 from the API  2 attempts, answered                      2 attempts, answered                      same
access token expired  2 attempts, 1 token bought, answered      2 attempts, 1 token bought, answered      same
```

Five rows match. `direct()` sends through the client's transport, so it carries the base URL, the
configured header, and the credential. The `retry` and `secrets` features wrap that transport, so
both paths retried the 503 and replaced the spent token.[^1] The two `DIFFERENT` rows are the
`telemetry` feature. It hooks the operation pipeline, and `direct()` dispatches no pipeline hook,
so a raw call has no span and no [`traceparent`](https://www.w3.org/TR/trace-context/) header.[^2]

The Go target ran against the same stand-in with the same result: `Direct` bought its token, was
retried after a 503, and sent no `traceparent`.

## Attach what raw calls must carry at the transport seam

The sdkgen
[hooks reference](https://github.com/voxgig/sdkgen/blob/main/docs/reference/hooks.md) names two
seams a feature can attach at: the pipeline hooks and the transport. A behavior that must reach raw calls belongs at the transport seam. `stamp.mjs` writes one
behavior both ways, a header that names the SDK build. This is the transport version:

```js title="stamp.mjs"
export class TransportStamp {
  name = 'stamp'
  version = '0.0.1'
  active = true

  constructor(build) {
    this.build = build
  }

  init(ctx) {
    const inner = ctx.utility.fetcher
    ctx.utility.fetcher = (callctx, url, fetchdef) =>
      inner(callctx, url, { ...fetchdef, headers: { ...fetchdef.headers, 'x-courier-client': this.build } })
  }
}
```

`seams.mjs` gives each version to the client through its `extend` option and reads the header the
API received:

```bash
node seams.mjs
```

```text output
x-courier-client as the API received it
  the feature attaches as a   modeled call   raw call
  PreRequest hook             ts/2.1.0       missing
  transport wrapper           ts/2.1.0       ts/2.1.0
```

The hook version stamps modeled calls alone. The transport version replaces `utility.fetcher`,
the function that `direct()` and every entity operation call, so it stamps both. `init()` runs
only for a feature that is switched on, here with `feature: { stamp: { active: true } }`.

## Decide how wide the hatch opens

A raw method sends any verb to any path with the client's credential. The generated client has
two allow-lists for that, `allow.method` and `allow.op`, set where the client is constructed:

```bash
node policy.mjs
```

```text output
the client is built with            direct() POST       direct() GET        Parcel().list()
the generated default               sent                sent                sent
allow: { method: 'GET' }            refused, not sent   sent                sent
allow: { op: 'create,load,list' }   refused, not sent   refused, not sent   sent
```

`allow.method` covers modeled calls too, so `GET` alone makes the whole client read-only.
`allow.op` names the operations the client may run. Leave out both `direct` and `graphql`,
because `graphql()` posts through the same raw path. `allow.op` does not cover `prepare()`, which
still returns the URL and the `authorization` header for a caller to send. Both lists are constructor
options, so a factory you export can set them and a caller can set them back. Treat them as a
default, not as a boundary.

## Subclass the OpenAPI Generator client

OpenAPI Generator's
[`typescript-fetch`](https://openapi-generator.tech/docs/generators/typescript-fetch/) generator
documents no raw request method. In the client it wrote from `api.json`, every generated method
ends in `BaseAPI.request()`, which applies the base path, the configured headers, and the
middleware. That method is `protected`, so a subclass exposes it, kept outside the directory the
generator writes to:

```ts title="openapi-generator/raw-api.ts"
const headers: runtime.HTTPHeaders = { 'Content-Type': 'application/json' }
// Each generated method adds the credential itself, so the raw path has to as well.
const token = this.configuration.accessToken
if (token) headers['Authorization'] = `Bearer ${await token('bearerAuth', [])}`

const response = await this.request({ path: urlPath, method, headers, body })
return response.json()
```

The comment marks the cost. Each generated method builds its own `Authorization` header before
it calls `request()`, so the subclass repeats those lines, and a subclass without them gets a
401. Reach also differs by generator: the Go client exports neither `callAPI` nor
`prepareRequest`. What you gain is one seam. A middleware registered on the `Configuration` runs
for generated and raw calls alike.

## Add a raw method to the NSwag client

NSwag generates no raw request method either. Its
[extension code](https://github.com/RicoSuter/NSwag/wiki/TypeScriptClientGenerator) copies the
body of a class you write into the generated TypeScript client, and a C# client is a
[`partial` class](https://github.com/RicoSuter/NSwag/wiki/CSharpClientGenerator) you extend in a
second file. Set `UseTransformOptionsMethod`, and every generated method passes its options
through `transformOptions` on your base class. The raw method makes the same call:

```ts title="nswag/courier-extensions.ts"
let options_: RequestInit = {
    body: body === undefined ? undefined : JSON.stringify(body),
    method: method,
    headers: {
        "Content-Type": "application/json",
        "Accept": "application/json"
    }
};

return this.transformOptions(options_).then(transformedOptions_ => {
    return this.http.fetch(url_, transformedOptions_);
```

`other-generators.mjs` runs both clients against the stand-in. Node's
[`--experimental-transform-types`](https://nodejs.org/docs/latest-v22.x/api/typescript.html#typescript-features)
flag loads the TypeScript as the generators wrote it:

```bash
node --experimental-transform-types other-generators.mjs
```

```text output
what the API received             modeled call            raw call
OpenAPI Generator, RawApi.raw()
  request                         GET /v1/parcels/pcl_1   POST /v1/parcels/pcl_1/reroute
  authorization                   Bearer at-1             Bearer at-1
  x-courier-tenant                tnt_7                   tnt_7
NSwag, CourierClient.request()
  request                         GET /v1/parcels/pcl_1   POST /v1/parcels/pcl_1/reroute
  authorization                   Bearer at-1             Bearer at-1
  x-courier-tenant                tnt_7                   tnt_7

OpenAPI Generator, request() with the credential lines left out: ResponseError 401
OpenAPI Generator, methods of the Go APIClient: callAPI, GetConfig, prepareRequest, decode
```

In both clients the tenant header comes from the one hook, a `pre` middleware or
`transformOptions`, and reaches the raw call because the raw method calls that hook.

## Check it worked

Keep the comparison as a test, so a regeneration that changes what a raw call carries fails the
build:

```js title="hatch.test.mjs"
test('a raw call carries the credential, the tenant header and the user agent of a modeled call', async () => {
  const rows = new Map((await parity()).map(([concern, modeled, raw]) => [concern, { modeled, raw }]))
  assert.equal(rows.get('request').raw, 'POST /v1/parcels/pcl_1/reroute')
  assert.equal(rows.get('authorization').modeled, 'Bearer at-1')
  assert.equal(rows.get('x-courier-tenant').modeled, 'tnt_7')
  for (const concern of ['authorization', 'x-courier-tenant', 'user-agent']) {
    assert.equal(rows.get(concern).raw, rows.get(concern).modeled, concern)
  }
})
```

```bash
node --experimental-transform-types --test hatch.test.mjs
```

```text output
1..15
# tests 15
# suites 0
# pass 15
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

`# pass 15` includes a test that pins the tracing gap, so closing it is a deliberate change.

## When it goes wrong

Raw calls start failing with 401 an hour after the process starts, and a 503 is never retried.
The raw method read the base URL and the token out of the client once and called `fetch` itself.
`own-client.mjs` builds that hatch beside `direct()`:

```bash
node own-client.mjs
```

```text output
                        client.direct()   a hatch with its own fetch
a healthy API           200               200
x-courier-tenant        tnt_7             missing
one 503 from the API    200               503
access token expired    200               401
```

It passes its first test, against a healthy API. Send raw requests through the transport the
modeled methods use.

Raw calls are missing from your traces. The tracing feature hooks the pipeline, which `direct()`
skips. Attach tracing at the transport seam, or say in the SDK's documentation that raw calls
carry no trace.

## When not to do this

Do not expose a raw method to avoid modeling an endpoint that is stable. A raw call returns
untyped data, with no check on its path or its body. Model the endpoint and keep the hatch for
what is beta, or shaped too oddly to model.

Do not count on sdkgen's `allow.op` to keep a caller away from an endpoint. The list is a client
option, and `prepare()` stays open when `direct()` is closed. Authorization belongs in the API.

Do not write a raw method that builds its own request, in any generator.

OpenAPI Generator is the better choice when tracing or validation must cover raw calls: one
middleware list runs for generated and raw requests, where sdkgen has two seams to keep in mind.
NSwag is the better choice for a C# and TypeScript SDK, where the raw method is one more
member of the client class.

## Related how-tos

- [Design an SDK constructor that takes configuration once](/howto/sdk-client-constructor-and-configuration)

- [Wrap an SDK transport in a middleware chain](/howto/wrap-an-sdk-transport-with-middleware)

- [Shape an SDK around entities instead of endpoint wrappers](/howto/entity-clients-instead-of-endpoint-wrappers)

- [Expose typed SDK errors callers match without parsing text](/howto/typed-sdk-errors-callers-can-match)

- [Tag SDK calls with session and request ids](/howto/tag-sdk-calls-with-session-and-request-ids)

## Last verified

Verified 2026-11-19 against Node 22.23.5, `@voxgig/create-sdkgen` 0.31.9, `@voxgig/sdkgen` 4.44.3,
OpenAPI Generator 7.27.0, and NSwag 14.8.0. Every output block is what the command preceding it
printed, against a stand-in on 127.0.0.1. sdkgen, OpenAPI Generator, and NSwag each ran once,
through `generate.sh`, and what they wrote is committed. OpenAPI Generator ran on Java 21 and
NSwag on the .NET 10 runtime. The Go program ran once against the same stand-in and is not re-run
on each build, because the generated Go tree is not committed. Octokit was not run. Its design
comes from its README.

[^1]: [RFC 6750](https://www.rfc-editor.org/rfc/rfc6750.html#section-3.1), dated October 2012,
defines `invalid_token` for an access token that is expired, revoked, or malformed. It says the
resource SHOULD respond with 401, and that the client MAY request another access token and retry
the protected resource request. The `secrets` feature takes up that permission once per request.

[^2]: The W3C [Trace Context](https://www.w3.org/TR/trace-context/) Recommendation is dated
November 23, 2021, an editorial update of the one published on February 6, 2020. It describes
`traceparent` as the position of the incoming request in its trace graph, in a portable,
fixed-length format. A request sent without the header has no position to report, which is what
the row marked `DIFFERENT` records.