本文介绍了如何根据 Ruby 的 OpenApi 规范验证 JSON 有效负载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我根据 jsonapi.org 指南构建了 HTTP 请求负载:

I have HTTP request payload structured according to jsonapi.org guidelines:

{
  "data": {
    "type": "employee",
    "attributes": {
      "firstName": "John",
      "lastName": "Doe",
    }
  }
}

然后我有这个有效负载的OpenApi规范(yaml):

then I have OpenApi specification (yaml) of this payload:

employee:
  type: object
  required: [data]
  properties:
    data:
      type: object
      properties:
        type:
          type: string
          enum: [employee]
        attributes:
          type: object
          required: [firstName, lastName]
          properties:
            firstName:
              type: string
              example: 'John'
            lastName:
              type: string
              example: 'Doe'

我想要的是根据规范(来自 Ruby/Rails)验证有效负载.

and what I want is to validate the payload against the specification (from Ruby/Rails).

存在 openapi3_parser gem,但似乎只能验证规范,不是实际的有效载荷.

there exist openapi3_parser gem, but that one seems to be capable only to validate the specification, not the actual payload.

然后,有 jsonapi.org 有效载荷反序列化器,但那些没有似乎完全不关心 OpenApi 的正式规范.

then, there are jsonapi.org payload deserializers, but those do not seem to take care about OpenApi formal specification at all.

我使用 OpenApi 来描述有效负载,因为我通过 Swagger 免费获得了 http API 文档.

I use OpenApi to describe the payload becuase I get http API docs for free via Swagger.

推荐答案

可以通过使用json-schema,例如:

errors = JSON::Validator.fully_validate(schema, payload)

(它对我来说使用 json-schema gem 2.8.1,模式本身是用 openapi v 2.0 编写的)

(it is working for me with json-schema gem 2.8.1, schema itself is written in openapi v 2.0)

这篇关于如何根据 Ruby 的 OpenApi 规范验证 JSON 有效负载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 10:52