Streamlining API Development with Swagger

 

What Is Swagger?

 

Swagger allows you to describe the structure of your APIs so that machines can read them. The ability of APIs to describe their own structure is the root of all awesomeness in Swagger. Swagger is an important tool for web development companies as it allows them to design, build, and test APIs in a standardized way.

Why is it so great? Well, by reading the API’s structure, we can automatically build beautiful and interactive API documentation. We can also automatically generate client libraries for the API in many languages and explore other possibilities like automated testing. Swagger does this by asking your API to return a YAML or JSON that contains a detailed description of your entire API.

 

Applications of Swagger

 

  1. API Documentation: Swagger helps to generate and maintain API documentation in a standard and easy-to-read format.
  2. Interactive Testing: Swagger provides an interactive interface for testing APIs, making it easier for developers to quickly test and debug their APIs.
  3. Code Generation: Swagger can generate code in various programming languages such as Java, Python, C#, etc., reducing the time and effort needed for manual coding.
  4. Validation: Swagger can validate the API request and response payloads, ensuring that the API is functioning as expected.
  5. Version Management: Swagger enables easy management of API versions, allowing developers to make changes to the API without breaking existing integrations.
  6. Collaboration: Swagger facilitates collaboration between developers, business users, and other stakeholders in the API development process.
  7. Security: Swagger supports authentication and authorization mechanisms, ensuring secure access to the API.
  8. Integration: Swagger integrates easily with other tools and platforms, such as CI/CD pipelines, API gateways, and API management tools.
  9. User-friendly Interface: Swagger provides a user-friendly interface for API documentation and testing, making it accessible to a wide range of users.
  10. Open-Source: Swagger is an open-source tool, making it accessible and cost-effective for small and large organizations alike.

How we can start implementing in Node.js?

 

       Install the following npm packages in your node project: swagger-jsdoc, swagger-ui-express, and swagger-ui-express. These packages will help configure Swagger UI. This one express-basic-auth the static authentication swagger ui.

 

npm i express-basic-auth swagger-jsdoc swagger-ui-express

After installing express-basic-auth, swagger-jsdoc, and swagger-ui-express, you can include these packages in app.js: express-basic-auth, swagger-jsdoc, and swagger-ui-express.

const swaggerJsdoc = require("swagger-jsdoc");

const swaggerUi    = require("swagger-ui-express");

const basicAuth    = require('express-basic-auth');

 

After including these packages in app.js: express-basic-auth, swagger-jsdoc, and swagger-ui-express, you need to configure the swagger definition. For example, this would be done like this.

 

                        const swaggerDefinition = {

  swagger: "2.0",

  info: {

    version: "1.0.0",

    title: "SSF Automation API UI",

    description: "SSF Automation API UI",

    contact: {

      email: "susanta.das@bluehorse.com"

    },

    license: {

      name: "Apache 2.0",

      url: "http://www.apache.org/licenses/LICENSE-2.0.html"

    },

  },

  host: BASEURL + ':' + port, // base url with port

  basePath: '/api/v1', //api bash path

  securityDefinitions: { //this for authorization definition which is passed in the header

    bearerAuth: {

      type: 'apiKey',

      name: 'token',

      scheme: 'bearer',

      in: 'header',

    },

  },

  security: [{ bearerAuth: [] }], //this for authorization variable for security

  tags: [{ // tag use for group of apis

    name: "Beam Master",

    description: "API for Beam Master in the system"

  }],

  schemes: ["http","https"],

};

 

After configuring the Swagger definition, we need to configure Swagger options. In Swagger options, you need to add the Swagger definition and API routes. This would be done like this.

                        const options = {

  swaggerDefinition,

  apis: ["./routers/api.route.js"],

};

Now we can define a URL for the Swagger UI and assign the Swagger UI and protect it with a static authentication. This is done like this. So the user name and password are gotten from the end, or else set static.

 

app.use("/api-docs", basicAuth({users: { [process.env.USERNAMESUI]:process.env.PASSWORDSUI }, challenge: true }), swaggerUi.serve, swaggerUi.setup(specs));

or 

app.use("/api-docs", basicAuth({users: { 'admin':'admin#321123' }, challenge: true }), swaggerUi.serve, swaggerUi.setup(specs));

 

Those things add before app. listen

 

                                app.listen(port, () => {

                                    console.log(`Server is running on ${app.locals.baseurl}`);

});

So we can see that first, we need to authenticate. Without authentication, we cannot see the Swagger UI. This is because it is protected by the express-basic-auth (username and pass word).

So we can see Swagger ui there show [ Base URL: localhost:3016/api/v1 ], Schemes dropdown, authorizations for header key, all tag.

Now our swagger ui ready. But no API UI there so, now we can start how to write API UI. In api route  page.

api route page we have to implement get method api first. So let start get api using passing parameter for swagger ui.

/**

 * @swagger

 * /view-site/{id}:

 *  get:

 *      tags:

 *        - Site

 *      summary: View Site

 *      consumes:

 *          - application/json

 *      parameters:

 *        - name: id

 *          in: path

 *          description: Site id

 *          type: integer

 *          required: true

 *      responses:

 *          200:

 *              description: User Details

 *       

*/

 

api route page we have to implement post Method api. So let start post method api using passing object in body for swagger ui.

 

/**

 * @swagger

 * /login:

 *  post:

 *      tags:

 *        - User

 *      summary: Login User

 *      consumes:

 *          - application/json

 *      parameters:

 *        - in: body

 *          name: body

 *          description: User object

 *          schema:

 *              type: object

 *              required:

 *                  - clientEmail

 *                  - clientPassword

 *              properties:

 *                  clientEmail:

 *                      type: string

 *                  clientPassword:

 *                      type: string

 *      responses:

 *          200:

 *              description: User Details

 *       

*/

api route page we have to implement put Method api. So let start put method api using passing object in body for swagger ui.

 

/**

 * @swagger

 * /update-site:

 *  put:

 *      tags:

 *        - Site

 *      security:

 *          - bearerAuth: []

 *      summary: Update Site

 *      consumes:

 *          - application/json

 *      parameters:

 *        - in: body

 *          name: body

 *          description: Site Data object

 *          schema:

 *              type: object

 *              required:

 *                  - id

 *                  - orgId

 *                  - projectId

 *                  - sourceProjectId

 *                  - name

 *                  - description

 *                  - domainName

 *              properties:

 *                  id:

 *                      type: integer

 *                  orgId:

 *                      type: integer

 *                  projectId:

 *                      type: integer

 *                  sourceProjectId:

 *                      type: integer

 *                  name:

 *                      type: string

 *                  description:

 *                      type: string

 *                  domainName:

 *                      type: string

 *      responses:

 *          200:

 

 *              description: User Details

 *       

*/


api route page we have to implement delete Method api. So let start delete method api using passing object in body for swagger ui.

/**

 * @swagger

 * /delete-site:

 *  delete:

 *      tags:

 *        - Site

 *      summary: Delete Site

 *      consumes:

 *          - application/json

 *      parameters:

 *        - in: body

 *          name: body

 *          description: Site Data object

 *          schema:

 *              type: object

 *              required:

 *                  - id

 *              properties:

 *                  id:

 *                      type: integer

 *      responses:

 *          200:

 *              description: User Details

 *       

*/

CONCLUSION

Swagger is an open-source software framework that is widely used in web development for creating, documenting, and consuming RESTful APIs (Application Programming Interfaces). It provides the ability to generate code in multiple programming languages, test API endpoints, and automatically generate API documentation. Additionally, Swagger provides security features that can help to protect the data of web development companies' clients.

 

We Serve clients globally in diverse industries

Stay Upto Date With Our Newsletter.