基于NodeJS + Swagger UI搭建Web API界面

基于NodeJS + Swagger UI搭建Web API界面


前言

Swagger是一个REST APIs文档在线自动生成和测试的框架

一、创建基于NodeJS的Swagger运行目录

shell 复制代码
> mkdir node-swagger
> cd node-swagger
# 初始化node项目
> npm init
# 基于express框架构建
# -S或--save:将包保存为生产依赖,添加到dependencies字段
# -D或--save-dev:将包保存为开发依赖,添加到devDependencies字段
> npm install express -S

二、添加Swagger官方的示例

1.创建public工作目录

shell 复制代码
> mkdir public

2.添加Swagger官方示例

(1)获取示例

shell 复制代码
# 下载示例
> git clone  https://github.com/swagger-api/swagger-ui.git

(2)将dist目录下的所有文件拷贝到/public目录下

3.启动SwaggerUI实例

(1)NodeJS脚本
node-swagger目录下创建index.js文件,内容:

javascript 复制代码
const path = require('path');
const express = require('express');
const app = express();

app.use('/static', express.static(path.join(__dirname, 'public')));
app.listen(3000, () => console.log('hello~'));

打开/public/swagger-initializer.js并修改

javascript 复制代码
window.onload = function() {
  //<editor-fold desc="Changeable Configuration Block">

  // the following lines will be replaced by docker/configurator, when it runs in a docker-container
  window.ui = SwaggerUIBundle({
    url: "https://petstore.swagger.io/v2/swagger.json",
    dom_id: '#swagger-ui',
    deepLinking: true,
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout"
  });

  //</editor-fold>
};

修改为

javascript 复制代码
window.onload = function() {
  //<editor-fold desc="Changeable Configuration Block">

  // the following lines will be replaced by docker/configurator, when it runs in a docker-container
  window.ui = SwaggerUIBundle({
   // url: "https://petstore.swagger.io/v2/swagger.json",
    url:"./app/lvmei-openapi.yaml",
    dom_id: '#swagger-ui',
    deepLinking: true,
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout"
  });

  //</editor-fold>
};

以后就可以替换./app/lvmei-openapi.yaml来迭代更新接口文档

(2)启动脚本

shell 复制代码
> node index.js

node index.js启动会阻塞命令行
使用pm2,采用守护进程模式运行

shell 复制代码
# 安装npm
> sudo npm install pm2 -g -unsafe-perm
# 启动
> pm2 start index.js
# pm2管理的守护进程清单
> pm2 list
# pm2停止所管理的守护进程
> pm2 stop app-id

启动后,可以通过以下地址访问:
http://localhost:3000/static/index.html

三、基于OpenAPI规范提供api文档

打开https://editor.swagger.io/可以打开模版文档

基于模板文档即可修改定制的api文档:

1.将模板文档内容复制到vscode

2.vscode安装扩展《OpenAPI (Swagger) Editor》

3.定制api文档即可

相关推荐
lane_developer9 个月前
swaggerUI不好用,试试这个openapiUI?
前端·后端·接口测试·swagger·openapi·swaggerui·openapiui