创建 Node REST API 文档

news2024/10/7 10:13:14

为自己开发的 Node REST API 生成文档,基本有两种方法:

1 极简版

此方法就是自己写一个文件,记录 API,不需要安装额外的 package,然后 app.js 增加一个 route 然后从浏览器查看这个文件就可以。
步骤如下:

1.1 在工程目录下新建文件 ./docs/apiDocs.json

此文件是自己手写的文件,记录了后端的各种 route,例如可以像下面这样写:

{
  "/": "api docs",
  "/signup": "sign up",
  "/signin": "sign in",
  "/signout": "sign out",
  "/users": "get all users",
  "/user/:userId": "get/update/delete user",

  "/posts": "get all posts",
  "/post/new/:userId": "create new post",
  "/post/by/:userId": "get posts by user",
  "/post/:postId": "update/delete post"
}

1.2 app.js 增加如下代码:

// for api docs
app.get("/api", (req, res) => {
  fs.readFile("docs/apiDocs.json", (err, data) => {
    if (err) {
      res.status(400).json({
        error: err,
      });
    }
    const docs = JSON.parse(data);
    res.json(docs);
  });
});

假定 server 在 80 端口监听,然后打开浏览器 localhost/api,可以看到如下界面,这就是 API 文档,就是前面的 apiDocs.json

在这里插入图片描述

2 详尽版,使用 Swagger

使用 Swagger 生成的 API 文档内容更丰富,界面也十分美观,还可以实现 postman 的功能测试 API,但步骤也更繁琐。

2.1 单独使用 swagger-ui-express

代码示例:

const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

其中的 swagger.json 就相当于极简版中的 apiDocs.json, 内容和格式参照 Swagger 文档中的 Basic Structure,然后根据自己的 Node 项目内容修改,以下是从别处copy来的两份 sample swagger.json:

2.1.1 swagger.json 例 1

{
  "swagger": "2.0",
  "info": {
    "description": "This is a sample video tutorial",
    "version": "1.0.0",
    "title": "Tutorial",
    "termsOfService": "http://swagger.io/terms/",
    "contact": {
      "email": "tutorial@gmail.com"
    },
    "license": {
      "name": "Apache 2.0",
      "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
    }
  },
  "host": "127.0.0.1:8000",
  "basePath": "/user",
  "tags": [
    {
      "name": "Login",
      "description": "Everything about your Login",
      "externalDocs": {
        "description": "Find out more",
        "url": "http://swagger.io"
      }
    },
    {
      "name": "Record",
      "description": "Operations about record",
      "externalDocs": {
        "description": "Find out more about our store",
        "url": "http://swagger.io"
      }
    }
  ],
  "schemes": ["https", "http"],
  "paths": {
    "/login": {
      "post": {
        "tags": ["Login"],
        "summary": "Create login",
        "description": "This can only be done by the logged in user.",
        "operationId": "createLogin",
        "produces": ["application/json"],
        "parameters": [
          {
            "in": "body",
            "name": "body",
            "description": "Created user object",
            "required": true,
            "schema": {
              "$ref": "#/definitions/Login"
            }
          }
        ],
        "responses": {
          "default": {
            "description": "successful operation"
          }
        }
      }
    },
    "/addRecord": {
      "post": {
        "security": [
          {
            "Bearer": []
          }
        ],
        "tags": ["Record"],
        "summary": "Create record",
        "description": "This can only be done by the logged in user.",
        "operationId": "createrRecord",
        "produces": ["application/json"],
        "parameters": [
          {
            "in": "body",
            "name": "body",
            "description": "Created user Record",
            "required": true,
            "schema": {
              "$ref": "#/definitions/createRecord"
            }
          }
        ],
        "responses": {
          "default": {
            "description": "successful operation"
          }
        }
      }
    },
    "/getRecord": {
      "get": {
        "security": [
          {
            "Bearer": []
          }
        ],
        "tags": ["Record"],
        "summary": "Get record",
        "description": "This can only be done by the logged in user.",
        "operationId": "getRecord",
        "produces": ["application/json"],
        "responses": {
          "default": {
            "description": "successful operation"
          }
        }
      }
    },
    "/updateRecord/{id}": {
      "put": {
        "security": [
          {
            "Bearer": []
          }
        ],
        "tags": ["Record"],
        "summary": "Update record",
        "description": "This can only be done by the logged in user.",
        "operationId": "updateRecord",
        "produces": ["application/json"],
        "parameters": [
          {
            "in": "path",
            "name": "id",
            "description": "ID of body",
            "required": true,
            "type": "string"
          },
          {
            "in": "body",
            "name": "body",
            "description": "Created user Record",
            "required": true,
            "schema": {
              "$ref": "#/definitions/updateRecord"
            }
          }
        ],
        "responses": {
          "default": {
            "description": "successful operation"
          }
        }
      }
    }
  },
  "securityDefinitions": {
    "Bearer": {
      "type": "apiKey",
      "name": "Authorization",
      "in": "header"
    }
  },
  "definitions": {
    "Login": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "password": {
          "type": "string"
        }
      },
      "xml": {
        "name": "User"
      }
    },
    "createRecord": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "email": {
          "type": "string"
        },
        "city": {
          "type": "string"
        }
      },
      "xml": {
        "name": "User"
      }
    },
    "updateRecord": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "email": {
          "type": "string"
        },
        "city": {
          "type": "string"
        }
      },
      "xml": {
        "name": "User"
      }
    }
  },
  "externalDocs": {
    "description": "Find out more about Swagger",
    "url": "http://swagger.io"
  }
}

如果使用这份文件,假定 node 使用80端口,打开浏览器 localhost/api-docs 可以看到生成的文档界面如下:

在这里插入图片描述

2.2.2 swagger.json 例 2

( 但是这个文件实际格式为 yaml,文件名是 api.yaml)

openapi: 3.0.0
info:
  title: Code Improve API
  description: Optional multiline or single-line description in [CommonMark](http://commonmark.org/help/) or HTML.
  version: 1.0 
servers:
  - url: http://localhost:8081/
    description:  Local server 
  - url: https://prod.com/
    description:  Pre Production server
  - url: https://test.com/
    description:  Production server
components:
  securitySchemes:
    ApiTokenss:        # arbitrary name for the security scheme
          
      type: http
      scheme: bearer
    
    ApiKey:        # arbitrary name for the security scheme
      type: apiKey
      in: header       # can be "header", "query" or "cookie"
      name: apikey
      
paths:
  /users/detail/{userId}:
    get:
      security:
       - ApiTokenss: []
       - ApiKey: []
      summary: Returns a user details by ID.
      parameters:
        - name: userId
          in: path
          required: true
          description: Parameter description in CommonMark or HTML.
          schema:
            # type : integer
            # format: int64
            type: string
            example: "Users String"
            minimum: 1
      responses: 
        '200':
          description: OK
  

  paths:
  /users/list:
    post:
      tags:
        - User List API 
      summary: Returns a user list. 
      description: <b> Request :- </b> <br /> <br />
              <b> page_no* </b>  is required <br /> 
              <b> status* </b>  is required <br /> 
              <b> type* </b>  is required <br /> 

      parameters:
        - in: query
          name: month_year
          schema:
            #type: integer
            example: 2022-10        
      post:
      requestBody:
        required: true
        content:
          multipart/form-data:
           #application/json:
            schema:
              type: object
              properties: 
                page_no:         
                  type: integer
                  example: 1  
                type:       
                  type: string
                  example: "A" 
                status:
                  type: integer
                  example: 0
                fileName:
                  type: string 
                  format: binary
         
      responses:
        '200':
          description: A user object. 
        '400':
          description: The specified user ID is invalid (not a number).
        '404':
          description: A user with the specified ID was not found.
        default:
          description: Unexpected error

因为此文件是 YAML 格式,需要安装 package: npm i yamljs 让 Swagger 读取, app.js 修改如下:

const YAML = require("yamljs");
const swaggerJSDocs = YAML.load("./api.yaml");
const swaggerUi = require("swagger-ui-express");
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerJSDocs));

与之对应的浏览器 localhost/api-docs 界面:

在这里插入图片描述

2.2 使用 swagger-ui-express + swagger-jsdoc

此方法不需要 wagger.json 文件,但是代码里每个route 前面都需要加如下格式的注释,让 swagger 提取以生成文档。

/** 
*@swagger
* /books
* something.............
**/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/502603.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

酷家乐x极盾科技:“智能安全决策平台”助力日均十亿级日志分析

企业网络环境中每天都会产生大量的网络日志&#xff0c;还有工作站&#xff0c;服务器&#xff0c;路由器和防火墙等网络设备中的日志对网络安全的提升具有重要意义。充分利用好它们可以帮助企业及时发现潜在的风险和安全漏洞&#xff0c;把网络环境中存在的威胁扼杀在摇篮中。…

10年IT老兵亲述SpringCloud开发从入门到实战文档

前言 首先给大家看一张图&#xff0c;不知道图上这些springcloud的技术知识点&#xff0c;大家是否都精通而灵活运用了呢&#xff1f; 如果没有精通灵活运用的话&#xff0c;小编将用此文来带大家一步步来深入学习这些技术知识&#xff0c;接下来将从Spring Boot微框架搭建、S…

Makefile及cmake学习

Makefile及cmake学习 1. g&#xff0c;gcc以及cpp的区别2. Makefile2.1 介绍一个例子2.2 避免头文件重复包含的方法2.2.1 宏定义2.2.2 #pargma once 2.3 使用Makefile编译文件2.3.1 手动编译2.3.2 Makefile编译-版本12.3.3 Makefile编译-版本22.3.4 Makefile编译-版本32.3.5 Ma…

【三维几何学习】网格简化-ModelNet10

网格简化-ModelNet10 引言一、网格的简化1.1 水密网格的简化可视化1.2 非水密网格的简化可视化1.3 核心代码 二、ModelNet10数据集简化三、展望 引言 计算机算力有限&#xff0c;特别是在深度学习领域&#xff0c;撇开网格的输入特征计算&#xff0c;现有条件很难直接训练测试…

JS逆向 -- 某联盟登录密码分析

一、输入账号密码 账号&#xff1a;15836353612 密码&#xff1a;123456 二、F12打开开发者工具&#xff0c;抓包分析&#xff0c;password被加密提交了 三、全局搜索password&#xff0c;定位到关键JS文件&#xff0c;下断调试 四、断下来后&#xff0c;查看formDate的值&…

AspNetCore中的中间件详解【超详细】

1 什么叫做中间件&#xff1f; ASP.NET Core处理请求的方式看做是一个管道&#xff0c;中间件是组装到应用程序管道中用来处理请求和响应的组件。通常是一个可重用的类方法 每个中间件可以&#xff1a; &#xff08;1&#xff09;选择是否将请求传递给管道中的下一个组件。 &a…

第一行代码 第七章 内容提供器

第七章 内容提供器 在上一章中我们学了Android数据持久化的技术&#xff0c;包括文件存储、SharedPreferences存储以及数据库存储。使用这些持久化技术所保存的数据都只能在当前应用程序中访问。 虽然文件和SharedPreferences存储中提供了MODE_WORLD_READABLE和MODE_WORLD_WR…

UU跑腿“跑男失联”:同城即配服务赛道商业逆袭难?

五一假期&#xff0c;人们纷纷走出家门&#xff0c;要么扎堆奔向“远方”&#xff0c;要么、享受本地烟火气息。 据文化和旅游部数据中心测算&#xff0c;劳动节假期&#xff0c;全国国内旅游出游合计2.74亿人次&#xff0c;同比增长70.83%。 五一假日的郑州东站 面对人山人海…

树莓派(主)与STM32(从)使用SPI通信

1.实验目的 2.SPI 简介 SPI&#xff08;Serial Peripheral Interface&#xff0c;串行外设接口&#xff09;是Motorola公司提出的一种同步串行数据传输标准 2.1 接口 SPI接口经常被称为4线串行总线&#xff0c;以主/从方式工作&#xff0c;数据传输过程由主机初始化。如图1…

【干货集】PCBA板边器件布局重要性

电子元器件在PCB板上的合理布局&#xff0c;是减少焊接缺点的极重要一环&#xff01;元器件要尽可能避开挠度值非常大的区域和高内应力区&#xff0c;布局应尽量匀称。 为了最大程度的利用电路板空间&#xff0c;相信很多做设计的小伙伴&#xff0c;会尽可能把元器件靠板的边缘…

机器学习基础知识之数据归一化

文章目录 归一化的原因1、最大最小归一化2、Z-score标准化3、不同方法的应用 归一化的原因 在进行机器学习训练时&#xff0c;通常一个数据集中包含多个不同的特征&#xff0c;例如在土壤重金属数据集中&#xff0c;每一个样本代表一个采样点&#xff0c;其包含的特征有经度、…

《程序员面试金典(第6版)》面试题 16.16. 部分排序(double双指针(多指针),C++)

题目描述 给定一个整数数组&#xff0c;编写一个函数&#xff0c;找出索引m和n&#xff0c;只要将索引区间[m,n]的元素排好序&#xff0c;整个数组就是有序的。注意&#xff1a;n-m尽量最小&#xff0c;也就是说&#xff0c;找出符合条件的最短序列。函数返回值为[m,n]&#xf…

什么是平台工程?如何开始?

平台工程是为开发人员构建和维护自助服务平台的学科。该平台提供了一套云原生工具和服务&#xff0c;帮助开发者快速高效地交付应用。平台工程的目标是通过标准化和自动化软件交付生命周期 (SDLC) 中的大部分任务来改善开发人员体验 (DX)。开发人员可以专注于使用自动化平台编码…

Type-C PD充电器诱骗PD+QC+AFC+FCP全协议快充取电5V9V12V15V20V

Type-C充电器采用的是PD快充协议&#xff0c;支持的电压高&#xff0c;电流大&#xff0c;一般有5V3A、9V3A、12V3A、15V3A、20V5A等等。 因为充电器内部有协议芯片&#xff0c;当外部设备连接时&#xff0c;设备会和充电器进行协议匹配&#xff0c;匹配成功之后&#xff0c;充…

ASEMI代理ADI亚德诺LT8609AJDDM#WTRPBF车规级芯片

编辑-Z LT8609AJDDM#WTRPBF特点&#xff1a; 宽输入电压范围&#xff1a;3.0V 至 42V 超低静态电流突发模式操作&#xff1a; 将 12VIN 调节到 3.3VOUT 时 IQ 为 2.5A 输出纹波 < 10mVP-P 高效 2MHz 同步操作&#xff1a; 1A 时效率为 93%, 12VIN 可获得 5VOUT 最大…

3.1 一个稍微完善的Vue.js响应式系统

前文提要&#xff1a;3.0 响应式系统的设计与实现 1、设置一个合理的effect副作用函数 如上文所说&#xff0c;如果我们直接将简单的effect函数作为副作用函数&#xff0c;如果一个副作用函数不叫effect岂不是找不到了。解决方案也很简单&#xff0c;我们设定一个全局变量用于…

在CRA中配置别名路径并添加别名路径提示

写在前面&#xff1a; 使用React官方脚手架create-react-app[简称CRA]创建react项目&#xff1a;npx create-react-app 项目名称 一、配置别名路径 1.1 写在前面 目的&#xff1a;简化项目中的路径处理&#xff0c;和Vue项目中的类似。 参考文档&#xff1a;自定义CRA的默认…

MySQL基础(十二)数据类型精讲

1. MySQL中的数据类型 类型类型举例整数类型TINYINT、SMALLINT、MEDIUMINT、INT(或INTEGER)、BIGINT浮点类型FLOAT、DOUBLE定点数类型DECIMAL位类型BIT日期时间类型YEAR、TIME、DATE、DATETIME、TIMESTAMP文本字符串类型CHAR、VARCHAR、TINYTEXT、TEXT、MEDIUMTEXT、LONGTEXT枚…

一个日期类深度认识operator符号重载

一&#xff1a;概念 在以前的C语言的学习中,如果我们需要比较两个整数并返回它的结果可以直接用与之相关的符号。例如我们可以直接写成A>B或者A<B一类的&#xff0c;但是它的局限性很大&#xff0c;只能比较内置类型&#xff0c;因为计算可以直接转换成对应的汇编代码进…

如何通过国外主机租用服务提高网站SEO排名?

当今的互联网已经成为了商业和社交活动的主要场所之一。在这个快速变化的数字时代&#xff0c;网站的搜索引擎优化(SEO)排名对于任何企业的成功都至关重要。一个好的SEO排名能够帮助企业吸引更多的访客和潜在客户&#xff0c;增加业务的转化率。而国外主机租用服务可以帮助您优…