OpenAPI Client Axios

7.9.0 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

Initializes an OpenAPI client with a public Petstore definition, then demonstrates fetching existing data and creating new resources using the dynamically generated client methods.

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();

view raw JSON →