node package manager


swagger-client is a javascript client for use with swaggering APIs.

Swagger JS library

This is the Swagger javascript client for use with swagger enabled APIs. It's written in javascript and tested with mocha, and is the fastest way to enable a javascript client to communicate with a swagger-enabled server.

Check out Swagger-Spec for additional information about the Swagger project, including additional libraries with support for other languages and more.

Install swagger-client:

npm install swagger-client


bower install swagger-js

Then let swagger do the work!

var Swagger = require('swagger-client');
var client = new Swagger({
  url: '',
  success: function() {{petId:7},{responseContentType: 'application/json'},function(pet){
      console.log('pet', pet);

NOTE: we're explicitly setting the responseContentType, because we don't want you getting stuck when there is more than one content type available.

That's it! You'll get a JSON response with the default callback handler:

  "id": 1,
  "category": {
    "id": 2,
    "name": "Cats"
  "name": "Cat 1",
  "photoUrls": [
  "tags": [
      "id": 1,
      "name": "tag1"
      "id": 2,
      "name": "tag2"
  "status": "available"

You need to pass success and error functions to do anything reasonable with the responses:

var Swagger = require('swagger-client');
var client = new Swagger({
  url: '',
  success: function() {{petId:7}, function(success){
      console.log('succeeded and returned this object: ' + success.obj);
    function(error) {
      console.log('failed with the following: ' + error.statusText);

You can use promises, too, by passing the usePromise: true option:

var Swagger = require('swagger-client');
new Swagger({
  url: '',
  usePromise: true
.then(function(client) {{petId:7})
    .then(function(pet) {
    .catch(function(error) {
      console.log('Oops!  failed with message: ' + error.statusText);

Need to pass an API key? Configure one in your client instance as a query string:

client.clientAuthorizations.add("apiKey", new Swagger.ApiKeyAuthorization("api_key","special-key","query"));

...or with a header:

client.clientAuthorizations.add("apiKey", new Swagger.ApiKeyAuthorization("api_key","special-key","header"));

...or with the swagger-client constructor:

var client = new Swagger({
  url: '',
  success: function() {},
  authorizations : {
    easyapi_basic: new Swagger.PasswordAuthorization('<username>', '<password>'),
    someHeaderAuth: new Swagger.ApiKeyAuthorization('<nameOfHeader>', '<value>', 'header'),
    someQueryAuth: new Swagger.ApiKeyAuthorization('<nameOfQueryKey>', '<value>', 'query'),
    someCookieAuth: new Swagger.CookieAuthorization('<cookie>'),

Note the authorization nickname, such as easyapi_basic in the above example, must match the security requirement in the specification (see the OAI Specification for details).

You can also pass authorzations on a per-request basis, in the event that you're reusing a swagger-client object across multiple connections:{pet: {
    name: 'doggie'
  }}, {
    clientAuthorizations: {
      api_key: new Swagger.ApiKeyAuthorization('foo', 'bar', 'header')
  .then(function(pet) {

Download browser/swagger-client.min.js and place it into your webapp:

<script src='browser/swagger-client.js' type='text/javascript'></script>
<script type="text/javascript">
  // initialize swagger client, point to a resource listing 
  window.client = new SwaggerClient({
    url: "",
    success: function() {
      // upon connect, fetch a pet and set contents to element "mydata"{petId:1},{responseContentType: 'application/json'}, function(data) {
        document.getElementById("mydata").innerHTML = JSON.stringify(data.obj);
  <div id="mydata"></div>

Need to send an object to your API via POST or PUT?

var pet = {
  id: 100,
  name: "dog"};
// note: the parameter for `addPet` is named `body` in the example below{body: pet});
var pet = "<Pet><id>2</id><name>monster</name></Pet>";{body: pet}, {requestContentType:"application/xml"});{petId:1}, {responseContentType:"application/xml"});

You can easily write your own request signing code for Swagger. For example:

var CustomRequestSigner = function(name) { = name;
CustomRequestSigner.prototype.apply = function(obj, authorizations) {
  var hashFunction = this._btoa;
  var hash = hashFunction(obj.url);
  obj.headers["signature"] = hash;
  return true;

In the above simple example, we're creating a new request signer that simply Base64 encodes the URL. Of course you'd do something more sophisticated, but after encoding it, a header called signature is set before sending the request.

You can add it to the swagger-client like such:

client.clientAuthorizations.add('my-auth', new CustomRequestSigner());

Headers are a type of parameter, and can be passed with the other parameters. For example, if you supported translated pet details via the Accept-Language header:

"parameters": [
    "name": "petId",
    "description": "ID of pet that needs to be fetched",
    "required": true,
    "type": "integer",
    "format": "int64",
    "paramType": "path",
    "minimum": "1.0",
    "defaultValue": 3,
    "maximum": "100000.0"
  "LanguageHeader": {
    "name": "Accept-Language",
    "in": "header",
    "description": "Specify the user's language",
    "required": false,
    "type": "string"

Then you would pass the header value via the parameters (header parameters are case-insenstive):{
  petId: 7,
  'accept-language': 'fr'
}, function(pet){
  console.log('pet', pet);

Don't like superagent? Despise JQuery? Well, you're in luck. You can plug your own HTTP library easily:

var myHttpClient = {
  // implment an execute function 
  execute: function(obj) {
    var httpMethod = obj.method;
    var requestHeaders = obj.headers;
    var body = obj.body;
    var url = obj.url;
    // do your thing, and call `obj.on.response` 
    if(itWorked) {
    else {
var client = new SwaggerClient({
  spec: petstoreRaw,
  client: myHttpClient,
  success: function () {{petId: 3}, function(data){

The swagger javascript client reads the swagger api definition directly from the server. As it does, it constructs a client based on the api definition, which means it is completely dynamic. It even reads the api text descriptions (which are intended for humans!) and provides help if you need it:
'* petId (required) - ID of pet that needs to be fetched'

The HTTP requests themselves are handled by the excellent superagent library, which has a ton of features itself. But it runs on both node and the browser.

Please fork the code and help us improve swagger-js. Send us a pull request to the master branch! Tests make merges get accepted more quickly.

Note! We will not merge pull requests for features not supported in the OAI Specification! Add an issue there instead!

swagger-js use gulp for Node.js.

# Install the gulp client on the path
npm install -g gulp
# Install all project dependencies
npm install
# List all tasks.
gulp -T
# Run lint (will not fail if there are errors/warnings), tests (without coverage) and builds the browser binaries
# Run the test suite (without coverage)
gulp test
# Build the browser binaries (One for development with source maps and one that is minified and without source maps) in the browser directory
gulp build
# Continuously run the test suite:
gulp watch
# Run jshint report
gulp lint
# Run a coverage report based on running the unit tests
gulp coverage

Copyright 2016 SmartBear Software

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.