【问题标题】:How to create API methods using rails & swagger docs for nested resources如何使用 Rails 和 swagger 文档为嵌套资源创建 API 方法
【发布时间】:2014-05-07 18:11:56
【问题描述】:

我有一个 Rails 应用程序,使用活动记录序列化程序来响应 json 或 html。我正在使用它来创建公共 API。我正在使用设计简单的 http 进行基本身份验证。

我通过以下 gem 使用 Swagger 文档。

gem 'swagger-docs' #for creating the swagger json format gem 'swagger-ui_rails' #for generating the swanky active docs UI

我已经能够通过控制器成功地为我的主要顶级资源创建 json。例如,在“products_controller.rb”中:

swagger_controller :products, "Product Management"

  swagger_api :index do
    summary "Fetches all Products"
    param :query, :page, :integer, :optional, "Page number"
    response :unauthorized
    response :success
  end

问题是如何设置嵌套资源。

所以,在我的架构中,Products has_many Slots / Slots 属于 Product。所以,在我的“slots_controller.rb”中,我以同样的方式进行了设置:

swagger_controller :slots, "Slot Management"

  swagger_api :index do
    summary "Fetches all Slots for a Product"
    param :query, :page, :integer, :optional, "Page number"
    param :form, :product_id, :integer, :required, "Product id"
    response :unauthorized
    response :success
  end

我认为这是一厢情愿的想法,提供:product_id 的参数以及使用产品ID 为给定产品查找插槽的控制器操作,然后swagger 可能会自动将其解释为嵌套资源。似乎不是,相反,我在 Swagger 中的插槽 API 方法正在寻找:

/api/v1/slots.json

而不是

/api/v1/products/#{product.id}/slots

如何设置我的 swagger_controller 来为插槽生成正确的嵌套 url 结构?

【问题讨论】:

    标签: ruby-on-rails json api resources swagger


    【解决方案1】:

    不确定你是否已经解决了这个问题,但你可以像这样使用:path param_type:

    swagger_api :index do
      summary "Fetches all Slots for a Product"
      param :path, :product_id, :integer, :required, "Product id"
      param :query, :page, :integer, :optional, "Page number"
      response :unauthorized
      response :success
    end
    

    【讨论】:

    • 谢谢马克。实际上,我最终暂时放弃了招摇,而是使用Slate 来记录我的 API。我可能会恢复到 swagger 以提供活动文档,但暂时使用 Slate 进行迭代要快得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 2019-04-19
    • 1970-01-01
    • 2013-10-16
    • 2020-11-10
    相关资源
    最近更新 更多