Using node to generate swagger interface document

In the development process, when we request an interface, we usually have an interface document in the background, which is convenient for us to consult. Today, we use node to generate an interface document of our own, and know how the interface document comes from.

  • This is not about how to install node, how to write interface, and how to write interface document directly. If you want to see how to use node interface, you can move to This blog
  • I have uploaded the final case to GitHub at You can download it and have a look

Install the swagger plug-in

cnpm install  express-swagger-generator

Import in your app.js file

const expressSwagger = require('express-swagger-generator')(app)

Use, where files is the path of your api interface file. Here is the js file in the api under router

  • The host port number should be consistent with the node service you started
  • Address accessed by route
  • files api interface address
let options = {
  swaggerDefinition: {
    info: {
      description: 'This is a sample server',
      title: 'Swagger',
      version: '1.0.0'
    host: 'localhost:3000',
    basePath: '/',
    produces: ['application/json', 'application/xml'],
    schemes: ['http', 'https'],
    securityDefinitions: {
      JWT: {
        type: 'apiKey',
        in: 'header',
        name: 'Authorization',
        description: ''
  route: {
    url: '/swagger',
    docs: '/swagger.json' //swagger file api
  basedir: __dirname, //app absolute path
  files: ['./router/api/*.js'] //Path to the API handle folder

Defined in your api interface file

  • @Address of route request interface
  • @param request parameters. How many parameters are written? username.query.requiredrequired means this is required
  • The most important thing is that these two @ route and @ param must be written in this format
  • userRegisterPost needs to throw this out, and its api can receive it.
 * User information registration
 * @route POST /api/users/register
 * @group user - Operations about user
 * @param {string} username.query.required - enter one user name
 * @param {number} password.query.required - Please input a password
 * @param {string} email.query.required - Please enter a legal email
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error

exports.userRegisterPost = function(req, res) {
  // Check whether the mailbox is registered
  res.setHeader('Content-Type', 'application/json;charset=utf-8')
    .then(user => {
      if (user) {
        // The mailbox has been registered
        return res.status(400).json('Mailbox is already registered')
      } else {
        // Generate default Avatar
        const avatar = gravatar.url(, {
          s: '200',
          r: 'pg',
          d: 'mm'
        const newUser = new User({
          username: req.query.username,
          password: req.query.password,
        // Encrypt password
        bcrypt.genSalt(10, function(err, salt) {
          bcrypt.hash(newUser.password, salt, (err, hash) => {
            if (err) {
              throw err
            // Cipher encryption
            newUser.password = hash
              .then(user => {
              .catch(err => {
    .catch(err => {

After defining the interface document, you need to use the
Introduce routing model

const user = require('./router/api/user')

Using router Middleware

  • api / users / register should be consistent with my interface api path'/api/users/register', (req, res) => {
  user.userRegisterPost(req, res)

When we visit http://localhost:3000/swagger, we can see the interface

By sending the request, you can see the result of our request

So far as our overall effect is concerned, we only need to add models and routes to automatically generate interface document descriptions

76 original articles published, 66 praised, 1664 visited
Private letter follow

Tags: JSON github git xml

Posted on Tue, 10 Mar 2020 23:01:13 -0700 by the_last_tamurai