How-to › Ship an SDK

How to unwrap response envelopes and keep headers and request IDs#

Return the entity or a page from each SDK method, not the data and meta envelope, and keep the status, headers, rate-limit values, and request ID one call away.

Audience
API producer
Level
beginner
Topic
Design SDK ergonomics per language
Languages
TypeScript and Java
Verified

Read first: Name SDK methods the same across resources and languages

Your API wraps every response in { data, meta }, and the SDK method hands that envelope straight back. Every caller writes .data before touching a field, and a list’s next_cursor sits beside the entities it paginates. The request ID that support asks for arrived in a header the method dropped on the floor.

What you get

You will end up with a client whose methods return the entity or a page. The status, headers, and request ID stay one call away on both a default and a raw path. This is for you if you design the return types of an SDK.

Short answer

Return the payload the caller asked for, the entity or a page, and keep the response it came from one call away. In TypeScript, record the status, request ID, and headers in a WeakMap keyed by the returned value, and add a withResponse() method to the returned promise. Put pagination on a page type, never on the entity. Assert in a test that both paths reach the request ID.

You will need

Node 22.18 or later, which runs the .ts files with its built-in type stripping, and a JDK 11 or later for the Java part. An API that wraps its responses in an envelope, here a local stand-in on 127.0.0.1. Method names follow the same verbs across resources.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
AWS SDK v3 $metadataThe output is a command result, not an entity a caller storesEvery output type carries $metadata, and a header it does not map to one of six fields needs a middlewareCallers store the returned value as an entity
OpenAPI Generator withHttpInfoJava and other typed clients generated from a documentA second method per operation, and the default method returns whatever schema the document names, envelope includedYou want the entity by default and can wrap the generated client
Stainless withResponse, as groq-sdk ships itYou write the pattern by hand: callers rarely need headers, and each method keeps one return typeThe default path keeps no request ID, so a caller must choose the raw path before the callSupport needs the request ID from every call, logged or not
Stripe lastResponseEvery returned object should carry its response, invisible to JSON.stringifyA property name taken from every entity, and lists still come back as a list object with dataAn entity may own a field with that name, or lists should be plain arrays

Stripe hangs the response on the object, so the default path keeps everything and the name lastResponse is reserved on every type. Stainless keeps the return type clean and puts the headers behind withResponse(), which a caller has to choose in advance. Stainless has stopped taking signups and creating projects and SDKs and is winding down its hosted products, so its row describes the pattern in groq-sdk, whose README says Stainless generated it. OpenAPI Generator pays for the same split with a second method per operation.

Return the payload and keep the response beside it

Record each response in a WeakMap keyed by the value the method returns. The entity type stays exactly what the API documents, so no field the API adds later can collide with the metadata.

const metaByValue = new WeakMap<object, ResponseMeta>()

/** The response that produced a value this client returned, or undefined. */
export function responseMeta(value: object): ResponseMeta | undefined {
  return metaByValue.get(value)
}

/** A Promise of the payload, plus withResponse() for the payload and the response. */
export type ApiCall<T> = Promise<T> & {
  withResponse(): Promise<{ data: T; meta: ResponseMeta }>
}

function apiCall<T>(result: Promise<{ data: T; meta: ResponseMeta }>): ApiCall<T> {
  const data = result.then((r) => r.data) as ApiCall<T>
  // Mark both rejections handled now; a caller who awaits either still gets the error.
  result.catch(() => {})
  data.catch(() => {})
  data.withResponse = () => result
  return data
}

ApiCall is a real Promise, so Promise.all and assert.rejects accept it. The two catch handlers stop Node from ending the process when a failed call is awaited late. The caller’s own await still throws.

Unwrap in one place, and give a list a page type of its own, so next_cursor never reaches an item.

  return {
    widgets: {
      get: (id: string) => apiCall(call(`/widgets/${segment(id)}`, (e: Envelope<Widget>) => e.data)),
      list: (cursor?: string) =>
        apiCall(
          call(
            `/widgets${cursor === undefined ? '' : `?cursor=${encodeURIComponent(cursor)}`}`,
            (e: Envelope<Widget[]>): Page<Widget> => ({ items: e.data, nextCursor: e.meta.next_cursor ?? null }),
          ),
        ),
    },
  }

Run the demo against the stand-in:

node demo.ts
default  {"id":"w_1","name":"sprocket"}
         responseMeta(widget).requestId = req_1
raw      {"id":"w_1","name":"sprocket"}
         status 200, requestId req_2, rateLimitRemaining 98
list     w_1 w_2, nextCursor c_2, requestId req_3
         keys of an item: id, name
error    widgets API answered 404 (request id req_4)

Check it worked

The tests assert that the request ID is reachable from the default path through responseMeta and from the raw path through withResponse(). They also cover a page, a 404, a plain-text 502 from a proxy, a copied entity, and a call awaited late. One test runs tsc over a file whose @ts-expect-error lines fail the moment widget.data, widget.meta, or widget.next_cursor would compile.

node --test envelope.test.ts
1..8
# tests 8
# suites 0
# pass 8
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 5832.652155

See where three published SDKs put it

The same stand-in serves Stripe, Groq, and DynamoDB shapes, and each client gets its address, key, and HTTP agent in code.

node vendors.ts
stripe 23.2.0
  retrieve       keys id, object, email; non-enumerable lastResponse
                 lastResponse.requestId req_1, statusCode 200
  list           keys object, data, has_more, url; non-enumerable lastResponse
                 lastResponse.requestId req_2
groq-sdk 1.6.0
  default        keys id, object, created, owned_by; non-enumerable none
  withResponse() data.id example-model; response.status 200, x-request-id req_4
  asResponse()   status 200, x-request-id req_5, body unread true
@aws-sdk/client-dynamodb 3.1180.0
  GetItem        keys Item, $metadata; non-enumerable none
                 $metadata {"httpStatusCode":200,"requestId":"req_6","attempts":1,"totalRetryDelay":0}
                 x-example-trace from the middleware: trace_7

stripe-node defines lastResponse as a non-enumerable property, so a logged customer does not show it.1 Its list comes back as Stripe’s own list object, so callers of a list do write .data. The groq-sdk default object carries no request ID at all. AWS keeps the request ID in $metadata, and the stand-in’s x-example-trace header reached the caller through a deserialize-step middleware added with priority: 'high'.

Wrap the generated Java client

OpenAPI Generator returns whatever schema the document names. Generated from an openapi.json whose 200 response is WidgetEnvelope, its getWidget returns the envelope, and getWidgetWithHttpInfo adds the status and headers.

  public WidgetEnvelope getWidget(@javax.annotation.Nonnull String id, Map<String, String> headers) throws ApiException {
    ApiResponse<WidgetEnvelope> localVarResponse = getWidgetWithHttpInfo(id, headers);
    return localVarResponse.getData();
  }

A facade of two methods unwraps it without touching the generated code:

  public Widget get(String id) throws ApiException {
    return api.getWidget(id).getData();
  }

  public ApiResponse<Widget> getWithHttpInfo(String id) throws ApiException {
    ApiResponse<com.example.widgets.model.WidgetEnvelope> raw = api.getWidgetWithHttpInfo(id);
    return new ApiResponse<>(raw.getStatusCode(), raw.getHeaders(), raw.getData().getData());
  }
node java-demo.ts
generated getWidget                 returns WidgetEnvelope, name via getData().getName(): sprocket
                                    request id via getMeta().getRequestId(): req_1
generated getWidgetWithHttpInfo     status 200, x-request-id req_2, x-ratelimit-remaining 98
UnwrappedWidgets.get                returns Widget, name via getName(): sprocket
UnwrappedWidgets.getWithHttpInfo    returns ApiResponse<Widget>, status 200, x-request-id req_4

This facade keeps the request ID on the WithHttpInfo path only, which is the cost of this row: a caller who needs the ID has to pick that method before the call.

When it goes wrong

Callers write .data everywhere, or an item carries next_cursor. The method returned the envelope, or flattened meta into each entity. pitfall.ts shows both against the same stand-in:

node pitfall.ts
envelope   caller writes envelope.data.name: sprocket
           top-level keys: data, meta; x-ratelimit-remaining kept: false
flattened  keys of one widget: id, name, request_id, next_cursor
unwrapped  keys of one widget: id, name; page keys: items, nextCursor

Unwrap in the client, and move pagination to a page type.

The request ID is undefined on a value you built yourself. responseMeta only knows the objects the client returned, and a spread such as { ...widget } makes a separate object. Keep the original, or take withResponse() when you plan to copy.

A request goes to the wrong path once the base URL holds /v1. new URL('/widgets', base) drops the base path, so client.ts appends the path to the base URL instead.

When not to do this

Do not unwrap an envelope that carries data the caller needs on every call. A batch endpoint that returns per-item errors in meta belongs in a result type that names them, not in a side table.

Do not hide the response behind a WeakMap if callers serialize and rebuild values before they read the request ID. A queue worker that receives a copy gets nothing back from responseMeta. Put the ID in your own log line at call time instead.

Do not add a raw method per operation by hand in a generated SDK. OpenAPI Generator already emits one, the WithHttpInfo method, and a facade over the generated client is less to maintain than edits a regeneration overwrites.

Last verified

Verified 2026-11-30 against Node 22.23.5, OpenJDK 21.0.13, TypeScript 6.0.3, stripe 23.2.0, groq-sdk 1.6.0, @aws-sdk/client-dynamodb 3.1180.0, OpenAPI Generator 7.28.0, and Jackson 2.21.8. Every output block is what the command preceding it printed. The three published SDKs ran against a local stand-in that copies each API’s envelope and request-ID header, not against Stripe, Groq, or AWS. The Stainless generator itself was not run; its row is read from groq-sdk.

Footnotes

  1. The property is set with Object.defineProperty, enumerable: false, and writable: false in the request sender, so JSON.stringify and console.log pass over it. The same file copies four headers onto the raw response as plain properties, requestId, stripeAccount, apiVersion, and idempotencyKey, which is how lastResponse.requestId exists without a header lookup. ↩︎ 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.