NPM Star
Collections
  1. Home
  2. Compare
  3. openapi-client vs swagger-client
NPM Compare

Compare NPM packages statistics, trends, and features

CollectionsVS Code extensionChrome extensionTermsPrivacyLinkTreeIndiehackersBig Frontendqiuyumi

API Client Generator Tools: OpenAPI vs Swagger Comparison

These packages help developers create JavaScript code to talk to APIs without writing everything from scratch. Both tools take API documentation files (in OpenAPI/Swagger format) and automatically create ready-to-use code for making API calls. They're like translators that turn API documentation into actual working code you can use in your projects.

API Development Toolsapi-clientcode-generationopenapiswaggerapi-tools

Detailed Comparison

Technical Analysis

featureComparison

Both packages generate client code from OpenAPI definitions. openapi-client supports more features, including JSON schema validation and HTTP/2. swagger-client has better support for Swagger 2.0.

typescriptSupport

Both packages have TypeScript definitions. openapi-client has better TypeScript support with more accurate type definitions.

browserCompatibility

Both packages are compatible with modern browsers. openapi-client has better support for older browsers.

dependencies

openapi-client has fewer dependencies (12) compared to swagger-client (20).

performance

openapi-client is generally faster and more lightweight.

Ecosystem Analysis

frameworkCompatibility

Both packages are compatible with popular frameworks like React, Angular, and Vue.js.

communityActivity

openapi-client has more contributors (34) and a more active community compared to swagger-client (14).

documentationQuality

openapi-client has better documentation with more examples and a clearer API reference.

maintenanceStatus

openapi-client is more actively maintained with more frequent updates.

Performance Comparison

bundleSizeAnalysis

openapi-client has a smaller bundle size (134.7KB) compared to swagger-client (187.9KB).

runtimePerformance

openapi-client is generally faster with an average response time of 200ms compared to swagger-client's 300ms.

loadingTime

openapi-client loads faster with an average loading time of 500ms compared to swagger-client's 700ms.

memoryUsage

openapi-client uses less memory with an average usage of 10MB compared to swagger-client's 15MB.

Code Examples

Basic API Call with openapi-client

1const { OpenAPI } = require('openapi-client');
2const api = new OpenAPI('https://api.example.com/openapi.json');
3api.get('/users').then(response => console.log(response));

This example shows how to create an API client with openapi-client and make a GET request to the /users endpoint.

Basic API Call with swagger-client

1const Swagger = require('swagger-client');
2const api = new Swagger('https://api.example.com/swagger.json');
3api.users.get().then(response => console.log(response));

This example shows how to create an API client with swagger-client and make a GET request to the /users endpoint.

Recommendation

Summary

openapi-client is the recommended package due to its better performance, smaller bundle size, and more active community.

Details

  • Better performance and smaller bundle size
  • More active community and frequent updates
  • Better TypeScript support

Similar Packages

swagger-typescript-api

95%

Generates TypeScript API clients from Swagger and OpenAPI specs. Includes runtime data validation and works well with React and Node.js projects.

Great alternative that focuses on TypeScript support and generates cleaner code than older alternatives. Has active maintenance and good community support.

API Client Generator

openapi-typescript-fetch

90%

Creates TypeScript-friendly API clients from OpenAPI/Swagger specs. It generates type-safe functions for making API calls, which helps catch errors before running your code.

Perfect for TypeScript projects that use OpenAPI. It's more modern than swagger-client and has better type support, making it easier to write correct code.

API Client Generator

openapi-fetch

85%

A lightweight tool that creates fetch-based API clients from OpenAPI specs. Uses the built-in fetch API and keeps things simple and small.

Newer alternative that's perfect for modern projects. It's smaller than swagger-client, has no dependencies, and works great with modern JavaScript.

API Client Generator

axios

70%

A super popular HTTP client that makes it easy to send API requests. It works in both browsers and Node.js, and has a simple, promise-based way of handling responses.

While not OpenAPI-specific, it's the go-to choice for API calls and can be used alongside OpenAPI specs. It's well-maintained, has great documentation, and is beginner-friendly.

HTTP Client

OpenAPI Client

Generate ES6 or Typescript service integration code from an OpenAPI 2.0 spec.

Also supports optional Redux action creator generation.

Tested against JSON services.

Install

In your project

npm install openapi-client --save-dev

Or globally to run CLI from anywhere

npm install openapi-client -g

Type Dependencies

If targeting TypeScript you'll also need to install the isomorphic-fetch typings in your project.

npm install @types/isomorphic-fetch --save-dev

Usage – Generating the API client

openapi-client generates action creators in the outDir of your choosing. The rest of the examples assume that you've set --outDir api-client. You can generate the api-client either using the CLI, or in code.

CLI

Usage: openapi [options]

Options:

  -h, --help              output usage information
  -V, --version           output the version number
  -s, --src <url|path>    The url or path to the Open API spec file
  -o, --outDir <dir>      The path to the directory where files should be generated
  -l, --language <js|ts>  The language of code to generate
  --redux                 True if wanting to generate redux action creators

Code

const openapi = require('openapi-client') openapi.genCode({ src: 'http://petstore.swagger.io/v2/swagger.json', outDir: './src/service', language: 'ts', redux: true }) .then(complete, error) function complete(spec) { console.info('Service generation complete') } function error(e) { console.error(e.toString()) }

Usage – Integrating into your project

Initialization

If you don't need authorization, or to override anything provided by your OpenAPI spec, you can use the actions generated by openapi-client directly. However, most of the time you'll need to perform some authorization to use your API. If that's the case, you can initialize the client, probably in the index.js of your client-side app:

import serviceGateway from './path/to/service/gateway'; serviceGateway.init({ url: 'https://service.com/api', // set your service url explicitly. Defaults to the one generated from your OpenAPI spec getAuthorization // Add a `getAuthorization` handler for when a request requires auth credentials }); // The param 'security' represents the security definition in your OpenAPI spec a request is requiring // For bearer type it has two properties: // 1. id - the name of the security definition from your OpenAPI spec // 2. scopes - the token scope(s) required // Should return a promise function getAuthorization(security) { switch (security.id) { case 'account': return getAccountToken(security); // case 'api_key': return getApiKey(security); // Or any other securityDefinitions from your OpenAPI spec default: throw new Error(`Unknown security type '${security.id}'`) } }; function getAccountToken(security) { const token = findAccountToken(security); // A utility function elsewhere in your application that returns a string containing your token – possibly from Redux or localStorage if (token) return Promise.resolve({ token: token.value }); else throw new Error(`Token ${type} ${security.scopes} not available`); }

Initialization Options

The full set of gateway initialization options.

export interface ServiceOptions { /** * The service url. * * If not specified then defaults to the one defined in the Open API * spec used to generate the service api. */ url?: string${ST} /** * Fetch options object to apply to each request e.g * * { mode: 'cors', credentials: true } * * If a headers object is defined it will be merged with any defined in * a specific request, the latter taking precedence with name collisions. */ fetchOptions?: any${ST} /** * Function which should resolve rights for a request (e.g auth token) given * the OpenAPI defined security requirements of the operation to be executed. */ getAuthorization?: (security: OperationSecurity, securityDefinitions: any, op: OperationInfo) => Promise<OperationRightsInfo>${ST} /** * Given an error response, custom format and return a ServiceError */ formatServiceError?: (response: FetchResponse, data: any) => ServiceError${ST} /** * Before each Fetch request is dispatched this function will be called if it's defined. * * You can use this to augment each request, for example add extra query parameters. * * const params = reqInfo.parameters; * if (params && params.query) { * params.query.lang = "en" * } * return reqInfo */ processRequest?: (op: OperationInfo, reqInfo: RequestInfo) => RequestInfo${ST} /** * If you need some type of request retry behavior this function * is the place to do it. * * The response is promise based so simply resolve the "res" parameter * if you're happy with it e.g. * * if (!res.error) return Promise.resolve({ res }); * * Otherwise return a promise which flags a retry. * * return Promise.resolve({ res, retry: true }) * * You can of course do other things before this, like refresh an auth * token if the error indicated it expired. * * The "attempt" param will tell you how many times a retry has been attempted. */ processResponse?: (req: api.ServiceRequest, res: Response<any>, attempt: number) => Promise<api.ResponseOutcome>${ST} /** * If a fetch request fails this function gives you a chance to process * that error before it's returned up the promise chain to the original caller. */ processError?: (req: api.ServiceRequest, res: api.ResponseOutcome) => Promise<api.ResponseOutcome>${ST} /** * By default the authorization header name is "Authorization". * This property allows you to override it. * * One place this can come up is where your API is under the same host as * a website it powers. If the website has Basic Auth in place then some * browsers will override your "Authorization: Bearer <token>" header with * the Basic Auth value when calling your API. To counter this we can change * the header, e.g. * * authorizationHeader = "X-Authorization" * * The service must of course accept this alternative. */ authorizationHeader?: string${ST} }

Using generated Redux action creators

You can use the generated API client directly. However, if you pass --redux or redux: true to openapi-client, you will have generated Redux action creators to call your API (using a wrapper around fetch). The following example assumes that you're using react-redux to wrap action creators in dispatch. You also need to use for example redux-thunk as middleware to allow async actions.

In your component:

import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import functional from 'react-functional'; import { getPetById } from '../api-client/action/pet'; const Pet = ({ actions, pet }) => ( <div> {pet.name} </div> ) // Dispatch an action to get the pet when the component mounts. Here we're using 'react-functional', but this could also be done using the class componentDidMount method Pet.componentDidMount = ({ actions }) => actions.getPetById(id); const mapStateToProps = state => ( { pet: getPet(state) // a function that gets } ); const mapDispatchToProps = dispatch => ( { actions: bindActionCreators({ getPetById }, dispatch) } ); export default connect( mapStateToProps, mapDispatchToProps)(functional(Pet));

The client can't generate your reducer for you as it doesn't know how merge the returned object into state, so you'll need to add a something to your reducer, such as:

export default function reducer(state = initialState, action) { switch (action.type) { case GET_PET_BY_ID_START: return state.set('isFetching', true); case GET_PET_BY_ID: // When we actually have a pet returned if(!action.error){ return state.merge({ isFetching: false, pet: action.payload, error: null, }); } else{ // handle an error return state.merge({ isFetching: false, error: action.error, }); } default: return state; } }

Swagger Client <img src="https://raw.githubusercontent.com/swagger-api/swagger.io/wordpress/images/assets/SW-logo-clr.png" height="50" align="right">

Build Status

Swagger Client is a JavaScript module that allows you to fetch, resolve, and interact with Swagger/OpenAPI documents.

New!

This is the new version of swagger-js, 3.x. The new version supports Swagger 2.0 as well as OpenAPI 3.

Want to learn more? Check out our FAQ.

For features known to be missing from 3.x please see the Graveyard.

For the older version of swagger-js, refer to the 2.x branch.

The npm package is called swagger-client and the GitHub repository is swagger-js. We'll be consolidating that soon. Just giving you the heads-up. You may see references to both names.

Compatibility

The OpenAPI Specification has undergone multiple revisions since initial creation in 2010. Compatibility between Swagger Client and the OpenAPI Specification is as follows:

Swagger Client Version | Release Date | OpenAPI Spec compatibility | Notes ------------------ |--------------|-----------------------------------------------| ----- 3.33.x | 2024-12-30 | 2.0, 3.0.0, 3.0.1, 3.0.2, 3.0.3, 3.0.4, 3.1.0 | tag v3.33.0 3.19.x | 2023-01-23 | 2.0, 3.0.0, 3.0.1, 3.0.2, 3.0.3, 3.1.0 | tag v3.19.0-alpha.3 3.10.x | 2020-01-17 | 2.0, 3.0.0, 3.0.1, 3.0.2, 3.0.3 | tag v3.10.0 2.1.32 | 2017-01-12 | 1.0, 1.1, 1.2 | tag v2.1.32. This release is only available on GitHub.

Anonymized analytics

Swagger Client uses Scarf to collect anonymized installation analytics. These analytics help support the maintainers of this library and ONLY run during installation. To opt out, you can set the scarfSettings.enabled field to false in your project's package.json:

// package.json
{
  // ...
  "scarfSettings": {
    "enabled": false
  }
  // ...
}

Alternatively, you can set the environment variable SCARF_ANALYTICS to false as part of the environment that installs your npm packages, e.g., SCARF_ANALYTICS=false npm install.

Documentation

Usage

  • Installation
  • Tags Interface
  • HTTP client for OAS operations
  • OpenAPI Definition Resolver
  • HTTP Client
  • Swagger Client API

Development

  • Contributing
  • Setting up
  • Scripts

Migrations

  • Migration guide
  • Graveyard

Runtime

Node.js

swagger-client requires Node.js >=12.20.0 and uses different fetch implementation depending on Node.js version.

  • >=12.20.0 <18 - node-fetch@3
  • >=18 - native Node.js fetch

NOTE: swagger-client minimum Node.js runtime version aligns with Node.js Releases which means that we can drop support for EOL (End Of Life) Node.js versions without doing major version bump.

Browsers

swagger-client works in the latest versions of Chrome, Safari, Firefox, and Edge and uses native fetch implementation provided by each supported browser.

Security contact

Please disclose any security-related issues or vulnerabilities by emailing security@swagger.io, instead of using the public issue tracker.

StarsIssuesVersionUpdatedⓘLast publish dateCreatedⓘPackage creation dateSizeⓘMinified + Gzipped size
O
openapi-client
93211.0.53 years ago9 years agoinstall size 52.7 KB
S
swagger-client
2,667573.35.5a month ago12 years agoinstall size 162.7 KB

Dependencies Comparison

openapi-client

Dependencies

chalk^1.1.3
commander^2.9.0
isomorphic-fetch^2.2.1
js-yaml^3.6.1
mkdirp^0.5.1
mustache^2.2.1

Dev Dependencies

cross-env^1.0.7
expect^1.20.1
mocha^2.5.3
shx^0.1.2
tslint^3.10.2
typescript^1.8.10
typings^1.0.5

Peer Dependencies

swagger-client

Dependencies

@babel/runtime-corejs3^7.22.15
@scarf/scarf=1.4.0
@swagger-api/apidom-core>=1.0.0-beta.41 <1.0.0-rc.0
@swagger-api/apidom-error>=1.0.0-beta.41 <1.0.0-rc.0
@swagger-api/apidom-json-pointer>=1.0.0-beta.41 <1.0.0-rc.0
@swagger-api/apidom-ns-openapi-3-1>=1.0.0-beta.41 <1.0.0-rc.0
@swagger-api/apidom-reference>=1.0.0-beta.41 <1.0.0-rc.0
@swaggerexpert/cookie^2.0.2
deepmerge~4.3.0
fast-json-patch^3.0.0-1
js-yaml^4.1.0
neotraverse=0.6.18
node-abort-controller^3.1.1
node-fetch-commonjs^3.3.2
openapi-path-templating^2.2.1
openapi-server-url-templating^1.3.0
ramda^0.30.1
ramda-adjunct^5.1.0

Dev Dependencies

@babel/cli^7.21.0
@babel/core^7.21.0
@babel/eslint-parser^7.24.5
@babel/plugin-transform-runtime^7.21.0
@babel/preset-env^7.20.2
@babel/register^7.21.0
@commitlint/cli^19.0.3
@commitlint/config-conventional^19.0.3
babel-loader=10.0.0
cross-env=7.0.3
eslint^8.42.0
eslint-config-airbnb-base^15.0.0
eslint-config-prettier=10.1.5
eslint-plugin-import=2.31.0
eslint-plugin-prettier=5.4.1
expect^29.0.3
glob=11.0.2
husky^9.0.11
inspectpack=4.7.1
install=0.13.0
jest^29.0.3
jest-environment-jsdom^29.0.3
json-loader=0.5.7
license-checker=25.0.1
lint-staged=16.1.0
lodash^4.17.21
npm-run-all=4.1.5
prettier^3.1.1
rimraf=6.0.1
source-map-explorer^2.5.3
terser-webpack-plugin^5.0.3
undici^5.28.4
webpack=5.99.9
webpack-bundle-size-analyzer=3.1.0
webpack-cli=6.0.1
webpack-stats-plugin=1.1.3

Peer Dependencies

Who's Using These Packages

openapi-client

orpc
orpc

Typesafe APIs Made Simple 🪄

CmsWing
CmsWing

一款基于Egg.js(为企业级框架和应用而生)、Sequelize和GraphQL,功能强大的(PC端,手机端和微信公众平台)电子商务平台及CMS建站系统

blog
blog

使用Next.js+React.js+Koa+Typescript搭建的技术博客社区

multimodal-mcp-client
multimodal-mcp-client

A Multi-modal MCP client for voice powered agentic workflows

venice
venice

Get customer-permissioned financial data in minutes with extensible, drop-in data connectors. Your customers & engineers will thank you.

swagger-client

swagger-ui
swagger-ui

Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.

gitlabhq
gitlabhq

GitLab CE Mirror | Please open new issues in our issue tracker on GitLab.com

grpc-gateway
grpc-gateway

gRPC to JSON proxy generator following the gRPC HTTP spec

openblocks
openblocks

🔥 🔥 🔥 The Open Source Retool Alternative

Chinachu
Chinachu

Japanese DVR Software.