ruby - 如何使用与 Swagger 兼容的参数 block 对 Grape REST API 进行 POST 请求

标签 ruby rest swagger swagger-ui grape-api

我正在使用 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/

相关文章:

ruby - 如果散列有 key ,则使用它。否则,使用不同的 key

java - "Content type ' application/json;charset=UTF-8 ' not supported"在 Spring Rest 应用程序中

rest - 在Spring REST应用程序中使用自定义消息处理通用HTTP异常

c# - 当从另一个项目内部提供 api 时,如何在 Swashbuckle/Swaggerwork 中创建 url 路径?

javascript - 如何使用 swagger-ui 模块在我的 MEAN 堆栈项目中显示 Swagger JSON 文件?

ruby - 如何从ruby中的内部类访问外部类的类变量

ruby-on-rails - 如何在 Ruby on Rails 应用程序中添加照片以更正索引?

Swagger REST API 注释不适用于接口(interface)但适用于实现类

sql - 可能的sql注入(inject)

python-3.x - 哪种python框架仅适合于api