GoatLabels

Generate a Shipping API Client From OpenAPI 3.1

Updated

How to generate a typed shipping API client from an OpenAPI 3.1 spec, pin and diff the spec, and wrap auth, idempotent retries and errors.

Get free rate quotes Free account. No card needed.

You can get a typed shipping API client without an official SDK by downloading the provider's OpenAPI 3.1 document, running an OpenAPI generator for your language against a pinned copy, and wrapping the result in a thin layer of your own. The generator gives you types for every documented endpoint. Your wrapper owns what a generator cannot know: where the API key lives, which calls carry an idempotency key, and how rate limits and errors are handled. Keep the layers apart and you can regenerate the client without touching business logic.

Why generate a client instead of waiting for an SDK?

Generating a client gets you typed calls now, built from the same document the provider publishes as its reference. An SDK is maintained by someone else; a generated client is maintained by you, and most of that work is re-running one command.

For a team connecting an ERP, WMS or order system to a label provider (the B2B shipping software overview covers the wider picture), the trade looks like this:

Approach What you get What you own
Hand-written REST calls Full control, no build step Every type, field name and typo
Client generated from the spec Types and methods for every documented endpoint The pinned spec file, regeneration and a wrapper
Official SDK, where one exists A maintained package Upgrade timing and the SDK's own abstractions

Field names and enum values come from the spec, so a misspelled property becomes a compile error instead of a 4xx response in production. You also decide when to pick up changes.

How do you pin the OpenAPI spec so the client does not drift?

Pin the spec by committing a downloaded copy to your repository and generating only from that file, never from the live URL. A build that fetches the spec at compile time can produce a different client from the same commit on two different days.

Every OpenAPI document carries an info.version string. Treat it as a label, not a stability promise: the reliable signal is the document itself. A workflow that holds up:

  1. Download the spec into the repo, for example as spec/shipping-api.openapi.json, and commit it.
  2. Generate the client from that file only. Commit the output, or generate it during the build from the committed file. Either way the input is fixed.
  3. On a schedule (weekly is a reasonable default), download the live spec to a temporary file and diff it against the committed copy.
  4. If the diff is empty, stop. If it is not, open a pull request that updates the pinned file, regenerates the client and lets your tests run against it.
  5. Read the diff for removed fields, newly required request properties, renamed enum values and changed response shapes. Those break running code.

A text diff of pretty-printed JSON with sorted keys is enough to start. Also check how your generator treats response enums: a new service name or status is a normal change, and a strict generated enum turns it into a parse failure. Contract tests that validate recorded responses against the pinned spec catch the rest; the post on testing a shipping API in CI with test keys covers that layer.

What belongs in generated code, and what belongs in your wrapper?

Generated code should hold types and request builders, and your wrapper should hold every decision that depends on your environment or your money. Treat generated output as read-only; regeneration erases hand edits.

A simple layout:

  • spec/: the pinned OpenAPI file.
  • generated/: generator output, never edited by hand.
  • shipping-client/: your wrapper, exposing only the operations your system uses, such as quote rates, validate an address, create a draft shipment and purchase a label.

The wrapper is also where your data model meets the API's. Your ERP has sales orders; the spec has shipments. Keep that mapping in one file so a spec change touches one place.

If your generator accepts a custom HTTP function or middleware, put the wrapper's request logic there so every generated method passes through it. If not, wrap each generated method you call. Nothing else in the codebase should call the generated client directly.

How should the wrapper handle auth and API keys?

The wrapper should read the API key and base URL from the environment at startup and send the key as a Bearer token on every request. No other module should know the key exists. An illustrative TypeScript sketch (names and retry counts are examples):

// Illustrative only. Every generated call goes through send().
const BASE_URL = process.env.SHIPPING_API_BASE_URL; // e.g. https://goatlabels.io/api/v1
const API_KEY = process.env.SHIPPING_API_KEY;       // sk_sandbox_ in CI, sk_live_ in production
const sleep = (s: number) => new Promise((r) => setTimeout(r, s * 1000));

export async function send(path: string, init: RequestInit, idempotencyKey?: string) {
  const headers = new Headers(init.headers);
  headers.set("Authorization", "Bearer " + API_KEY);
  if (idempotencyKey) headers.set("Idempotency-Key", idempotencyKey);

  for (let attempt = 1; ; attempt++) {
    try {
      const res = await fetch(BASE_URL + path, { ...init, headers });
      if (res.status !== 429 || attempt === 4) return res;
      await sleep(Number(res.headers.get("Retry-After") ?? "1"));
    } catch (err) {
      if (!idempotencyKey || attempt === 4) throw err; // outcome unknown
      await sleep(attempt * 2);
    }
  }
}

Three key-handling rules belong next to that code:

  • Keep sandbox keys in CI and staging, and the live key only in production. When both share one base URL, the key is the only thing between a sample label and a paid one.
  • Copy a new key into your secret store when it is created. If the provider shows the full secret once, there is no second look.
  • Rotate by adding, then removing. If rotation stops the old secret immediately, a rolling deploy sees failures, so create a second key, deploy it, then revoke the old one. Give reporting jobs a read-only key so an accidental write fails.

How do you make create and purchase calls safe to retry?

Send an Idempotency-Key header built from a stable business identifier, and resend the exact same key and body on every retry. A retry after a timeout then returns the original response instead of buying a second label.

Derive the key from your own records, such as order number, box number and operation. A random value per attempt defeats the point. Serialize the body once and reuse that string, because a rebuilt body with a different timestamp or rounding is a different body.

Example: purchasing a label for order 10482 when the response is lost.

Step (example) What happens
1 Wrapper sends purchase-label with Idempotency-Key: order-10482-box-1-purchase
2 The label is bought, but the response never arrives and the client times out
3 Wrapper waits 2 seconds and resends the same body with the same key
4 The API returns the original response with Idempotent-Replayed: true, so no second label is bought
5 Wrapper stores the tracking number and label from the replayed response

Had step 3 rebuilt the body with a different weight, the API would answer 409 with idempotency_error: a bug to fix, not a condition to retry. See idempotent label purchases from an ERP for key design.

How should the wrapper map rate limits and errors?

Map each status and error type to one decision: wait and retry, or stop and alert. Whether your generator throws typed errors or returns raw responses, the wrapper turns both into a short list callers can act on.

Response Error type on the v1 API Wrapper decision
429 rate_limit_error Wait the Retry-After seconds, then resend the same request
409 idempotency_error Read the message: a reused key with a different body is a bug, so stop and log it; a request still in flight means the first attempt is running, so wait and resend the same key and body, and if it keeps answering in flight, check whether the shipment was created before you retry under a new key
402 plan_quota_error Stop. The Free plan's monthly cap (50 shipments, drafts included, or 100 address validations) is used up until resetAt
403 insufficient_scope Stop. A read-only key attempted a write
403 test_mode_unsupported Stop. A sandbox key called something the sandbox does not cover, such as filing an insurance claim
Timeout or reset none Retry only if the call carried an idempotency key; otherwise check state first

Two rows share 403, so branch on the error type, not the status alone. For pacing, read X-RateLimit-Remaining and X-RateLimit-Reset (unix seconds) and slow down before the window runs out. The limit is per API key, so workers sharing a key share one window; the post on shipping API rate limits in batch integrations covers pacing. Webhook signature checks stay hand-written: a generated client covers calls you make, not calls you receive.

Where GoatLabels fits

GoatLabels serves an OpenAPI 3.1 document at /api/v1/openapi.json and /api/v1/openapi.yaml, no key needed, with a Redoc reference at /developers/api. There is no official SDK: generate a client from the spec as described here, or call REST directly. Auth is a Bearer key, and on both plans the number of calls is uncapped, with a rate limit of 300 requests per minute per API key reported in X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset; on Free, creating shipments stops at 50 per calendar month (UTC, drafts included) and address validation at 100, each with a 402 plan_quota_error, while rate quotes are never counted. See the shipping API for developers page and pricing for the Free and Pro plans.

Know the limits before you build. Idempotency-Key works on create-shipment and purchase-label calls, not on every write. Sandbox keys on the v1 API use the same base URL and the same endpoints against test data: rate quotes are the real prices, a purchase returns a sample label paid from a test balance, and return labels and pickups are simulated, so no carrier is booked and nothing is charged. A sandbox label cannot be shipped, and on Free the address validations a sandbox key makes still count toward the 100 a month. There is also no native ERP connector, so the wrapper you write is the integration.