Swagger is a tool that allows to describe a service API. One of the reasons for that is creation of documentation for all API functions so make it easy to examine and navigate through. Even further, swagger allows to call the API functions in a simple manner like let's say Postman does. So working with ExpressJS I just discovered the swagger-ui-express library that gives us opportunity to build the swagger UI in literaly few steps. So I created the simplest possible example (Github Link) that will be be taken to pieces below step-by-step.
As usually, we start with installing the package npm install -s swagger-ui-express.
Now let's create a simple ExpressJS HTTP server with several CRUD functions.
const express = require('express'); const app = express(); const uuidv4 = require('uuid/v4'); //stores the books collection let _books = []; app.route('/api/book') .get(function (req, res) { res.json(_books.filter(b => b.id == req.query.id)); }) .put(function (req, res) { let book = JSON.parse(JSON.stringify(req.query)); book.id = uuidv4(); _books.push(book); res.json(book); }) .delete(function (req, res) { _books = _books.filter(b => b.id != req.query.id); res.json(_books); }) app.get('/api/books', function (req, res) { res.json(_books); }); // start the server in the port 3000 app.listen(3000, function () { console.log('Start app listening on port 3000.'); });
The service exposes functions allow to get/add/delete records (books) and retrieve all the books as well.
Next step is to display that API on UI.