如何使用快速JSON api序列化器用Rswag定义复杂的JSON响应



我得到rswag设置,所以我可以很容易地为我的rails API生成文档。我已经使用gem 'jsonapi-serializer'来构建响应,它工作得很好。

然而,我似乎不知道如何在rswag定义的schema部分定义响应。

现在我有这个:

# spec/integrations/customer_spec.rb
get 'Retrieves a customer' do
tags 'Customers'
produces 'application/json'
parameter name: :id, in: :path, type: :string
security [api_key: []]
response '200', 'customer found' do
schema type: :object,
properties: {
id: { type: :integer },
name: { type: :string },
email: { type: :string },
address: { type: :json }
},
required: [ 'id' ]
let(:id) { customer.public_id }
run_test!
end

我知道如何像上面的代码样例那样定义简单的响应,但是我不确定如何定义更复杂的响应。

下面是一个示例响应体:

"data"=>
{"data"=>
{"id"=>"cust_29od5g7d8aPuPXzb3JHfQCpzYjb",
"type"=>"customer",
"attributes"=>{"name"=>"Pouros, Zboncak and Bernhard", "phone"=>"+13105552474", "email"=>"kathrin@skiles.com", "address"=>"13949 Janey Village, Farrellmouth, NH 73307-1612", "stripe_customer_id"=>nil, "permissions"=>{"data"=>[]}},
"relationships"=>{"subscriptions"=>{"data"=>[]}, "products"=>{"data"=>[]}, "customer_quotas"=>{"data"=>[]}}}}}

现在,我得到这个错误。我不确定如何构建模式以识别id在哪里:

Rswag::Specs::UnexpectedResponse:
Expected response body to match schema: The property '#/' did not contain a required property of 'id' in schema 586f23d3-4484-5ad4-ad61-154265f7292b
...

我以前没有使用该gem进行开发,但这是一个JSON模式验证错误,表明响应与您定义的模式不匹配。您粘贴的响应是ruby哈希(不是JSON),并且缺少大括号,因此很难知道您在粘贴时是否犯了错误,或者您的响应是否真的有两个嵌套的"data"级别;如果这不是一个错误,那么像这样的错误的可能原因是规范在不存在的键级别寻找'id'(即,哈希的唯一键是'data'的级别)。

gem在README的Rspec DSL部分中提供的第一个例子和你的模式定义都表明它期望响应的顶级键等于模式属性中定义的键(意思是去掉前两个data级别,它可能会工作)。如果这是一个错别字场景,但您的响应必须包含data根密钥,那么您需要调整模式或遵循DSL中的示例,以不同的方式解析JSON并验证结构。

我找到了Swagger。IO文档(例如,https://swagger.io/docs/specification/describing-responses/, https://swagger.io/docs/specification/data-models/dictionaries/, https://swagger.io/specification/)非常有用;他们也有一些工具,比如https://inspector.swagger.io/builder。API客户端工具(如Insomnia或Postman)中的API构建器功能也可以真正帮助您使用OpenAPI语法,以确定哪些有效,哪些无效。

我还建议查看gem的源代码——特别是规范文件和示例应用程序;这些文件通常包含在自述文件中找不到的语法和用法示例。

最新更新