我正在使用 grape构建 REST API,我在使用 params
选项时遇到了一些问题。
这是我执行 POST 请求的方式:
# Curl Request
# curl -X POST -H "Content-Type:application/json" 0:9292/v1/articles -d '{"title":"hello","body":"world"}'
# {"error":"article is missing"}
# curl -X POST -H "Content-Type:application/json" 0:9292/v1/articles -d '{"article":{title":"hello","body":"world"}}'
# {"error":"article is invalid"}
如您所见,如果我省略 article
它会失败 article missing
,如果我输入 article
它会失败 article invalid
.
这是代码,我正在使用 grape-entity。
# Entity
module API
module Entities
class Article < Grape::Entity
expose :title, documentation: { type: 'string', desc: 'Title' }
expose :body, documentation: { type: 'string', desc: 'Body' }
end
end
end
# API
desc "Create an article"
params do
requires :article, type: API::Entities::Article, documentation: { eg: "aklsdfj" }
end
post '/articles' do
puts params
article = Article.create(params(:title, :body))
represent(article, env)
end
# Add Swagger Docs
add_swagger_documentation mount_path: 'api/doc',
api_version: 'v1',
markdown: GrapeSwagger::Markdown::KramdownAdapter,
hide_documentation_path: true,
base_path: Application.config.base_path,
models: [API::Entities::Article]
特别是问题是由 params
block 引起的,它需要
:article
API:Entities::Article
.
另请注意,我正在使用 add-swagger-documentation
,并且此代码
生成正确的 swagger 文档,因此解决方案必须是
与 Swagger 完全兼容。 params
的正确用法是什么
阻止而不冒犯 Swagger 。
最佳答案
我不确定您要在这里完成什么。我猜您想以一种接受 JSON 的方式更改您的 post 方法:
{ attribute1: value, attribute2: value }
代替
{ article: { attribute1: value, attribute2: value } }
在这种情况下,您必须将 params block 更改为类似这样的内容
params do
requires :attribute1, type: String, documentation: { eg: "aklsdfj" }
requires :attribute2, type: String, documentation: { eg: "aklsdfj" }
end
代替
params do
requires :article, type: API::Entities::Article, documentation: { eg: "aklsdfj" }
end
上面的 params block 需要一个包含文章属性的 JSON,该属性由实体 API::Entities::Article 中定义的每个属性组成。
事实上,Grape 不接受实体对象作为参数的类型。
关于ruby - 如何使用与 Swagger 兼容的参数 block 对 Grape REST API 进行 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27189803/