A developer reviewing an OpenAPI spec on a laptop, with code snippets and API documentation visible. Alt: openapi spec preparation for axios typescript generator.

How to Build an openapi to axios typescript client generator for Strongly-Typed API Clients

Ever stared at a massive OpenAPI spec and thought, “How am I supposed to turn this into a clean Axios wrapper without spending days writing boilerplate?”

You’re not alone. Most devs hit that wall when they need a type‑safe TypeScript client that talks to their APIs the way Axios does—fast, predictable, and with proper IntelliSense.

That’s where an openapi to axios typescript client generator swoops in. It reads the spec, spits out typed request functions, and wires up Axios instances so you can call `getUser()` instead of manually crafting URLs and headers.

Imagine you’re building a SaaS dashboard. Yesterday you added a new “billing” endpoint, updated the OpenAPI doc, and now you need to expose it in your React components. With a generator, you run a single command, get a `billingApi.ts` file with fully typed methods, drop it into your repo, and you’re back to building UI—not debugging mismatched request bodies.

Real‑world example: a fintech startup integrated a third‑party payments API. The spec had 120 paths. Manually writing Axios calls took weeks and introduced subtle bugs (wrong query param names). After running the generator, they reduced integration time to two days and cut runtime errors by 80 % because every request now complied with the generated TypeScript interfaces.

Here’s a quick checklist to get you started:

  • Install the generator (npm `openapi-axios-gen` or use SwapCode’s online tool).
  • Point it at your `openapi.yaml` or `json`.
  • Choose an output folder, run the command, and review the generated `apiClient.ts`.
  • Plug the client into your existing Axios instance (add base URL, interceptors, auth).
  • Run your test suite; you’ll see type errors where your code deviates from the spec.

If you want a deeper walk‑through, check out How to Generate API Client from OpenAPI in TypeScript. It walks you through configuration options, custom templates, and how to tweak the generated code for your project’s conventions.

And because generating code is only half the battle, you’ll also need a way to keep your API contracts in sync. Tools like Swagger UI or Postman can validate the live spec, while CI pipelines can re‑run the generator on every merge. That way your TypeScript client never drifts away from the source of truth.

Finally, if you’re looking to streamline the whole workflow with AI‑powered automation, consider exploring Assistaix – AI Business Automation. It can help you orchestrate code generation, testing, and deployment steps, saving precious development time.

TL;DR

The openapi to axios typescript client generator instantly transforms your OpenAPI spec into a fully typed Axios wrapper, slashing boilerplate and preventing runtime mismatches.

Just right away run the tool, plug the generated apiClient.ts into your project, and enjoy type‑safe calls that keep your front‑end and back‑end perfectly in sync.

Step 1: Prepare your OpenAPI spec and project prerequisites

Before you even think about running the openapi to axios typescript client generator, you need a clean, version‑controlled OpenAPI document. If your spec lives in a messy mix of YAML files, broken $ref pointers, or undocumented endpoints, the generator will spit out code that looks like it was written by a robot on a coffee break. Take a moment to open the spec in Swagger UI or your favorite editor and verify that every path, schema, and parameter has a clear description.

First thing’s first: make sure you’re using a supported OpenAPI version (3.0.x or 3.1.x). Older 2.0 definitions can still work, but you’ll end up fighting conversion quirks later. If you’re on 2.0, run a quick upgrade script or use an online converter—just keep the resulting file tidy.

Next, pull the spec into your repo and lock it to a specific branch or tag. This way, when the generator runs in CI, you always know which contract you’re targeting. A good practice is to add a openapi.yaml file to the src/api folder and reference it in your package.json scripts.

Now, let’s talk dependencies. The generator expects an existing Axios instance, so you should have axios installed (>=0.27). If you’re already using axios for other services, great—just export the instance from a central httpClient.ts file. If not, run npm i axios and set up a basic instance with a base URL and any interceptors you need (auth tokens, logging, retry logic).

Because the output will be TypeScript, make sure your project is set up for strict typing. Enable "strict": true in your tsconfig.json and add "esModuleInterop": true if you’re mixing CommonJS and ES modules. This prevents the generator from creating any “any” types that would defeat the purpose of type safety.

Feeling a bit overwhelmed? That’s normal. A quick checklist can save you a lot of back‑and‑forth:

  • Validate the OpenAPI file with swagger-cli validate or an online validator.
  • Confirm all $ref links resolve correctly.
  • Pin the spec version in Git.
  • Install axios and expose a shared instance.
  • Turn on strict TypeScript mode.

Once you’ve crossed those boxes, you’re ready to run the generator. If you want a step‑by‑step walkthrough of the exact command line flags and template tweaks, check out How to Generate API Client from OpenAPI in TypeScript: Step‑by‑Step Guide. It walks you through everything from output folder selection to customizing request‑interceptor hooks.

And if you’re looking to automate the whole pipeline—pulling the spec from a remote repo, regenerating the client, running tests, and even deploying—you might want to explore Assistaix – AI Business Automation. It can orchestrate those steps and give you a nice dashboard that shows exactly where a spec change broke the build.

Finally, for teams that need strategic oversight on API design, consider partnering with a tech‑strategy firm like CTO Input. They can help you define versioning policies, governance workflows, and even run regular audits so your OpenAPI spec stays the single source of truth.

With a solid spec, a ready‑made Axios instance, and strict TypeScript settings, the generator becomes a joy to run rather than a headache to fix. Run it once, review the generated apiClient.ts, and you’ll see how many lines of boilerplate vanished.

Next up, we’ll dive into customizing the generated code—adding custom headers, handling pagination, and tweaking error handling to match your app’s conventions.

A developer reviewing an OpenAPI spec on a laptop, with code snippets and API documentation visible. Alt: openapi spec preparation for axios typescript generator.

Step 2: Install and configure an openapi to axios typescript client generator

Now that your spec is clean and you’ve got a custom axiosInstance ready, it’s time to bring the generator into the picture. Think of it as the “auto‑pilot” that writes the repetitive request code for you, while you stay in control of auth, retries, and logging.

Install the generator

First, add the generator as a dev‑dependency. Most teams use the official OpenAPI Generator CLI because it supports the typescript-axios template out of the box:

npm install --save-dev @openapitools/openapi-generator-cli

If you prefer not to pollute your project’s node_modules, you can run the CLI from Docker – the docs show a simple openapitools/openapi-generator-cli image that works on any OS.OpenAPI Generator documentation

Configure the output

Create a tiny JSON config (or pass flags) that tells the generator where to dump the files and which options you care about. A common setup looks like this:

{
  "npmName": "api-client",
  "supportsES6": true,
  "withSeparateModelsAndApi": true,
  "apiPackage": "api",
  "modelPackage": "models"
}

Save it as generator-config.json in the root of your repo. Then add a script to package.json:

"generate:client": "openapi-generator-cli generate -i ./openapi.yaml -g typescript-axios -o ./src/api-client [email protected]"

Running npm run generate:client will spin up the generator, read openapi.yaml, and spit out a tidy apiClient.ts plus model interfaces.

Want proof it works in a real app? Arnaud Cortisse shows a full Docker‑based workflow that pulls the OpenAPI JSON from a NestJS server and drops the generated client straight into a React app – and the whole thing reruns on every pull request so the TypeScript types never drift.Cortisse’s NestJS client generation guide

Hook the generated client into your Axios instance

Open the freshly generated apiClient.ts. By default it imports Axios directly, but you can swap that line for your custom instance:

import axios from "../axiosInstance";

Because the file is just TypeScript, the change is safe and won’t break the generated types. Now every request method – getUser(), createInvoice(), etc. – automatically uses your interceptors, base URL, and error handling logic.

Tip: keep the import path relative to the generated folder so you can move the whole src/api-client directory without hunting down import statements.

Run, verify, and automate

Give the client a quick spin by calling one of the generated functions from a test or a dev page. If the TypeScript compiler throws a mismatch, you’ve caught a spec‑code drift before it hits production.

Once you’re confident, lock the script into your CI pipeline. Every time openapi.yaml changes, the pipeline runs npm run generate:client, commits the updated files (or fails the build), and you’re guaranteed that the front‑end always speaks the same language as the back‑end.

And because the generator is just another npm script, you can add a --skip-validate-spec flag if you’ve already run a separate validation step – that saves a couple of seconds in large monorepos.

Need a visual walkthrough? The video below walks through the exact commands we just described, from installation to CI integration.

After the video, spin up your own generator, replace the Axios import, and watch how quickly you go from a raw OpenAPI spec to a fully typed client that feels native to your codebase. The next step will cover how to fine‑tune the generated code for your project’s conventions.

Step 3: Generate the client and integrate with Axios (video walkthrough)

Alright, you’ve just run the npm run generate:client command and a whole bunch of files landed in src/api-client. The moment those files appear, you’re basically holding a typed bridge between your front‑end and the API.

Inspect the output and swap the Axios import

Open apiClient.ts. By default the generator pulls in Axios directly from the node_modules copy. That works, but you probably already have a custom axiosInstance that adds auth headers, retry logic, and request logging. Replace the line

import axios from 'axios';

with

import axios from '../axiosInstance';

Because the file is plain TypeScript, the change won’t break any of the generated types. Now every call – getUser(), createInvoice(), etc. – automatically inherits your interceptors.

Set the base URL at runtime

One snag developers often hit is the hard‑coded BASE_PATH that the generator injects. A quick fix is to pass the base URL via the generated configuration class. For example:

import { Configuration, UsersApi } from './apiClient';
const config = new Configuration({ basePath: process.env.API_URL });
export const usersApi = new UsersApi(config);

If you prefer not to touch the generated code, you can also override the base path with the --additional-properties=basePath=${API_URL} flag when you run the CLI. The Stack Overflow discussion confirms both approaches work (see the answer that shows using Configuration or the basePath flag).

Run a quick sanity check

Spin up a dev page or a simple Jest test that calls usersApi.getUser({ id: 1 }). If TypeScript compiles cleanly and the network request hits the expected endpoint, you know the wiring is solid. If you see a mismatch, the compiler will point you right to the offending interface – that’s the whole point of generating a typed client.

In a recent fintech project, the team added a new /payments/preview endpoint. After regenerating, they ran a one‑liner test that asserted the response shape matched the PaymentPreview interface. The test caught a missing “currency” field within minutes, something that would have slipped into production otherwise.

Automate the whole flow

Now that the manual steps are clear, lock them into your npm scripts. A typical package.json snippet might look like:

"scripts": {
  "generate:client": "openapi-generator-cli generate -i ./openapi.yaml -g typescript-axios -o ./src/api-client --additional-properties=supportsES6=true",
  "postgenerate": "node scripts/patch-axios-import.js"
}

The postgenerate script can program‑matically replace the Axios import so you never forget that step. Then add the script to your CI pipeline – every pull request that touches openapi.yaml triggers a fresh client, runs npm run postgenerate, and fails the build if TypeScript errors appear.

Real‑world tip: keep configuration separate

Store the base URL and any auth tokens in a dedicated config.ts file that both your custom Axios instance and the generated client import. This prevents duplicated environment reads and makes it easy to switch between staging and production.

Need a visual refresher? The video below walks through the exact steps we just covered, from generating the files to swapping the import and testing a call.

And if you ever wonder how to generate TypeScript snippets on the fly, check out the TypeScript Code Generator – it’s a handy side‑tool when you need a quick type for an ad‑hoc payload.

Finally, remember that a solid API client is only as good as the feedback loop you create. Pair the generation step with a lightweight monitoring tool that alerts you when a generated method starts returning a 5xx – that way you catch contract breaks before users do. For teams that care about developer experience, benchmarking those cycles can be eye‑opening. That’s why many engineering groups turn to Benchmarcx to measure how quickly new endpoints become usable.

Step 4: Compare generator options and choose the right one

Now that you’ve got a clean spec and a custom Axios instance, the next puzzle is picking the right openapi to axios typescript client generator. There isn’t a one‑size‑fits‑all answer, but a quick side‑by‑side look can save you hours of back‑and‑forth.

What are the popular flavors?

In the OpenAPI Generator ecosystem you’ll mainly bump into three TypeScript‑oriented templates:

  • typescript-axios – spits out Axios‑based calls straight out of the box.
  • typescript-fetch – uses the native fetch API, which Node 18 now supports.
  • openapi-fetch – a lightweight wrapper that auto‑detects the spec and leans heavily on fetch.

All three claim to honor the spec, but their real‑world stability differs. A recent Stack Overflow discussion notes that teams have found typescript-axios and typescript-fetch to be “very stable and very similar,” while openapi-fetch is newer and still gaining traction.

Decision matrix

Generator Maturity Key pros Typical cons
typescript-axios High (long‑time default) Built‑in error handling, Axios interceptors, familiar API Throws on non‑2xx responses (you must catch)
typescript-fetch Medium (stable but newer) Leverages native fetch, no extra Axios dependency Doesn’t raise errors automatically – you must inspect ok flag
openapi-fetch Low (emerging) Very small bundle, auto‑detects spec Limited feature set (no anyOf support yet)

Take a moment to map these points to your project’s constraints. Do you already depend on Axios for logging and retry logic? Then the first row probably feels like home. If you’re building a server‑side‑only service on Node 18 and want to avoid an extra package, the fetch‑based option might be leaner.

Real‑world checklists

Here’s a quick “try‑out” list you can run in a fresh branch:

  1. Generate a tiny client with each template (use –additional-properties=supportsES6=true).
  2. Swap the import to your custom axiosInstance for the Axios version, or to a simple global.fetch wrapper for fetch.
  3. Write a one‑liner test that calls an endpoint returning a 404. Observe whether the promise rejects (Axios) or resolves with ok===false (fetch).
  4. Measure bundle size with webpack-bundle-analyzer. You’ll often see a ~10 KB difference between Axios and fetch templates.
  5. Check the generated TypeScript interfaces for complex schemas (e.g., oneOf or anyOf). The Stack Overflow thread mentions a hiccup with anyOf in the fetch generator.

If the Axios version passes all three steps without extra plumbing, it’s probably the safest bet. If you love the idea of a sub‑10 KB client and can tolerate a manual if (!response.ok) guard, give the fetch template a spin.

Expert tip: combine the best of both worlds

Many teams generate the client with typescript-axios for its robust error model, then wrap the generated calls in a thin utility that normalizes errors to a shape your UI expects. That way you keep the rich Axios interceptor ecosystem while still having a single error handling strategy.

Still on the fence? Our step‑by‑step guide walks through configuring the generator, tweaking the output, and wiring it into a real React dashboard. Follow it, run the comparison table above, and you’ll land on the option that matches your team’s rhythm.

Bottom line: the right generator is the one that aligns with your existing stack, your team’s comfort zone, and the complexity of your OpenAPI spec. Run the quick checklist, compare bundle sizes, and let the data guide you. When you’ve made the choice, lock the generator version in package.json and automate the run in CI – you’ll never have to wonder again which tool to trust.

Step 5: Customize TypeScript types, request/response mapping, and advanced patterns

Now that the client is wired up, the real magic begins when you start shaping the generated types to match how your UI actually talks to the API.

The generator gives you a bunch of plain interfaces like UserDto or CreateInvoiceRequest, but most teams soon realize they need a thin layer that converts UI‑friendly objects into the exact contract the server expects.

That’s where request/response mapping comes in – think of it as a translator sitting between your React form values and the OpenAPI‑defined payload.

Here’s a quick pattern: create a folder src/api-mappers and for each generated model write a function to that picks, renames, or formats fields before you hand the object to the Axios call.

Because the mapper returns the generated interface, TypeScript still gives you IntelliSense, but you’ve isolated all the “quirky” business rules in one place.

Want to avoid writing a mapper for every single endpoint? You can lean on utility types like Partial or Pick to compose reusable adapters. For example, a generic applyDefaults(obj: Partial, defaults: T): T lets you supply only the fields a form collects while the rest are filled from a constant config.

Now, let’s talk about customizing the generated types themselves. By default the OpenAPI Generator spits out interfaces, but some developers prefer classes because they can embed helper methods.

The community workaround lives on Stack Overflow – you can drop a custom Mustache template that swaps the interface keyword for class and the generator will emit classes that still satisfy the same shape. Stack Overflow discussion on generating classes instead of interfaces walks through the exact steps.

Keep in mind you’ll need to maintain that template whenever the generator updates, so schedule a quarterly check‑in to pull the latest defaults and re‑apply your overrides.

If you’re not ready to switch to classes, you can augment the interfaces with declaration merging. Create a *.d.ts file next to the generated model and add a method signature – TypeScript will merge it into the existing type without touching the generated code.

Advanced pattern: response transformation. The generator creates a Configuration class where you can plug a response interceptor. Inside the interceptor, map the raw JSON into a richer domain model, strip out server‑only fields, or even convert timestamps into Date objects. This keeps your UI components clean – they always receive the shape they expect.

A practical tip is to wrap the generated API classes in a thin service layer. The service exposes methods like getUserProfile() that internally calls usersApi.getUser() and then runs the response mapper. That way you get a single place to handle pagination, error unwrapping, and caching. If you need to spin up quick unit tests for those mapper functions, the Free AI Test Code Generator can scaffold Jest tests in seconds.

Don’t forget error mapping. Axios throws on non‑2xx, but the generated error type is just any. Create a custom error transformer that reads the OpenAPI‑defined error schema (often an ErrorResponse model) and throws a typed ApiError so downstream code can catch instanceof ApiError and react accordingly.

Finally, automate the whole thing. Add a post‑generation script that runs prettier on the output, copies your mapper stubs into the right folder, and updates an index file so imports stay tidy. Commit the script alongside your generator-config.json so new team members get the same polished setup out of the box.

A developer reviewing TypeScript mapper functions in VS Code, showing before‑and‑after code snippets of an API request transformation. Alt: openapi to axios typescript client generator custom types mapping.

Pulling these pieces together gives you a client that feels native to your codebase: generated types stay in sync with the spec, custom mappers handle the messy UI‑to‑API translation, and a small service layer gives you consistent error handling and response shaping. That’s the sweet spot most senior engineers aim for when they move beyond the “just‑generated” code.

Step 6: Add CI, tests, publishing, and maintenance workflows

Now that you have a clean, typed client and a few mapper helpers, the real safety net appears when you bake everything into CI. Picture a teammate updating openapi.yaml at midnight; without automation you’d have to re‑run the generator, format, and manually check types. A CI job makes that invisible.

Step 1 – Wire the generator into your build

Add a npm script that runs the generator in check‑only mode. The CLI’s --dry-run flag validates the spec without touching your source tree. In package.json you might have:

"gen:check": "openapi-generator-cli generate -i openapi.yaml -g typescript-axios -o /dev/null --dry-run"

Then create a second script that actually writes to src/api-client. CI runs the check script first; if it passes, the write script updates the folder.

Step 2 – Run tests against the generated code

Write a tiny Jest suite that imports the generated client and hits a mock server (e.g., msw) to verify request shape. Place the suite under __tests__/generated and run it as part of npm test.

Tip: generate those tests automatically. A small Node script can read operationIds from the spec and emit a skeleton test for each endpoint, so coverage never slips when new paths appear.

Step 3 – Publish the client as a versioned package

If several front‑ends need the same client, publish it as a private npm package. Add a tiny package.json inside src/api-client, set the version to match the API contract, and run npm publish from CI after a successful generation.

Step 4 – Keep the client in sync with the spec

Add a “spec‑changed” guard in your CI config. The job runs git diff --name-only and, if openapi.yaml appears, triggers generation, prettier formatting, and publishing. If the spec didn’t change, skip the heavy steps.

Store a hash of the last generated output (e.g., .client‑hash). After regeneration compute the new hash; if it matches, CI can safely skip publishing because nothing really changed.

You can also cache the generated client as an artifact between jobs so downstream stages don’t need to regenerate it. This speeds up the pipeline and guarantees every step uses the exact same code.

Step 5 – Ongoing maintenance chores

Keep the generator version pinned in package.json and create a quarterly “upgrade‑and‑test” ticket. When you bump the CLI, run the full CI locally first to catch breaking template changes.

Add a short README in src/api-client that lists the three‑step flow: (1) run npm run gen:check locally, (2) run npm test to validate contracts, (3) let CI publish a new version. New hires will follow it without guessing.

Consider adding a simple CI health check that runs npm run gen:check on a nightly schedule. If the generator ever fails because the spec is invalid, the job will alert the team early, preventing broken builds from reaching production.

So what does this give you? A single source of truth in version control, regenerated on every spec change, verified by tests, and delivered as a tidy npm package. In short, you’ve turned a one‑off generator into a maintainable piece of your pipeline.

Conclusion

By now you’ve seen how an openapi to axios typescript client generator can turn a bulky spec into clean, type‑safe code you actually enjoy working with.

Does it feel like magic when a single npm script spits out dozens of ready‑to‑call functions? That’s the point – we’re swapping endless hand‑crafted requests for a repeatable, version‑controlled process.

Remember the three‑step loop we built: validate the spec, run the generator, and lock the output in CI. If any piece breaks, the pipeline flags it before it reaches production, so you spend more time building features and less time hunting mismatched payloads.

One practical tip: treat the generated client as a library, not a one‑off artifact. Add a short README, version it alongside your API contract, and let new teammates run npm run gen:check to stay in sync.

So, what’s next for you? Grab your OpenAPI file, give the generator a spin, and watch the boilerplate disappear. When the client lives in source control, you’ve future‑proofed your front‑end against drift.

Happy coding – and let the generator do the heavy lifting while you focus on the product.

If you hit any hiccups, check your generator version and run the dry‑run flag first – it saves you from unexpected surprises down the line.

FAQ

What is an openapi to axios typescript client generator and why should I use it?

In plain terms, it’s a tool that reads your OpenAPI definition and spits out ready‑made TypeScript functions that call Axios under the hood. The big win is you get type‑safe request signatures without hand‑crafting every URL, header, or payload. That means fewer runtime bugs, instant IntelliSense, and a lot more time to focus on business logic instead of boilerplate.

How does the generator keep my client in sync when the API changes?

The generator can be wired into your CI pipeline so that any commit touching openapi.yaml automatically re‑runs the build step. If the spec diverges, the script either overwrites the client folder or fails the build, forcing you to address the mismatch before code lands in production. Pair that with a npm run gen:check command locally, and you have a repeatable, version‑controlled loop.

Do I need to install additional dependencies besides Axios?

Usually you only need the generator CLI (for example @openapitools/openapi-generator-cli) as a dev dependency. The generated code imports Axios, so as long as you already have Axios in your project you’re good to go. If you prefer a custom Axios instance with auth interceptors, just replace the import line in the generated file – the types stay untouched.

Can I customize the output folder or naming conventions?

Absolutely. The CLI accepts an -o flag to point at any directory you like, and you can feed a JSON config with npmName, modelPackage, or apiPackage values to control where models and API classes land. Most teams create a dedicated src/api-client folder, version it, and add a tiny README that explains how to run the generator and where to find the generated typings.

What if my OpenAPI spec uses features that the generator doesn’t support?

When you hit an unsupported keyword (like a complex anyOf or a vendor‑extension), the generator will emit a warning or error during the dry‑run phase. The usual workaround is to simplify the schema in the spec – for example, replace anyOf with a union of concrete objects – or to extend the Mustache templates yourself. Keeping the spec clean and version‑controlled helps you spot those edge cases early.

How do I test that the generated client actually works against my backend?

Spin up a lightweight mock server with msw or json-server, then write a Jest test that calls one of the generated functions. Because the functions are fully typed, the TypeScript compiler will flag any mismatched request shapes before the test even runs. A quick sanity check – call getUser({ id: 1 }) and assert the response matches the User interface – gives you confidence that the contract is solid.

Is it safe to commit the generated code to my repository?

Yes, and most teams do. Treat the generated client as a library that lives alongside your source code. Commit the output folder, version it with the same tag as your API contract, and let new contributors run npm install to get the exact same typings. If you prefer a slimmer repo, you can generate on‑the‑fly in CI and publish the client as a private npm package, but the core idea is the same: a single source of truth that never drifts.

Similar Posts