Saturday, September 24, 2016

Apidocs for Rest in Node js

Hey guys, I know I am pretty late in creating the content but this sharing a worth .

So now for all of you I want to tell you that I started working in Node js from past 6 months and found it really interesting in the way it handles the stuff and ease by which new things gets created in Node.

Now a days the frameworks are getting created by keeping a motto in mind that the client feels very less friction in attaching it. So for that only the concept of REST is becoming very popular.

Since in case of REST you don't need that the client have to install any executable or generate any stubs (as in case of SOAP), to interact with your server. Its just a normal HTTP/HTTPS call on which you send your data and the result is sent to you either in the form of JSON or XML depending on the request.

Now one thing that really bothers for all developers is that how will you document your api so that the client have clear cut understanding how to call an api and what kind of data he will get back as the response. For documenting the REST apis number of libraries are there that gives you the functionality, out of which some of the names are :
  1. Swagger
  2. ApiDocs
Now there are many more but these 2 are mainly used in the Node js community.

Today we are mainly going to concentrate on ApiDocs although Swagger is more popular but when I wanted to do the documentation I felt ApiDocs much more easy to understand and maintain as compared to Swagger.

This is because the Swagger forces you to learn a whole new way of creating the documentation like you have to write the info of documentation in YAML language which in turn is translated in to JSON by the Swagger API and that JSON is then utilized to show the HTML view of the documentation.

So coming back to the ApiDocs, let me tell you the system works very simple. You create a rest layer in a folder named rest (most of the times, there is a rest folder where you write the code for routes).

So what you can do is that you write the normal comments in a special format that is given by ApiDocs and then ask ApiDocs plugin to generate the documentation by the help of the these comments to a specific folder.

The only draw back which I felt is not that important is that ApiDocs doesn't provide the demo caller functionality as in case of Swagger that means you can't test the call from the ApiDoc UI itself.

Lets start coding. :D 
  1. Okay so first of all you have to install the ApiDoc module. 
    • npm install --save apidoc
  2. Now this will install the apidoc in a local mode and believe me its more than sufficient although the documentation of ApiDoc say that you should have to install it globally but its ok to install in locally.
  3. Configure the ApiDoc. 
    • For this there are 2 modes either you can give a json file individually and then tell the ApiDoc to pick this json file of you can give the config in package.js file (the same file which is the npm file).
    • Config looks like :
      "apidoc": {
          "name": "Name",
          "version": "1.0.0",
          "description": "Name API's",
          "title": "Title",
          "url": "http://localhost:3555/api/1.0.0"
        }
    • The name shown in the UI in the top is Name, Version is 1.0.0, title as Title, and the base Url is http://localhost:3555/api/1.0.0
  4. You have to put the comments in a specific format like:
         /***
         * @apiDefine ServerError
         * @apiErrorExample 500:
         * HTTP/1.1 500 Server Error
         * {
         *      "statusCode": 500,
         *      "status": false,
         *      "message": "Internal Server Error.",
         *      "data" : "{Message with the Internal server error}"
         * }
         */
         /***
         * @api {get} /users/:userId Get Users
         * @apiName GetUserById
         * @apiGroup Users
         * @apiVersion 1.0.0
         *
         * @apiParam {String} userId Users unique ID.
         *
         * @apiSuccessExample {json} Success-Response:
         * HTTP/1.1 200 OK
         *
         * {
         *      "statusCode": 200,
         *      "status": true,
         *      "message": null,
         *      "data": {
         *          "_id": "{userId}",
         *          "userName": "{userName}",
         *          "addresses": {
         *              "user": [
         *                  {
         *                      "_id": "{addressId}",
         *                      "name": "{addressName}",
         *                      "addressLine1": "{addressLine1}",
         *                      "addressLine2": "{addressLine1}",
         *                      "street": "{street}",
         *                      "city": "{city}",
         *                      "country": "{countyCode}",
         *                      "pincode": "{pincode}"
         *                  }
         *              ]
         *          }
         *      }
         * }
         *
         * @apiUse ServerError
         */
         router.get("/:userId", function(request, response){
            //rest handler
        });
  5. Now after this if we have to generate the documentation.
    • base_directory_of_your_project/node_modules/.bin/apidoc -i folder_with_files_commented/ -o folder_to_get_output_to
    • -i -> Input Parameter
    • -o -> output parameter
Now this is just an example, that is self explanatory. 

The command in step 5 will generate the html files with the documentation on the basis of the special comments you have given to the rest layer.

FYI: 

  1. In order to automate the building process you can use gulp tasks.
  2. The demo of the apidocs is available here, please clone and read the README.md in order to get the taste of APIDOCS.

Hope you guys liked it, happy coding
:D

1 comment: