npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

appc-swagger-client

v2.2.0

Published

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

Downloads

7

Readme

Swagger JS library

Build Status

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.

Calling an API with swagger + node.js!

Install swagger-client:

npm install swagger-client

or:

bower install swagger-js

Then let swagger do the work!

var Swagger = require('swagger-client');

var client = new Swagger({
  url: 'http://petstore.swagger.io/v2/swagger.json',
  success: function() {
    client.pet.getPetById({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": [
    "url1",
    "url2"
  ],
  "tags": [
    {
      "id": 1,
      "name": "tag1"
    },
    {
      "id": 2,
      "name": "tag2"
    }
  ],
  "status": "available"
}

Handling success and failures

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: 'http://petstore.swagger.io/v2/swagger.json',
  success: function() {
    client.pet.getPetById({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: 'http://petstore.swagger.io/v2/swagger.json',
  usePromise: true
})
.then(function(client) {
  client.pet.getPetById({petId:7})
    .then(function(pet) {
      console.log(pet.obj);
    })
    .catch(function(error) {
      console.log('Oops!  failed with message: ' + error.statusText);
    });
});

Need to pass an API key? Configure one 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: 'http://example.com/spec.json',
  success: function() {},
  authorizations : {
    easyapi_basic: new client.PasswordAuthorization('<username>', '<password>'),
    someHeaderAuth: new client.ApiKeyAuthorization('<nameOfHeader>', '<value>', 'header'),
    someQueryAuth: new client.ApiKeyAuthorization('<nameOfQueryKey>', '<value>', 'query'),
    someCookieAuth: new client.CookieAuthorization('<cookie>'),
  }
});

Calling an API with swagger + the browser!

Download browser/swagger-client.js 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: "http://petstore.swagger.io/v2/swagger.json",
    success: function() {
      // upon connect, fetch a pet and set contents to element "mydata"
      client.pet.getPetById({petId:1},{responseContentType: 'application/json'}, function(data) {
        document.getElementById("mydata").innerHTML = JSON.stringify(data.obj);
      });
    }
  });
</script>

<body>
  <div id="mydata"></div>
</body>

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

var pet = {
  id: 100,
  name: "dog"};

client.pet.addPet({body: pet});

Sending XML in as a payload to your API?

var pet = "<Pet><id>2</id><name>monster</name></Pet>";

client.pet.addPet({body: pet}, {requestContentType:"application/xml"});

Need XML response?

client.pet.getPetById({petId:1}, {responseContentType:"application/xml"});

Custom request signing

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

var CustomRequestSigner = function(name) {
  this.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());

How does it work?

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:

s.apis.pet.getPetById.help()
'* petId (required) - ID of pet that needs to be fetched'

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

Development

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

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
gulp

# 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

License

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 apache.org/licenses/LICENSE-2.0

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.