Back to blog

OpenAPI TypeScript Guide: Generate Typed API Clients

Learn how to generate TypeScript types and a typed client from an OpenAPI spec with OpenAPI TypeScript, with Solana examples for fees and API calls.

By Solana TrackerPublished 13 min read
OpenAPI TypeScript Guide: Generate Typed API Clients

You're building a Solana wallet dashboard or swap bot in TypeScript. You copy a sample JSON payload from an API reference, write a hand-rolled interface for token prices, and ship the feature. Two weeks later, the upstream API renames a field or starts returning null for a newly launched mint, and your trade sizing breaks in production.

Using an OpenAPI TypeScript workflow removes that manual guesswork. Instead of maintaining duplicate interfaces by hand, you generate static TypeScript definitions straight from the API's OpenAPI schema. Adoption across the ecosystem reflects how reliable this pattern is: the openapi-typescript npm package page reports 17,494,750 weekly downloads for converting OpenAPI 3.0 and 3.1 schemas into TypeScript.

Still, compiled types have a hard ceiling in crypto apps. Generated definitions prove your request matches the contract on disk, not that live Solana data is accurate when it arrives. Before any step that moves funds, such as submitting a swap, you need runtime validation alongside those types.

Choose Between openapi-typescript and Full Generators

Before wiring code generation into a Solana codebase, pick the tool that matches how much HTTP boilerplate you want to own.

Tool Output Runtime code Best fit
openapi-typescript TypeScript types only None You write the request calls yourself
OpenAPI Generator (TypeScript Fetch) Full client library Yes, Fetch-based Teams that want generated methods and can review experimental output
openapi-fetch Typed fetch wrapper Small wrapper Typed calls on top of openapi-typescript types

Practical rules for Solana apps

A wallet dashboard or risk monitor calling a handful of Solana endpoints usually works best with openapi-typescript paired with openapi-fetch. Your request surface stays small, your client bundle stays lean, and you keep full control over headers, timeouts, and error handling.

A large internal SDK shared across several trading teams can save initial scaffolding time with OpenAPI Generator (TypeScript Fetch), which outputs ready-made methods like getTokenPrice(tokenAddress) using Mustache templates. Don't ship its output blindly, though. The OpenAPI Generator TypeScript documentation marks this generator as experimental, so you should audit its generated authentication, serialization, and error-handling code before trusting it with live order flows.

Where code generation stops

None of these tools gives you a complete production client out of the box. As IlevenTech's OpenAPI client comparison points out, openapi-typescript is strictly a type-generation layer with zero runtime cost, leaving you to build request retries, authentication flows, multipart handling, and non-2xx error parsing yourself.

A type-safe API call proves your code compiles against a saved spec. It can't detect stale token balances, missing fields, or malformed JSON coming back from a live server.

Think of a Solana integration as three separate layers: generated TypeScript types, a thin HTTP or WebSocket transport, and runtime validation at critical boundaries. Keeping those layers distinct prevents you from confusing compile-time checks with payload safety.

Generate TypeScript Types from an OpenAPI Spec

Modern REST specs make static generation straightforward. According to the Swagger OpenAPI specification history, OpenAPI 3.0 launched on July 26, 2017, followed by OpenAPI 3.1 on February 15, 2021, with tighter JSON Schema alignment, and version 3.1.1 on October 24, 2024.

Here is the end-to-end flow from a YAML contract to typed client code.

A hand-drawn illustration showing the workflow from an OpenAPI YAML specification to a typed TypeScript API client.

You can wire this entire pipeline into a Solana project in an afternoon by following five steps:

  1. Install the generator as a dev dependency: Run npm install -D openapi-typescript. Because the tool only runs at build time to emit static .ts definitions, keeping it out of runtime dependencies adds zero weight to your wallet UI or trading bot.
  2. Store and dereference a valid OpenAPI 3.0 or 3.1 file: Commit your API contract (for example, ./spec.yaml) into the repo, and bundle any external $ref files before running the generator. The most common mistake here is generating against an outdated local copy of the spec, which hides real API changes until your live bot crashes.
  3. Generate one consolidated types file: Run npx openapi-typescript ./spec.yaml -o ./src/api/schema.ts. Writing every path and model to a single generated artifact keeps pull-request diffs readable whenever an endpoint changes.
  4. Import exact schema types where needed: Pull in paths or components inside your feature code, such as type TokenInfo = components['schemas']['TokenInfo'] for Solana token metadata. Never hand-edit schema.ts, because the next generation pass overwrites manual fixes.
  5. Automate regeneration and type checks in CI: Add an npm script that regenerates schema.ts whenever the spec updates, and run tsc --noEmit in your CI pipeline. If an upstream schema change breaks a wallet or pricing call, the build fails before merge.

Verify your setup worked

Run tsc --noEmit locally and open a file that imports components['schemas']['TokenInfo']. Declare a variable with that type and type a dot after the variable name. If your editor autocompletes token fields cleanly and the compiler exits with zero errors, your pipeline is wired correctly.

Call Typed Solana Endpoints Without Guessing Fields

Say you're writing a price lookup helper called getTokenPrice(tokenAddress: string). Instead of guessing the JSON shape, you type its return value directly from paths['/price']['get']['responses']['200']['content']['application/json'], where priceUsd is defined as a number.

Pass the API base URL from an environment variable such as process.env.SOLANA_API_BASE_URL at runtime, and attach your API key in an HTTP request header. Keeping connection details outside the generated file lets you switch between local mocks, staging endpoints, and mainnet without touching your types.

Catch field typos and narrow HTTP statuses

Suppose you mistype response.priceUSD instead of response.priceUsd while computing a token's dollar value. TypeScript flags the casing error in your editor immediately, long before the bot executes a trade.

Before reading the JSON body, narrow on the HTTP response status. Check if (res.status === 404) to handle an unknown mint address gracefully, and only parse the typed success payload when res.ok evaluates to true.

Runtime guard rule: Before priceUsd feeds a swap quote or stop-loss trigger, assert Number.isFinite(data.priceUsd) && data.priceUsd > 0. Static types can't stop a degraded upstream service from returning 0, NaN, or a stringified number.

Separate REST snapshots from live wallet streams

Wallet portfolios need both initial state and continuous updates, so don't force streaming events into your REST schema. Fetch the wallet's starting token balances through a typed OpenAPI REST call on load, then hand live updates to a dedicated WebSocket layer.

The Solana WebSocket RPC documentation outlines subscription methods for live account, slot, and signature activity so your app reacts to balance changes without polling. Separating those two layers keeps your REST request and response types focused and predictable.

To confirm your helper is type-safe, test calling getTokenPrice() without its required tokenAddress argument. If TypeScript rejects the call during compilation rather than failing at runtime in production, your request contract is doing its job.

Estimate Solana Swap Fees Before You Submit

Typed request parameters matter most when real lamports are on the line. According to the Solana core fee documentation, every Solana transaction pays a base fee of 5,000 lamports per signature, plus an optional prioritization fee calculated with this formula:

ceil(compute_unit_price * compute_unit_limit / 1,000,000) lamports

Here, compute_unit_price is expressed in micro-lamports per compute unit (CU). The diagram below shows how the compute limit and unit price combine with the base signature fee.

A diagram illustrating how Solana transaction priority fees are calculated using a balance scale and a formula.

Price (micro-lamports per CU) CU limit Priority fee (lamports) Total (lamports)
1 200,000 1 5,001
10,000 200,000 2,000 7,000
100,000 200,000 20,000 25,000
100,000 1,400,000 140,000 145,000

Check the math row by row

Take the first row with one signature, a 200,000 CU limit, and a price of 1 micro-lamport per CU. Multiplying 1 * 200,000 and dividing by 1,000,000 leaves a fraction of a lamport, and applying ceil rounds up to 1 priority lamport, bringing the total to 5,001 lamports.

Bump the unit price to 10,000 micro-lamports at the same 200,000 CU limit and you get 2,000 priority lamports for 7,000 total lamports. At 100,000 micro-lamports, the priority fee reaches 20,000 lamports and 25,000 total. Leave the limit loose at 1,400,000 CU under that same 100,000 micro-lamport price, and the priority fee jumps sevenfold to 140,000 lamports (145,000 total).

Wire fee parameters into your typed client

Two simple habits keep swap fees predictable in production:

  • Match your CU limit to the swap route: Because the priority fee scales directly with compute_unit_limit, setting an inflated cap overpays on every congested block.
  • Account for extra signers: Every additional signature on a transaction adds another 5,000 base lamports on top of the numbers in the table.
  • Model fee fields as explicit integer parameters: Expose computeUnitPrice and computeUnitLimit directly in your OpenAPI swap request schema so your app calculates total lamports before submission. Keep all lamport values as integers (bigint or integer lamports), never floating-point SOL numbers that invite rounding drift. For end-to-end swap wiring, review this TypeScript guide to Solana swap API requests.

Common Errors and How to Fix Them

When a typed Solana client misbehaves in production, the root cause almost always maps to one of five failure patterns, ordered below from most frequent to least.

Symptom Likely cause Fix
Property missing after regenerating Spec changed and types were not regenerated Regenerate, review the diff, fix compile errors
Field is undefined at runtime Schema marks the field optional or nullable Check before reading and enable noUncheckedIndexedAccess
Code compiles but response is wrong Types cannot check live payloads Add runtime validation at trust boundaries such as swaps
Token amount loses precision Large integers typed as number Read amounts as strings or bigint-compatible values
Rate limit error in production Request quota exceeded Check for 429, read Retry-After, and wait before retrying

Fix contract drift at the right layer

API schemas, response formats, and endpoints may change with or without notice. Even when a spec is syntactically valid, Zaira Labs' OpenAPI generator comparison notes that incomplete or ambiguous contracts still produce misleading TypeScript around nullable properties, discriminated unions, and numeric precision.

Turn on noUncheckedIndexedAccess in tsconfig.json right away so dictionary lookups on token maps or optional wallet records force explicit guards. As explained in the openapi-typescript documentation, runtime-free types add zero bundle weight precisely because they vanish before execution, meaning they can't enforce schema constraints like minimum, maximum, or maxLength against live JSON.

Concrete client-side safeguards

  • Preserve raw token integers: Define large raw token balances as string in the OpenAPI contract and parse them with BigInt(balance.rawAmount) instead of JavaScript number.
  • Type your non-2xx responses: Model error payloads in the spec, narrow on res.status before reading the body, and throw structured errors in your wrapper, such as RateLimitError with retryAfter in seconds when available, DataApiError with a status for HTTP failures, and ValidationError for bad input.
  • Respect HTTP 429 headers: When a request hits quota limits, read res.headers.get('Retry-After') and pause before retrying instead of hammering the endpoint in a tight loop.

Fix order: Update the OpenAPI spec first, regenerate TypeScript types second, and add runtime checks third. Patching symptoms inside consumer components hides contract drift until the next deploy.

Ship Your Typed Solana Client

As your API surface grows across prices, pools, wallets, and risk endpoints, compiler latency becomes a real operational metric. Benchmarks from the openapi-chain performance suite across 25 operations show that an openapi-typescript-shaped client incurred roughly 1.4x the type-check time of an alternative on TypeScript 7, and raising call volume from 40 to 200 invocations made one client's checking time climb roughly fivefold.

Run through this four-point release checklist before shipping a typed Solana integration:

  1. Keep CI gates mandatory: Confirm your OpenAPI spec validator and tsc --noEmit check both pass on every pull request with zero ignored warnings.
  2. Add negative type assertions: Include small compile tests with @ts-expect-error that omit a required query parameter or pass a wrong path type, proving the compiler actively rejects broken calls.
  3. Benchmark realistic call volume: Isolate generated types in their own package, record both cold and incremental tsc builds, and stress-test your highest-volume pattern (such as 200 calls rather than 40) before release.
  4. Verify live contracts and swap checks: Run automated contract tests against deployed endpoints, and confirm your runtime validators execute before any swap transaction signs.

If you'd rather consume a maintained typed client for Solana market data instead of hand-wiring every endpoint, we publish our official Data API SDK on npm as @solana-tracker/data-api. It exposes 70+ endpoints covering tokens, wallets, trades, prices, and risk scores, all indexed and served in milliseconds. Version 0.6.0 is the first release with transfer methods, and our examples run on Node.js 20.18 or newer.

Take one concrete step today: generate TypeScript types for a single read-only endpoint like token pricing, add one @ts-expect-error test, and expand across the rest of your API one endpoint at a time.


Building fast, reliable Solana apps takes more than clean types; it also takes indexed data, live WebSocket streams, and dependable swap routing underneath them. With our unified Data API, low-latency RPC infrastructure, and TypeScript tooling, you can wire tokens, wallet portfolios, risk scores, and swap execution without maintaining custom indexers. Explore the docs and start building on Solana Tracker.

More articles