How to Use OpenAPI to Generate and Maintain an SDK

A step-by-step walkthrough: generate a typed TypeScript client from Paprel's OpenAPI spec, add auth, and keep it in sync with CI — by hand or with a coding agent.

Paprel Engineering Team
25 min read
A structured API specification connects through an adapter to nested code modules

You don't need to hand-write an SDK for an API that publishes an OpenAPI spec. You generate the types and client from the spec, add a thin hand-written layer for auth and conveniences, and regenerate whenever the spec changes.

This guide does that end to end against Paprel's real spec, https://paprel.com/openapi.json. By the end you'll have a typed TypeScript client that authenticates itself, a pagination helper, and a CI job that blocks breaking API changes before they reach your code. The TypeScript commands and snippets below, and the oasdiff check, were run and type-checked against the live spec (OpenAPI 3.1.0, Paprel Public API 1.1.0) on October 29, 2026.

The short version:

Shell
npm i openapi-fetch
npm i -D openapi-typescript typescript
npx openapi-typescript https://paprel.com/openapi.json -o src/paprel/schema.d.ts

Then wrap it with auth middleware (step 4). If you'd rather have a coding agent do the work, skip to Let a coding agent do it for a prompt you can paste.

Why Generate Instead of Hand-Writing

Hand-written clients drift. Endpoints get added, enums grow, fields become required, and the client quietly falls behind. Integrators find out at runtime, usually on a write.

When the spec is the source of truth and the client is generated from it, drift becomes a compile error instead. A generated client gives you:

  • a typed method or path for every operation
  • request and response types that match the contract
  • typed query parameters instead of string bags
  • a diffable artifact you can review when the API changes

You still write a little code by hand. The trick is keeping that code small and outside the generated files.

Step 1: Check the Spec Is Generator-Ready

Generating from a weak spec just automates the weakness. Before you pick a tool, check five things. Here's how Paprel's spec measures up:

CheckWhy it mattersPaprel spec
OpenAPI versionSome generators still handle 3.1 poorly3.1.0
operationId on every operationBecomes method names in class-style SDKs323 of 323 (get_accounts, add_journal, …)
Reusable component schemasGives you named types instead of anonymous blobsBankingJournalFormModel, DocModel, UserErrorModel, …
Security scheme declaredLets tooling know how to authenticatebearerAuth (HTTP bearer, JWT)
Servers listedGives you base URLs per environmenthttps://api-sandbox.paprel.com, https://api.paprel.com

One more thing to look for: headers that are required on every call. Paprel requires x-partner-domain on general API requests, and the spec models it as a shared PartnerDomain header parameter on each operation. That's accurate, but generators will then ask you to pass it on every single call. You'll fix that in step 3.

Step 2: Choose a Generator

ToolOutputRuntimeBest for
openapi-typescript + openapi-fetchTypes only, plus a tiny fetch wrapper~6 kBTypeScript apps that want zero generated runtime code
Hey APITypes plus generated functions and SDK classesSmallTypeScript teams that want named methods (addJournal())
OpenAPI GeneratorFull client in 50+ languagesVaries by languageJava, Go, C#, PHP and other non-TS stacks
KiotaFluent request buildersKiota runtime.NET and multi-language teams standardizing on one style
Hosted (Speakeasy, Fern, Stainless)Polished, published SDKsVariesAPI providers shipping official SDKs in several languages

This guide uses openapi-typescript + openapi-fetch. There's no generated runtime code to review or patch: you generate one .d.ts file, and calls look like the HTTP API itself, client.POST("/v1/accounting/journals", …). That also makes it easy for a coding agent to read and use, since paths and types map one-to-one to the API reference.

Step 3: Generate the Client

Install

Shell
npm i openapi-fetch
npm i -D openapi-typescript typescript

Save the spec and strip the global header

Rather than generating straight from the URL, save a copy of the spec in your repo. That gives you a file to diff in code review, and a place to remove the x-partner-domain parameter so you don't have to pass it on every call. Your middleware will send it instead.

Create scripts/fetch-spec.mjs:

JavaScript
// Download the Paprel spec and drop the x-partner-domain header parameter.
// The client middleware sends that header on every request instead.
import { mkdir, writeFile } from "node:fs/promises";

const res = await fetch(process.env.PAPREL_SPEC_URL ?? "https://paprel.com/openapi.json");
if (!res.ok) throw new Error(`Spec download failed: ${res.status}`);
const spec = await res.json();

const isPartnerDomain = (p) =>
  p.$ref === "#/components/parameters/PartnerDomain" || p.name === "x-partner-domain";

for (const item of Object.values(spec.paths)) {
  for (const op of Object.values(item)) {
    if (Array.isArray(op?.parameters)) op.parameters = op.parameters.filter((p) => !isPartnerDomain(p));
  }
}

await mkdir("openapi", { recursive: true });
await writeFile("openapi/paprel.json", JSON.stringify(spec, null, 2) + "\n");
console.log(`Saved openapi/paprel.json (${spec.info.title} ${spec.info.version})`);

Without this step, every call fails to type-check until you add the header:

Text
Property 'header' is missing in type '{ query: { page: number; }; }' but required in type ...

Add a generate script

In package.json (the snippets use ES modules, so set "type": "module"):

JSON
{
  "type": "module",
  "scripts": {
    "gen:api": "node scripts/fetch-spec.mjs && openapi-typescript openapi/paprel.json -o src/paprel/schema.d.ts"
  }
}

Run it:

Shell
npm run gen:api
Text
Saved openapi/paprel.json (Paprel Public API 1.1.0)
✨ openapi-typescript 7.13.0
🚀 openapi/paprel.json → src/paprel/schema.d.ts [304.5ms]

src/paprel/schema.d.ts now holds every path, operation and schema in the API as TypeScript types: paths, operations and components. Treat it as build output and never edit it by hand. Everything you write goes in the files next to it.

Step 4: Add the Hand-Written Layer

You'll write two small files: a client factory that handles authentication, and a pagination helper.

Auth and partner-domain middleware

Paprel API calls need a short-lived bearer token plus the x-partner-domain header. You get the token by exchanging your client credentials at POST /v1/app-connect/oauth/token (see Authentication: Client Credentials to Access Token). The middleware below caches the token, refreshes it a minute before it expires, and sets both headers on every request.

Create src/paprel/client.ts:

TypeScript
import createClient, { type Middleware } from "openapi-fetch";
import type { components, paths } from "./schema.js";

export type Schemas = components["schemas"];

export interface PaprelConfig {
  baseUrl: string; // https://api-sandbox.paprel.com or https://api.paprel.com
  partnerDomain: string; // sandbox.paprel.com, app.paprel.com, or your registered domain
  clientId: string;
  clientSecret: string;
}

export function createPaprelClient(config: PaprelConfig) {
  const client = createClient<paths>({ baseUrl: config.baseUrl });

  // The token exchange goes through a separate client so it never loops through the auth middleware.
  const tokenClient = createClient<paths>({ baseUrl: config.baseUrl });
  let cached: { token: string; expiresAt: number } | undefined;

  async function getAccessToken(): Promise<string> {
    if (cached && Date.now() < cached.expiresAt) return cached.token;
    const { data, error, response } = await tokenClient.POST("/v1/app-connect/oauth/token", {
      headers: { "x-partner-domain": config.partnerDomain },
      body: { grant_type: "client_credentials", client_id: config.clientId, client_secret: config.clientSecret },
    });
    if (!data) throw new PaprelError(response.status, error);
    // Refresh one minute before the token expires.
    cached = { token: data.access_token, expiresAt: Date.now() + (data.expires_in - 60) * 1000 };
    return cached.token;
  }

  const auth: Middleware = {
    async onRequest({ request }) {
      request.headers.set("authorization", `Bearer ${await getAccessToken()}`);
      request.headers.set("x-partner-domain", config.partnerDomain);
      return request;
    },
  };

  client.use(auth);
  return client;
}

export type PaprelClient = ReturnType<typeof createPaprelClient>;

export class PaprelError extends Error {
  constructor(
    readonly status: number,
    readonly body: unknown,
  ) {
    super(`Paprel API error ${status}: ${JSON.stringify(body)}`);
  }
}

Keep this on your server. The client secret must never reach a browser. For browser-side embeds, use the token backend pattern in Build the embed token backend (BFF).

A pagination helper

Most Paprel lists are page-numbered: page and page_size (up to 200) go in, and total_records comes back next to the rows under data (see Paginating API Lists). An async generator hides the loop. Here it is for invoices, with filters typed straight from the spec.

Create src/paprel/paginate.ts:

TypeScript
import { PaprelError, type PaprelClient } from "./client.js";
import type { paths } from "./schema.js";

type InvoiceFilters = Omit<NonNullable<paths["/v1/invoices"]["get"]["parameters"]["query"]>, "page" | "page_size">;

// Yields every invoice that matches the filters, 200 per request.
export async function* allInvoices(client: PaprelClient, filters: InvoiceFilters = {}) {
  for (let page = 1; ; page++) {
    const { data, error, response } = await client.GET("/v1/invoices", {
      params: { query: { ...filters, page, page_size: 200 } },
    });
    if (!data?.data) throw new PaprelError(response.status, error);
    yield* data.data.docs;
    if (page * 200 >= data.data.total_records) return;
  }
}

The row array's key differs by module (docs, journals, accounts, …), and the generated types tell you which one each list uses.

Step 5: Make Typed Calls

Here's the client in use. This example creates a draft journal, then lists past-due invoices.

TypeScript
import { PaprelError, createPaprelClient } from "./paprel/client.js";
import { allInvoices } from "./paprel/paginate.js";

const paprel = createPaprelClient({
  baseUrl: "https://api-sandbox.paprel.com",
  partnerDomain: "sandbox.paprel.com",
  clientId: process.env.PAPREL_CLIENT_ID!,
  clientSecret: process.env.PAPREL_CLIENT_SECRET!,
});

// Replace the account IDs with two accounts from your sandbox chart of accounts.
const { data, error, response } = await paprel.POST("/v1/accounting/journals", {
  body: {
    currency: "USD",
    date: "2026-10-29",
    description: "SDK smoke test",
    exchange_rate: "1",
    is_manual: true,
    posted: false,
    reference: "SDK-001",
    lines: [
      { account_id: process.env.DEBIT_ACCOUNT_ID!, debit: "100.00", credit: null, description: "Cash", is_tax: false, is_taxable: false },
      { account_id: process.env.CREDIT_ACCOUNT_ID!, debit: null, credit: "100.00", description: "Revenue", is_tax: false, is_taxable: false },
    ],
  },
});

if (!data) throw new PaprelError(response.status, error);
console.log("Created", data.data?.journal.identifier);

for await (const invoice of allInvoices(paprel, { past_due: true })) {
  console.log(invoice.document_number, invoice.document_net_balance);
}

There are no hand-written request or response types anywhere. The body is checked against BankingJournalFormModel, the response is typed as BankingJournalFormResponse, and your editor autocompletes both.

What the compiler now catches

Mistakes that would otherwise surface as a 400 in production now fail at build time:

MistakeResult
Wrong path, e.g. "/v1/accounting/journal"Argument of type '"/v1/accounting/journal"' is not assignable to …
Missing a required field, e.g. no currencyProperty 'currency' is missing in type …
Wrong type, e.g. currency: 840Type 'number' is not assignable to type 'string'.

One limit to know about: inline at the call site, TypeScript does not flag unknown keys, such as a misspelled optional body field (exchange_rte instead of exchange_rate) or a query filter that doesn't exist. The Paprel API ignores unknown query parameters rather than rejecting them, so a typo'd filter silently returns unfiltered results. Declare the value with its generated type and the compiler catches those too:

TypeScript
import type { Schemas } from "./paprel/client.js";
import type { paths } from "./paprel/schema.js";

const body: Schemas["BankingJournalFormModel"] = { /* … */ };
const query: paths["/v1/invoices"]["get"]["parameters"]["query"] = { past_due: true };

The allInvoices helper above already does this for its filters.

Handling errors

Every call returns { data, error, response }, so nothing throws unless you choose to. Paprel's 400 responses come in two shapes, and both are in the generated types:

  • Field validation errors: { "error": { "field_name": ["CODE"] } }
  • Business-rule errors: { "error": { "code", "message", "details?" } }

Branch on the stable code, not the message. The full list is in API Errors and Error Codes.

Step 6: Keep It in Sync

Generation is not a one-time event. The client stays trustworthy only if you regenerate when the API changes, and you notice when a change is breaking.

The loop

  1. npm run gen:api fetches the latest spec and regenerates schema.d.ts.
  2. oasdiff breaking compares the new spec with the copy you committed and reports breaking changes.
  3. tsc --noEmit shows exactly which of your calls the change affects.
  4. You review the spec diff and type errors in a pull request.
  5. If you publish the client as a package, bump its version: breaking change → major, new operations or fields → minor, everything else → patch.

Commit both openapi/paprel.json and src/paprel/schema.d.ts. That way every API change shows up as a readable diff in review, not as a surprise at runtime.

Detecting breaking changes with oasdiff

oasdiff compares two OpenAPI files and classifies each change. Here's what it reports if a field becomes required on journal creation:

Shell
docker run --rm -v "$PWD/openapi:/specs" tufin/oasdiff \
  breaking /specs/paprel.json /specs/next.json --fail-on ERR
Text
error   [request-property-became-required] at /specs/next.json
    in API POST /v1/accounting/journals
        the request property `reference` became required

It exits non-zero, so the check fails CI.

A weekly GitHub Actions job

This workflow regenerates the client every Monday, fails on breaking changes, and otherwise opens a pull request you can review and merge.

YAML
# .github/workflows/paprel-sdk.yml
name: Regenerate Paprel client
on:
  schedule:
    - cron: "0 6 * * 1"
  workflow_dispatch:

permissions:
  contents: write
  pull-requests: write

jobs:
  regenerate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm ci
      - run: cp openapi/paprel.json /tmp/paprel-previous.json
      - run: npm run gen:api
      - name: Fail on breaking API changes
        run: |
          docker run --rm -v /tmp:/base -v "$PWD/openapi:/specs" tufin/oasdiff \
            breaking /base/paprel-previous.json /specs/paprel.json --fail-on ERR
      - run: npx tsc --noEmit
      - uses: peter-evans/create-pull-request@v7
        with:
          branch: chore/regenerate-paprel-client
          title: "Regenerate Paprel API client"
          commit-message: "Regenerate Paprel API client from openapi.json"

When the breaking check fails, the job stops and no PR is opened. Read the oasdiff output and the versioning and deprecation policy, update your calls, then run npm run gen:api locally and open the PR yourself.

Let a Coding Agent Do It

Everything above is mechanical, which makes it a good job for a coding agent such as Claude Code, Cursor or Codex. The spec is machine-readable, the steps are deterministic, and the type checker tells the agent when it got something wrong. Two things help the agent get it right first time: a precise prompt, and a standing instructions file in your repo.

A prompt you can paste

Text
Add a typed Paprel API client to this repo.

Spec: https://paprel.com/openapi.json (OpenAPI 3.1). Guide to follow:
https://paprel.com/blog/embedded-accounting-guides/how-to-use-openapi-to-generate-and-maintain-an-sdk

1. Install openapi-fetch, and openapi-typescript + typescript as dev dependencies.
2. Add scripts/fetch-spec.mjs that downloads the spec to openapi/paprel.json and removes
   the x-partner-domain header parameter (#/components/parameters/PartnerDomain) from
   every operation.
3. Add an npm script "gen:api" that runs it, then generates src/paprel/schema.d.ts.
4. Add src/paprel/client.ts: createPaprelClient({ baseUrl, partnerDomain, clientId,
   clientSecret }) using openapi-fetch middleware. Exchange credentials at
   POST /v1/app-connect/oauth/token, cache the token until 60s before expires_in, and
   set authorization: Bearer <token> and x-partner-domain on every request.
5. Add src/paprel/paginate.ts with an async generator over GET /v1/invoices using
   page and page_size=200, stopping at data.total_records.
6. Use the sandbox: https://api-sandbox.paprel.com with partner domain sandbox.paprel.com.
   Read credentials from PAPREL_CLIENT_ID and PAPREL_CLIENT_SECRET. Never hardcode them.
7. Run npm run gen:api and npx tsc --noEmit, and fix every type error before finishing.
   Do not edit schema.d.ts by hand and do not cast to any to silence errors.

The last two lines matter most. Asking the agent to type-check, and forbidding any casts, keeps it honest: the agent can't claim the client works while it disagrees with the spec.

Standing instructions for agents in your repo

Add this to your AGENTS.md or CLAUDE.md, so any agent that touches the integration later follows the same rules:

Markdown
## Paprel API client

- Generated files: `openapi/paprel.json` and `src/paprel/schema.d.ts`. Never edit them by hand.
  Regenerate with `npm run gen:api`.
- Hand-written code lives in `src/paprel/client.ts` and `src/paprel/paginate.ts`.
- Call the API only through `createPaprelClient()`. It sets the bearer token and
  `x-partner-domain`; don't set those headers yourself.
- Look up request and response shapes in `schema.d.ts` (or https://paprel.com/api-documentation),
  not from memory. If a call doesn't type-check, the spec is right and the code is wrong.
- Use the sandbox (`https://api-sandbox.paprel.com`) for anything you run. Never call
  production from a script or test.
- Run `npx tsc --noEmit` after any change to Paprel calls.

Where agents should look

Point agents at machine-readable sources rather than rendered pages:

A generated SDK is for agents that write code against Paprel. If your agent needs to call Paprel at runtime, to post journals or read reports as part of a conversation, use the Paprel MCP server instead. See Connect an AI Agent to the Paprel MCP Server.

Other Languages

For complete, tested Python, Go, Java and PHP samples, see SDKs and client libraries. The same pattern applies outside TypeScript: save the spec, strip the global header, generate, wrap auth in middleware, and regenerate in CI. Check each generator's OpenAPI 3.1 support before you commit to it, since 3.1 support varies by tool and version.

Shell
# Python
pipx run openapi-python-client generate --path openapi/paprel.json

# Go
# (-response-type-suffix avoids name clashes with spec schemas ending in "Response")
go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@latest \
  -generate types,client -package paprel -response-type-suffix Result \
  openapi/paprel.json > paprel/client.gen.go

# Java, C#, PHP, Ruby and others
npx @openapitools/openapi-generator-cli generate -i openapi/paprel.json -g java -o sdk/java

Each one has a hook for shared headers: an httpx client with event hooks in Python, a RequestEditorFn in Go, and an interceptor in the OpenAPI Generator clients. Put your token and x-partner-domain logic there.

Common Mistakes

  • Editing generated files. Your fix disappears on the next regeneration. Put it in the hand-written layer, or fix it in the spec-prep script.
  • Generating from the live URL in CI without a committed copy. You lose the diff, so API changes reach your code without review.
  • Requesting a token per call. Tokens last expires_in seconds (one hour by default). Cache them.
  • Shipping the client secret to a browser. Token exchange belongs on your server.
  • Casting to any to get past a type error. The type error is the contract telling you something changed. Read it.
  • Skipping the breaking-change check. A regenerated client that compiles can still disagree with how your code used the API yesterday. oasdiff and tsc together catch both sides.
Explore the Paprel API documentation →
Posted by: Paprel Engineering Team · Engineering
Posted on: (Updated: November 20, 2026)
Evaluate Paprel

Build in sandbox, launch with a production trial

Use sandbox for developer testing with no billing. When you are ready for real workflows, start production on a monthly plan with a 14-day free trial.

API-First Delivery
Audit-Ready Controls
Sandbox And Guided Rollout