DavidSpot Blog

Developer, super curious, a dog lover, sports fan and techie guy


Swagger CodeGen Tooling - the WSDL and Proxy Generator for REST API

I'm developing REST services for some time for at my job and the most difficult part it's when I have to make a some changes to structure of the request/response objects and this is the result of the very nature of a REST service, a call made through an HTTP Request with a meaning full URL path like http://api.uber.com/products?localtion=lisbon where you normally receive a JSON result.

Usually a use a Swagger to generate a nice documentation so that clients can easily check the service details and test if needed, here an image with an example from a generate web API description from the swagger website:

The problem with JSON, despite of being so dynamic, we lose type and with this we lose tooling and compile time errors witch are handy to catch errors earlier than in runtime.

In the traditional way, where we use SOAP services (for instance WCF from Microsoft), you can use the WSDL file to generate the client proxy witch has all the methods available in the server and with the advantage of getting strongly typed classes witch it's awesome for tooling and intellisense.

But... there's hope, the team behind the Swagger tool created a nice "WSDL and Proxy Generator" for REST API's that generate code for all this languages

And this is so cool that this even allow us to generate the Server side code as well.

You can see in the demo editor page how this works, just select one of the dropdowns (Generate Server or Generate Client), select the language/framework and that's it, you will download a complete Server API or Proxy Client in the language of your choice. You can also edit the contents of your REST Service directly in the browser

Because I'm .NET developer, I use a :NET tool called Swashbuckle that it's a development by the .net community that uses All the Swagger features for .NET.

To see a complete list of Swagger Community integrations go here


Publish-Subscribe pattern in javascript

If you never used a pattern like pub/sub this is very useful when you are creating a modular application and need communication between them.

A simple (yet powerfull) mini pub/sub library could be the one below:

var JSNotify = (function(){
  var topics = {};
  var hOP = topics.hasOwnProperty;

  return {
    subscribe: function(topic, listener) {
		
      // Create the topic's object if not yet created
      if(!hOP.call(topics, topic)) {
		  topics[topic] = [];
	  }

      // Add the listener to queue
      var index = topics[topic].push(listener) -1;

      // Provide handle back for removal of topic
      return {
        remove: function() {
          delete topics[topic][index];
        }
      };
    },
    notify: function(topic, info) {
		
      // If the topic doesn't exist, or there's no listeners in queue, just leave
      if(!hOP.call(topics, topic)) {
		  return;
	  }

      // Cycle through topics queue, fire!
      topics[topic].forEach(function(item) {
      		item(info != undefined ? info : {});
      });
    }
  };
})();


To subscribe do this:

var subscription = JSNotify.subscribe('pubSubDemo', function (obj) {
        console.log(obj);
    });

 

To notify the subscribers do this:

    JSNotify.notify('pubSubDemo', {
        //any argument
        hello: 'hello world' 
    });

 

To stop receiving notifications just remove:

subscription.remove();

 

If you're using Knockout you can also use the ko.subscribable function and this is very similar to the previous example:

     //create a subscriber
    var postbox = new ko.subscribable();

    //subcribe channel with topic "divChanged"
    postbox.subscribe(function (newValue) {
        console.log(newValue);
    }, this, "divChanged");

    //notify all listeners in channel "divChanged" (in this case only one) and pass some a parameter
    //I'm passing a string "div1", but you could pass anything you want
    postbox.notifySubscribers("div1", "divChanged");

 


From C# to Javascript and the problem with return keyword and curly braces position

Many new javascript developers that have some background with C# development some times have problems when returning objects from within a javascript function by putting the curly braces after the return keyword.

Because javascript Semicolon is optional (different from C# or Java witch is required to end a sentence) the javascript interpreter will try to guess where to put when it's not present.

For instance, the code below results in different results:

// Good
return {
    prop : "one"
};

// Bad!
return
{
    prop : "two"
};

The first one returns an object as expected but the last returns undefined and here is the reason why:

return; // Semicolon inserted, believing the statement has finished. Returns undefined
{ // Considered to be an anonymous block, doing nothing
	prop : "two"
};// Semicolon interpreted as an empty dummy line and moved down
 

C# developers, that normally use Visual Studio, are used to the default syntax (by default if you use Ctrl + K + D shortcut, visual studio will auto-ident the code for you), witch puts in a new line a curly brace every time with have a class or method and because of this the probability to make have this kind of unexpected error it's big.

My suggestion to avoid this problem is to put the first curly brace always at the end of the line preceded by some other code.