Ruby 如何使用与Swagger兼容的params块对Grape REST API进行POST请求

Ruby 如何使用与Swagger兼容的params块对Grape REST API进行POST请求,ruby,rest,swagger,swagger-ui,grape-api,Ruby,Rest,Swagger,Swagger Ui,Grape Api,我正在使用来构建RESTAPI,我在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

我正在使用来构建RESTAPI,我在
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"}
如您所见,如果我省略了
文章
,它将失败
文章丢失
,如果我放置
文章
,它将失败
文章无效

这是代码,我使用的是grape实体

# 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]
#实体
模块API
模块实体
类文章
具体而言,该问题是由
params
块引起的,它
需要
类型为
API:Entities::article
:article

还要注意的是,我正在使用
添加招摇过市文档
,这段代码 生成正确的招摇过市文档,因此解决方案必须 与招摇完全兼容。
params的正确用法是什么

在不冒犯招摇过市者的情况下阻止。

我不确定您在这里想要实现什么。我猜您希望更改post方法,使其接受JSON,如下所示:

{ attribute1: value, attribute2: value }
而不是

{ article: { attribute1: value, attribute2: value } }
params do
    requires :article, type: API::Entities::Article, documentation: { eg: "aklsdfj" }
end
在这种情况下,您必须将参数块更改为如下内容

params do
  requires :attribute1, type: String, documentation: { eg: "aklsdfj" }
  requires :attribute2, type: String, documentation: { eg: "aklsdfj" }
end
而不是

{ article: { attribute1: value, attribute2: value } }
params do
    requires :article, type: API::Entities::Article, documentation: { eg: "aklsdfj" }
end
上面的params块需要一个JSON,其中包含一个由实体API::Entities::article中定义的每个属性组成的article属性


事实上,Grape不接受实体对象作为参数的类型。

但这不利于招摇过市,请参见。是的。我同意你的看法。到目前为止,Grape不接受实体对象作为参数的类型。你只有两个选择。您可以使用实际建议的方法,也可以等待新的葡萄版本。:)