Search code examples
node.jsswagger-uiswagger-jsdocs

existing nodeJS and swagger JS docs not working


I have a simple nodeJS project and want to add swagger into it. I have required swaggerUI and swaggerJSDoc

Here is my app.js file.

// requires
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const postsRoutes = require("./routes/posts/posts");
const userRoutes = require("./routes/auth/user");
const swaggerUi = require("swagger-ui-express");
const swaggerJSDoc = require("swagger-jsdoc");

// https://swagger.io/specification/v2/
const swaggerOptions = {
  swaggerDefinition: {
    info: {
      title: "Post API",
      description: "This is a sample Post API",
      contact: {
        name: "Test ",
        url: "http://www.swagger.io/support",
        email: "[email protected]"
      },
      servers: ["http://localhost:3850/"]
    }
  },
  swagger: "2.0",
  apis: ["/backend/routes/posts/posts.js"]
};

const app = express();
let options = {
  explorer: true
};

// swagger
const swaggerDocs = swaggerJSDoc(swaggerOptions);
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocs, options));

// MONGOOSE CONNECT
mongoose
  .connect(
    "mongodb+srv://"
  )
  .then(() => {
    console.log("####-connected to MongoDB");
  })
  .catch(error => {
    console.log("Connection ERROR!", error);
  });

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use("/images", express.static(path.join("backend/images")));

// CORS
app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, PUT, DELETE, OPTIONS"
  );
  next();
});

// ROUTES
app.use("/api/posts", postsRoutes);
app.use("/api/user", userRoutes);

module.exports = app;

I have a couple of routes, also a post.js route file. This file is included in the array, with the definition of swagger.

// express router
const router = express.Router();

// get posts endpoint
/**
 * @swagger
 * /api/posts:
 *  get:
 *   description use to request all posts
 *   responses:
 *   '200':
 *     description: a successful response
 */
router.get("", PostController.getPosts);

Unfortunately I don't see any api definition in the browser. enter image description here Can somebody help me?

Grz, Pete


Solution

  • Its very simple to add swagger in your project. just follow the steps:-

    Install the module "swagger-ui-express"

    npm install swagger-ui-express

    In your app.js file add:-

    const swaggerUi = require('swagger-ui-express');
    const swaggerDocument = require('./swagger.json');
    app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
    

    create swagger.json file (I have added simple login API and classes) looks like:-

    {
        "swagger": "2.0",
        "info": {
          "version": "1.0.0",
          "title": "Parveen App API",
          "description": "Find out how your APIs work",
          "license": {
            "name": "MIT",
            "url": "https://opensource.org/licenses/MIT"
          }
        },
        "host": "localhost:5000",
        "basePath": "/api/v1",
        "tags": [
          {
            "name": "Users",
            "description": "API for users in the system"
          }
    
        ],
        "schemes": [
          "http",
          "https"
        ],
        "consumes": [
          "application/json"
        ],
        "produces": [
          "application/json"
        ],
        "securityDefinitions": {
            "ApiKeyAuth":{
              "type": "apiKey",
              "in": "headers",
              "name": "authorization"
            }
        },
        "paths": {
          "/users/login": {
            "post": {
              "summary": "Login user",
              "tags": [
                "Users"
              ],
              "description": "Login user in system",
              "parameters": [
                {
                  "name": "user",
                  "in": "body",
                  "description": "Login user",
                  "schema": {
                    "$ref": "#/definitions/User"
                  }
                }
              ],
              "produces": [
                "application/json"
              ],
              "responses": {
                "200": {
                  "description": "Login Success",
                  "schema": {
                    "$ref": "#/definitions/User"
                  }
                },
                "401":{
                  "description": "Login details are not valid!!"
                },
                "404":{
                  "description": "Email is not registered!"
                },
                "500":{
                  "description": "User login failed!!"
                }
              }
            }
          }
        },
    
        "definitions": {
    
          "User": {
            "properties": {
              "email": {
                "type": "string"
              },
              "password": {
                "type": "string"
              }
            }
          },
          "userEmail":{
            "properties": {
              "email": {
                "type": "string"
              }
            }
          }
    
    
    
        }
      }
    

    You can add/change swagger.json according to your API.

    Now simply open http://localhost:5000/api-docs

    It will work like a champ!

    Hope this will help!