Skip to content

Seven promises a good SDK keeps

What a TypeScript API client owes the people who call it, with examples and what the well-known SDKs do.

Joshua Jordan
8 min read
  • TypeScript
  • SDK design
  • APIs
The title Seven promises a good SDK keeps, with the MO Data logo above it.
In This Article

The client everyone writes first

An API client is easy to write and hard to write well. The easy version wraps fetch, adds types and ships. It works for the person who wrote it, because that person knows where it's fragile.

I built one of those for an advertising API and ran it in production for months. Then I read how Stripe, AWS, OpenAI and Azure build theirs, and found the same seven promises in all of them. I'd kept about half.

Here's the client almost everyone starts with. Everything below is about what's missing from it.

client.tsCopy
export async function getReport(id: string): Promise<Report> {  const res = await fetch(`${BASE_URL}/reports/${id}`, {    headers: { Authorization: `Bearer ${process.env.API_KEY}` },  });  if (!res.ok) throw new Error(`Request failed: ${res.status}`);  return res.json();}

It has no timeout, so a hung connection hangs the caller. It can't be cancelled. One network blip fails the call. The error is a string. The return type is a promise the server never made. And the key comes from a global, so you can't test it or point it at staging without changing the environment.

The API in the examples

Every example below uses the same small, made-up API. Call it the upstream API. It has reports you can start and fetch, and campaigns you can list. Three endpoints are enough to show every problem.

EndpointWhat it doesWhat makes it awkward
POST /reportsStarts a report job and returns a job ID straight away.It's a write. Sending it twice makes two reports.
GET /reports/{id}Returns the job's status, then the result once it's done.You have to keep asking until it finishes.
GET /campaignsReturns one page of campaigns and a cursor for the next.The full list takes many requests.

Here is what comes back, written as the types an SDK would hand you.

schema.tsCopy
type Report = {  id: string;  status: "queued" | "running" | "done" | "failed";  rows?: number;};
type Page<T> = { data: T[]; nextCursor: string | null };
type ApiErrorBody = { code: string; message: string };

An SDK is the library that sits between your code and those endpoints. It turns HTTP calls into methods, JSON into types, and status codes into errors. A small one is laid out like this.

reports-sdk
  • src
    • client.ts
    • errors.ts
    • pagination.ts
    • polling.ts
    • schema.ts
    • resources
      • campaigns.ts
      • reports.ts
  • test
    • client.test.ts
client.ts holds configuration, auth and the request loop. Each file in resources is one group of endpoints. The other files are the promises below, one each.

The caller only ever sees the methods. client.reports.create, client.reports.get and client.campaigns.list. Everything else in that tree exists so those three calls behave well when the network or the API doesn't.

1. One client, and every call can override it

Configuration lives on one object. Each call can then override it for that call alone.

Copy
const client = new Client({ apiKey, timeoutMs: 30_000, maxRetries: 2 });
await client.reports.get(id);await client.reports.get(id, { timeoutMs: 5_000, signal });

The second argument is the part people skip. Without it, one slow endpoint forces you to raise the timeout for every call. The order of precedence should be boring and the same everywhere. The call beats the client, the client beats the environment, and the environment beats the built-in default.

Which timeout wins?

30,000 msFrom the client option. The most specific setting that exists wins.

Stripe, the OpenAI and Anthropic SDKs, and AWS all take per-request options. AWS documents the same precedence order explicitly. Mine took no per-call options at all.

2. A shape you can guess

There are four common shapes for the same call. Pick one and use it everywhere.

The same call, four ways
await client.reports.create({ type: "daily" });
Used by
Stripe, OpenAI, Anthropic
Finding a method
Type client. and explore
What lands in the bundle
The whole client ships

For a server-side client I'd take the namespace tree. It reads like the API's own docs, and bundle size doesn't matter on a server. If the SDK has to run in a browser, flat functions are worth the plainer look. Cloudflare's SDK ships both from one package.

Whatever you choose, name methods after what the API calls them. If the docs say "list campaigns", the method is campaigns.list. A caller who has read the docs should be able to type the call without opening yours.

3. Types that match what the server sends

A TypeScript type is a claim about data you haven't seen yet. Generate types from the provider's spec when there's a spec you trust. Hand-written types drift, and AWS said as much about its own older SDK.

When you can't trust the spec, validate at runtime. The question is how strictly. Try the three policies against four things a server might do.

What the server sent, and what your client does

Response body

{  "id": "r_81",  "status": "done",  "rows": 120,  "region": "us"}

Result

ok  parsed, "region" passed through

The new field is kept and nothing breaks.

No validation is the calmest until the day a field is renamed. Then the bug shows up three functions away from the cause. Strict validation catches that, and also breaks every caller the day the API adds a harmless field. Lenient checks the fields you rely on and lets the rest through.

Copy
// Going out: strict. Reject a bad request before sending it.const body = requestSchema.strict().parse(params);
// Coming back: check what you rely on, let the rest through.const data = responseSchema.passthrough().parse(json);

The well-known SDKs split on this. Anthropic's doesn't validate responses at all, on purpose. Speakeasy validates both ways so drift fails loudly. Strict out and lenient in gets most of both.

4. Errors that say what happened

The same failure, reported three ways.

A 429 from the server
try {  await client.reports.get(id);} catch (e) {  // Is this a rate limit? A bad ID? A network drop?  if (e.message.includes("429")) await sleep(1000);}

What the caller has to work with

Error: Request failed: 429

The caller parses a message string. There's no request ID to send to support and no way to know how long to wait.

Whichever style you pick, the error has to carry four facts. The HTTP status, the request ID, the response headers, and the parsed error body. Give all errors one base class so a caller can catch anything from this SDK in one line.

errors.tsCopy
export class ApiError extends Error {  constructor(    message: string,    readonly status: number,    readonly requestId: string | undefined,    readonly headers: Headers,    readonly body: unknown,  ) { super(message); }}
export class RateLimitError extends ApiError {}export class ValidationError extends ApiError {}

5. Retries, timeouts and a way to stop

Networks fail. A good client retries on its own, a small number of times, and gets out of the way when told to. The details matter more than they look.

A retry scheduleabout 2.9 s of waiting
attempt 10 ms
attempt 2+423 ms
attempt 3+955 ms
attempt 4+1545 ms

Each wait doubles, then is shortened by a random amount of up to 25 percent.

Twenty clients that failed together, on their second retry

Turn jitter off and look at the bottom strip. Every client comes back at the same instant, which is how a recovering server gets knocked over again. Jitter spreads them out for free.

  • Retry reads by default. Two or three attempts on connection errors, 408, 429 and 5xx.
  • Listen to the server. Honour Retry-After, with a cap. The OpenAI client ignores values over 60 seconds so a bad header can't stall you.
  • Time out every attempt, not only the whole call, and accept an AbortSignal.

Writes need one more thing. If a POST times out you don't know whether it happened. Retrying blind can charge a card twice. An idempotency key fixes that. Generate it once, send it on every attempt, and the server treats the repeats as the same request.

retry.tsWrap linesCopy
const key = options.idempotencyKey ?? crypto.randomUUID();
for (let attempt = 0; attempt <= maxRetries; attempt++) {  const res = await send(request, { headers: { "Idempotency-Key": key } });  if (!shouldRetry(res)) return res;  await sleep(backoff(attempt, res.headers.get("retry-after")));}

This connects to something I've written about before. Retries and timeouts are facts the SDK can work out, so they should be implicit. Anything that costs money or changes data is a decision, so the caller states it explicitly.

6. Lists you can walk

The caller shouldn't manage cursors by hand. They also shouldn't get a helper that silently loads a million rows into memory. Here are ten items behind a page size of three.

Reading a paginated list
for await (const item of client.items.list({ limit: 3 })) {  use(item);}
0 read · 0 requests · 0 held in memory

With the iterator, a caller who needs the first two items pays for one request. With fetch-all they pay for every page before seeing anything. Stripe and the OpenAI SDK return an object that works both ways, and it keeps the cursor so a job can resume.

Copy
const page = await client.campaigns.list({ limit: 3 });page.data;        // the three itemspage.nextCursor;  // save this to resume later
for await (const campaign of client.campaigns.list({ limit: 3 })) {  if (campaign.status === "paused") break; // stops fetching}

Azure's guidelines forbid a method that collects all pages into an array. Stripe offers one and makes you pass a limit.

7. Long jobs you can wait on, or walk away from

Many APIs have operations that take minutes. You start a job, poll it, then fetch the result. Offer the three raw calls, then one helper on top.

Copy
const job = await client.reports.create(params);
const done = await client.reports.waitFor(job.id, {  maxWaitMs: 15 * 60_000,  signal,  onProgress: (s) => log(s.status),});
Waiting on a job
Press start. Times are simulated, with the wait doubling between polls.

Each button is a promise the helper has to keep. It gives up after a maximum wait. It backs off between polls. Cancelling stops the polling and leaves the server-side job alone. And the job ID is something a different process can pick up later.

AWS makes the maximum wait a required argument. Azure asks for a poller that can be serialised and resumed. Also decide what a failed job does. OpenAI's helpers return the object and let you check its status. Throwing is fine too. Pick one and document it.

Three smaller promises

Sign last, and log safely

If requests are signed, sign as the final step before sending, and sign again on every retry. A signature over a timestamp is stale on the second attempt. Redact credentials before a log line is built.

Debug logCopy
-> GET /reports/r_81  attempt 1   authorization: Bearer ****   x-signature: ****<- 200  184 ms  request-id req_7Qm2

Make it testable without a network

Accept a fetch in the constructor. That one option covers tests, proxies and odd runtimes, and it means no mocking library.

client.test.tsCopy
const client = new Client({  apiKey: "test",  fetch: async () => Response.json({ id: "r_81", status: "done" }),});

Leave a way out

The API will ship an endpoint before you do. Expose the low-level request so callers keep auth, retries and errors while calling something you haven't wrapped.

Wrap linesCopy
const beta = await client.request("POST", "/v2/experimental/forecasts", { body });

What to make implicit

Most of this post is a list of things the SDK should decide so the caller doesn't have to. A few things run the other way.

The SDK works it outThe caller states it
Base URL and API versionCredentials
Retries, backoff and timeoutsAnything that spends money or changes data
Idempotency keys on retried writesThe maximum wait on a long job
JSON encoding and the user agentA limit, when collecting a whole list
Fetching the next pageRunning in a browser with a secret key

Score your own

Here is all of it as thirteen checks. Tick what your client does.

Thirteen checks0 of 13

An internal client so far.Next to fix: Explicit options override environment variables. Every call takes per-request options.

When I ran my own client through this I had three, with six more half done. Every gap was on the caller's side of the list. I'd been the only caller, so I'd never felt them.

The short version

  • One client. Every call takes options.
  • One shape, used everywhere, named after the API's own docs.
  • Strict requests, lenient responses.
  • Errors carry status, request ID, headers and body.
  • Retries and timeouts are implicit. Writes and spend are explicit.
  • Lists iterate and keep the cursor.
  • Long jobs can be awaited, cancelled and resumed.

Sources