2

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

3
  • are you using swagger.json file? Commented Feb 20, 2020 at 6:04
  • Hi, no for now I have hard coded this in my app.js Commented Feb 20, 2020 at 6:28
  • Try fixing your apis path, see stackoverflow.com/a/62741528/14281832 (path of apis property has to be relative path from root). Also if anyone stumbles here, check your jsdoc formatting, proper formatting of the jsdoc is important. Commented Apr 14 at 7:02

1 Answer 1

6

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!

Sign up to request clarification or add additional context in comments.

4 Comments

Hi Parveen, many thanks! This worked! In the end very easy, isn't it. My fault was thinking that the swagger.json would be automatically generated by swagger, but it isn't. Thanks again.
it's ok. Cheers!
Do you know any tool that can generate the swagger.json? thanks?
I would expected swagger-jsdoc to replace the need for swagger.json completely. This answer does the opposite: completely removing swagger-jsdoc in favor of swagger.json. It works, but it shouldn't be an accepted answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.