OpenAPI Client Axios
openapi-client-axios is a JavaScript and TypeScript library designed to create dynamic API clients from OpenAPI v3 definitions at runtime. It leverages the popular axios library for HTTP requests, offering a powerful and flexible alternative to code generation for API consumption. The current stable version is 7.9.0. The library features automatic TypeScript type generation for API operations, full IntelliSense support, and a consistent API for calling operations using JavaScript methods based on operationIds. It operates isothermically in both browser and Node.js environments. Key differentiators include its no-code-generation approach, strong TypeScript integration, and reliance on existing, robust HTTP client infrastructure (axios), providing a predictable release cadence tied to upstream OpenAPI spec updates and axios releases.
Common errors
-
Cannot read properties of undefined (reading 'default')
cause Attempting to use `require('openapi-client-axios')` directly in CommonJS without accessing the default export of the module.fixModify your import to `const OpenAPIClientAxios = require('openapi-client-axios').default;`. -
Error: definition must be a string (URL) or an object
cause Passing a local file path (e.g., `./openapi.json`) as the `definition` option, which is no longer supported for file system resolution since v7.0.0.fixProvide a URL for the OpenAPI definition, or read the file content yourself and pass the parsed JSON/YAML object directly: `new OpenAPIClientAxios({ definition: yourParsedObject })`. -
ReferenceError: require is not defined in ES module scope
cause Using CommonJS `require()` syntax in an environment configured for ES Modules (e.g., Node.js with `"type": "module"` in `package.json` or in a browser bundling context expecting ESM).fixReplace `require()` with the standard ES Module `import` syntax: `import OpenAPIClientAxios from 'openapi-client-axios';`.
Warnings
- breaking Since v7.0.0, `openapi-client-axios` no longer supports resolving remote `$refs` or loading OpenAPI definitions from local file paths. Definitions must be provided as local URLs or inline JavaScript/JSON objects.
- breaking Version 7.0.0 removed the `@apidevtools/swagger-parser` dependency, replacing it with an internal, simpler dereferencer. This change significantly reduces bundle size but means custom parsing or complex `$ref` resolution strategies previously relying on `swagger-parser` may no longer work.
- breaking Version 6.0.0 introduced support for `axios` v1 and above. Older versions of `axios` might lead to compatibility issues or unexpected behavior.
- gotcha When using `openapi-client-axios` in a CommonJS environment (e.g., Node.js without ESM enabled), the `OpenAPIClientAxios` class is exposed as a default export, requiring `.default` to access.
Install
-
npm install openapi-client-axios -
yarn add openapi-client-axios -
pnpm add openapi-client-axios
Imports
- OpenAPIClientAxios
import { OpenAPIClientAxios } from 'openapi-client-axios';import OpenAPIClientAxios from 'openapi-client-axios';
- Client
import type { Client } from 'openapi-client-axios'; - OpenAPIClient
import type { OpenAPIClient } from 'openapi-client-axios';
Quickstart
import OpenAPIClientAxios from 'openapi-client-axios';
import type { Client } from 'openapi-client-axios';
const PETSTORE_URL = 'https://petstore.swagger.io/v2/swagger.json';
// Initialize the client with the OpenAPI definition URL
const api = new OpenAPIClientAxios({ definition: PETSTORE_URL });
async function fetchAndCreatePet() {
try {
// Initialize the API client and get the generated operations
const client: Client = await api.getClient();
// Example 1: Fetch all pets (using a method derived from operationId 'findPetsByStatus')
console.log('Fetching available pets...');
const availablePetsResponse = await client.findPetsByStatus({ status: ['available'] });
console.log('Available pets:', availablePetsResponse.data.slice(0, 3)); // Log first 3
// Example 2: Create a new pet (using operationId 'addPet')
console.log('\nAdding a new pet...');
const newPet = {
id: 987654321,
name: 'Buddy',
status: 'available',
category: { id: 1, name: 'Dogs' },
photoUrls: ['http://example.com/buddy.jpg']
};
const addPetResponse = await client.addPet(newPet);
console.log('New pet added:', addPetResponse.data);
} catch (error: any) {
console.error('An error occurred:', error.message);
if (error.response) {
console.error('API Response Data:', error.response.data);
}
}
}
fetchAndCreatePet();