Swagger With Nodejs
Swagger is an Interface Description Language for describing RESTful APIs expressed using JSON. Swagger is used together with a set of open-source software tools to design, build, document, and use RESTful web services. Swagger includes automated documentation, code generation, and test-case generation.
For connecting swagger with nodejs we have to use two npm packages:-
"swagger-jsdoc": "6.1.0",
"swagger-ui-express": "^4.1.6",
Swagger UI Express
This module allows you to serve auto-generated swagger-ui generated API docs from express, based on a swagger. json file. swagger-jsdoc: Allows you to markup routes with jsdoc comments. It then produces a full swagger yml config dynamically, which you can pass to this module to produce documentation.
Swagger Jsdoc
The options object is used by swagger-jsdoc to produce an OpenAPI specification in a variable called swaggerSpec. This specification is equivalent to the swagger. json or swagger. yaml file normally used by Swagger UI for creating docs pages.
To apply swagger, Open app.js and import these packages;-
const swaggerUi = require('swagger-ui-express');
const swaggerJsdoc = require("swagger-jsdoc");
Here we need to define the swagger option
var options = {
definition: {
openapi: "3.0.0",
info: {
title: "Swagger",
version: "0.1.0",
description:
"CRUD Api documentation for node service",
},
// You can remove this if you don't want bearerAuth
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
}
}
},
security: [{
bearerAuth: []
}],
servers: [
{
url: "http://localhost:3000",
},
],
},
apis: ["./routes/details.js"],
};
And pass the option variable into swagger doc
const specs = swaggerJsdoc(options);
Now Adding a middleware for the swagger path
app.use(
"/api-docs",
swaggerUi.serve,
swaggerUi.setup(specs,{ explorer: true })
);
We have to define some swagger annotation before every API
/**
* @swagger
* /api/data:
* get:
* description: Returns Some Data
* tags: [Task]
* parameters:
* - in: query
* name: userId
* type: number
* required: true
* - in: query
* name: date
* type: number
* required: true
* responses:
* 200:
* description: SUCCESS
*/
app.get("/api/data", function(req, res, next) {
});