【问题标题】:Automatic Validation of Swagger API Request In Express?在 Express 中自动验证 Swagger API 请求?
【发布时间】:2023-03-22 11:24:01
【问题描述】:

如果这个问题看起来很明显,请原谅,但我是 Express、Node 和 Swagger 的新手。

我为 API 编写了 Swagger 规范。

是否有工具可以将请求与 Swagger.json 文件一起传递给 Swagger 记录的 API,以验证所需参数是否存在、这些参数的枚举值是否正确等?

类似于:

validator.validate ("./swagger.json", req, function (req, res, err) {
     if (err) {
       res.status('400').send(err.message());
     }
     else {
       // Call my controller
       swaggerController(req, res);
     }
});

我相信有,但很难找到,或者我不是在寻找正确的东西。

【问题讨论】:

    标签: node.js express swagger


    【解决方案1】:

    是的,您可以这样做。 有一个生成器项目可以做到这一点,表达无压力。得到它here

    使用它时,每个 API 请求都将根据您在 Api.yaml 中提供的 Swagger API 描述进行验证。

    例如,要验证 POST/examples 的请求的 body,您可以执行以下操作:

    编辑Api.yaml

    ...
    definitions:
      # define the example body i.e. require the property name
      ExampleBody:
        type: object
        title: example
        required:
          - name
        properties:
          name:
            type: string
            description: The example name
    paths:
      # define your /examples POST endpoint
      # reference the ExamplesBody definition from above
      /examples:
        post:
          tags:
            - Examples
          description: Create a new example
          parameters:
            - name: example
              in: body
              description: number of items to skip
              required: true
              schema: 
                $ref: "#/definitions/ExampleBody"
          responses:
            200:
              description: Returns all examples
    ...
    

    接下来,在 Node.js 代码中为 POSTs 创建一个路由处理程序到 /examples

    例如

    app.post('/examples', function (req, res) { /* your handler logic here */ /* no need to validate the request payload. it will be done automatically */ });

    注意:仅包含您的处理程序逻辑。正文验证将自动处理。

    【讨论】:

      【解决方案2】:

      这是一个中间件示例,用于根据 swagger json-schema 验证传入响应。只是一个概念证明,但它可能会为您指明正确的方向:

      swagger-json-schema-middleware-example

      【讨论】:

        猜你喜欢
        • 2017-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-02
        • 2019-10-09
        • 2021-12-03
        • 2021-08-11
        • 2018-08-03
        相关资源
        最近更新 更多