The Perfect REST API (Part 3)

The back end part is done. The REST API is set into place and running somewhere in the background. Now it is time to integrate the Swagger definitions into the front end part of our application.

As for the back end we have a ready to use npm package for the Swagger integration: Swagger Server

Why to build upon Swagger?

You could ask: Why should I build my front end on Swagger at all? I could also just use the Swagger file, open it in the Swagger Editor and use the documentation to develop the front end.

While this would be a totally valid approach, there are some more aspects to think about:

  • Do you want to run the - potentially time-consuming - back end calls against a live back end, while you develop?
  • Do you want to get live data from the back end or do you prefer to have mocked data during the development process?
  • How do you integrate the mocked data into the front end without affecting the built version?

As you can imagine, those questions can be easily answered with the Swagger Server package.

Define the build process

We only rely on Node.js for this step. Let's create a Javascript file and name it for example server.js. Then let's load the Swagger Server which is based on Express.js.

var swagger  = require('swagger-server'),  
    Server   = swagger.Server;

// Create a Swagger Server instance
var server = new Server();  

We then parse the Swagger definitions that we have created in the previous tutorials.

server.parse('swagger.yaml');  

Now we could just start the server and make it listen on the port that is specified in the swagger.yaml file.

// Start listening
server.listen();  

But hey, what about mocking?

Creating mock handlers

While the Swagger Server will serve mock data by itself without defining anything else, we most likely want to define some mock objects of our own. Let's do this for one of our routes defined in the last part of this series.

/**
 * The camels route.
 *
 * @param server
 */
module.exports = function (server) {

  server.get('/camels', function(req, res) {
    res.json([
      {
        "id": 1,
        "name": "Carlos",
        "color": "Autumn Gold"
     },
     {
       "id": 2,
       "name": "Alfredo",
       "color": "Raven Black" // creepy I know
     }
  ]);
};

But what if we have a parameter in our route like for retrieving one particular camel? No problem, Swagger Server offers a nice option for that.

var swagger  = require('swagger-server'),  
    Resource = swagger.Resource;

/**
 * The camels/:id route.
 *
 * @param server
 */
module.exports = function (server) {

  server.dataStore.save(
    new Resource('/camels/1', { /* include Carlo here */ }));

  server.dataStore.save(
    new Resource('/camels/2', { /* include Alfredo here */ }));
};

Sweet! Now we can create any type of mock object and return it for specific routes. Let's tell Swagger Server to use those mocks.

Include the mock handlers

Let's get back to the server.js file we created in the last step. Before we tell the server to listen, we load the new mock objects defined in mock/camels.jsand mock/camel.js.

// initialize mock objects for all available routes
require('./mock/camels')(server);  
require('./mock/camel')(server);  

The only thing left is do add some configuration for the Swagger Server and include an error handler.

// Enable Express' case-sensitive and strict options
server.enable('case sensitive routing');  
server.enable('strict routing');

// Add a custom error handler
server.use(function(err, req, res, next) {  
  res.status(err.status);
  res.type('html');
  res.send('<html><body><h1>' + err.status + ' Error!</h1><p>' + err.message + '</p></body></html>'));
});

Summary

Congratulations, you reached the end of that short tutorial! We learned, how to work with Swagger, how to use it in our Node.js back end application and how to make the most out of it for the front end development process.

I can only encourage you to try Swagger on your own. It's an amazing ecosystem for API development and it makes your development a lot easier in the long term.

If you have any questions or if you need some help with your API development, don't hesitate to get in touch with me.