首页 文章

在Express中自动验证Swagger API请求?

提问于
浏览
1

对不起,如果这个问题看起来很明显,但我是Express,Node和Swagger的新手 .

我为API编写了一个Swagger规范 .

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

类似于:

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

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

2 回答

  • 0

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

    swagger-json-schema-middleware-example

  • 0

    是的,你可以这样做 . 有一个发电机项目正是这样,表达无压力 . 得到它here

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

    例如,要将 POSTPOST 请求验证为 /examples ,您可以执行以下操作:

    编辑 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代码中为/ examples创建 POST 的路由处理程序

    例如

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

    注意:仅包含处理程序逻辑 . 身体验证将自动处理 .

相关问题