To generate a typed SMS API client from an OpenAPI spec, point openapi-generator or openapi-typescript at the provider's spec file, review the output, and wrap it with your own timeouts, retries and idempotency keys. The generator gives you types and method signatures. It doesn't give you safe sending behavior, and that gap is where most of the pitfalls live.

We make Ready, so one caution up front. We don't point you at an OpenAPI file for Ready here. Check the API docs to see whether a machine-readable spec is offered. If there isn't one you can rely on, the last sections show how to hand-write a thin client from the documented requests, which for a messaging API is often less work than taming generated code.

What a generator gives you

A spec describes paths, parameters, request bodies and responses. A generator turns that into code, and the code varies a lot by tool.

ToolOutputTypical use
openapi-typescriptType definitions only, no runtimePair with a small fetch wrapper such as openapi-fetch
openapi-generator (typescript-fetch)Full client classes and modelsTeams that want everything generated
openapi-generator (java, kotlin, python, go and others)Client library for that languageBackends outside TypeScript

The first row is the lightest. Types are erased at runtime, so there's nothing to keep in sync except the types themselves. The full generators produce models with validation and serialization code, which means more to read and more to break.

Generating the client

Both tools run from one command. The flags below are the short forms. Replace the file name with whatever spec your provider documents.

# types only
npx openapi-typescript ./provider-openapi.yaml -o ./src/sms-schema.d.ts

# full client, TypeScript with fetch
npx @openapitools/openapi-generator-cli generate \
  -i ./provider-openapi.yaml \
  -g typescript-fetch \
  -o ./src/generated/sms

Pin the generator version in your lockfile, and commit the generated output or generate it in CI. A generator upgrade can rename methods and change model shapes, and you want to see that in a diff, not in production.

With openapi-typescript, calling the API looks like this. The base URL and path are placeholders for a hypothetical provider.

import createClient from "openapi-fetch";
import type { paths } from "./sms-schema";

const sms = createClient<paths>({
  baseUrl: "https://sms.provider.example",
  headers: { "X-API-Key": process.env.SMS_API_KEY ?? "" },
});

const { data, error } = await sms.POST("/v1/messages", {
  body: { to: "+12125550199", body: "Your order #1042 has shipped." },
  params: { header: { "Idempotency-Key": crypto.randomUUID() } },
});

Types catch a misspelled field at compile time. They can't tell you that the key above is wrong for a retry, because a new randomUUID() per call defeats idempotency. That's the first pitfall of many.

Pitfalls that bite on SMS APIs

Generated clients are written for the average API. A messaging API has sharper edges.

  • No timeouts by default. Many generated clients inherit the platform's fetch or HTTP defaults, which may wait forever. Set connect and total timeouts yourself. Our post on HTTP timeouts and connection pooling covers the numbers.
  • No retries, or the wrong ones. A generator doesn't know that a timed-out send is ambiguous. Wrap calls in a retry that reuses one idempotency key per message, as in our post on retries and failure handling.
  • Idempotency header as a normal parameter. If the spec lists Idempotency-Key per operation, the generated method wants a value on every call. Generate it from your message's identity, not at the call site.
  • Closed enums. A response field typed as an enum of three values breaks when the provider adds a fourth. Strict generated deserializers throw, and a delivery state you didn't expect becomes a crash. See our post on the tolerant reader.
  • Required fields that aren't. If a spec marks a response field required and the provider sometimes omits it, strict models fail on valid responses. Prefer optional fields for anything you don't read.
  • oneOf and anyOf responses. Success and error shapes often come out as awkward unions, or as a bare unknown. Check what your tool produces for the error body, because that's the body you'll log most.
  • Number formats. E.164 phone numbers are strings with a pattern, not integers. Some generators turn a long numeric format: int64 into a lossy float in JavaScript.
  • Drift. A spec that was accurate last quarter may not match the API today. A generated client compiles happily against a stale spec.

None of these are reasons to avoid generation. They're a checklist for reviewing what it produced.

Wrap the generated client

Keep generated code in its own folder and never edit it by hand, since the next regeneration overwrites your changes. Put a small wrapper in front that owns the behavior you care about.

type SendInput = { to: string; text: string; key: string };

export async function sendText(input: SendInput, attempts = 4) {
  for (let attempt = 1; attempt <= attempts; attempt++) {
    let wait = 0;
    try {
      const res = await sms.POST("/v1/messages", {
        body: { to: input.to, body: input.text },
        params: { header: { "Idempotency-Key": input.key } },
        signal: AbortSignal.timeout(35_000), // above the api's 30 s request budget
      });
      const status = res.response.status;
      if (![409, 429].includes(status)) return res;
      // 409 idempotency_in_progress: the first try is still running, retry with the same key
      wait = Number(res.response.headers.get("Retry-After")) * 1000 || 0;
    } catch {
      // timeout or network error: the outcome is unknown, retry with the same key
    }
    if (attempt < attempts) {
      await new Promise((r) => setTimeout(r, wait || 250 * 2 ** attempt));
    }
  }
  throw new Error("send failed after retries; check the message before resending");
}

The caller passes the key, so a stored key survives a restart. The wrapper is the only place that knows about retries, which means you can change the policy once. A 503 on a send is not a same-key retry, so the wrapper returns it; see the when to retry table for the new-key retry.

Or write a thin client from the documented requests

For a messaging API with a handful of calls, a hand-written client can be smaller than the generator's config. With Ready you'd write only what the docs describe: POST /v1/messages with to, body and consent_attested, an X-API-Key header, and an Idempotency-Key header. For the response, decode only the fields you use, after reading the messages API reference.

const BASE = "https://api.tryready.com";

export async function sendMessage(to: string, body: string, key: string) {
  const res = await fetch(`${BASE}/v1/messages`, {
    method: "POST",
    headers: {
      "X-API-Key": process.env.READY_API_KEY ?? "",
      "Content-Type": "application/json",
      "Idempotency-Key": key,
    },
    body: JSON.stringify({ to, body, consent_attested: true }),
    signal: AbortSignal.timeout(15_000),
  });
  const payload: unknown = await res.json().catch(() => null);
  return { status: res.status, payload };
}

The return type is unknown on purpose. It stops you from reading a response field the docs don't promise. When you need a field, add a small type guard for that field alone. Our TypeScript client post builds this out into a full wrapper.

Which approach to pick

Generate when the spec is official, current and tested by the provider, and when you call many operations. Hand-write when you call three or four endpoints, when the spec is missing or stale, or when you want a client that does nothing you didn't write. Either way, test the wrapper against a fake. Our post on mocking an SMS API in unit tests shows how, so your retry and key logic gets exercised without sending a real text.

Wrapping up

A generated client is a head start on types, not on behavior. Add the timeout, the retry and the stable idempotency key yourself, review the enums and required fields, and keep the generated folder untouched. If there's no trustworthy spec, a thin client built from the documented requests is a fine answer, and it's easy to replace later.

When you want to try the real API, the quickstart covers the key and a first send.