Swagger API请求In Express的自动验证



如果这个问题看起来很明显,请原谅,但我是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);
     }
});

我相信有,但很难找到,或者我没有找到正确的东西。

是的,你可以这样做。有一个发电机项目正是这样做的,没有任何压力。点击这里:

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

例如,要将POST请求的body验证为/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代码中,为POST到/examples 创建一个路由处理程序

例如

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

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

这里有一个中间件示例,用于根据swaggerjson模式验证传入响应。这只是一个概念的证明,但它可能会为你指明正确的方向:

swaggerjson模式中间件示例

最新更新