【问题标题】:Creating an api endpoint with Grape that returns a nested hash使用 Grape 创建一个返回嵌套哈希的 api 端点
【发布时间】:2014-12-12 18:25:55
【问题描述】:

我在尝试设置我的第一个 API 时遇到了问题。我有使用 Grape 的 API 端点,但我不确定如何获得我想要的正确数据哈希。

现在 API 非常简单,如下所示:

    module CategoryTopic
      class API < Grape::API
        prefix "api/v1"
        format :json

        resource "categories" do
          get do
            Category.all
          end
        end

      end
    end

然后返回这个

[{"id":1,"category_name":"General Questions"}]

但在我的应用程序内部,一个类别有_many 个主题,我想返回一个看起来像这样的哈希:

{categories: 
  {"Numbers": "1", "2"},
  {"Colors": "Red", "Blue"}
}

这样的事情可能吗?

【问题讨论】:

    标签: ruby-on-rails ruby json ruby-on-rails-4 grape


    【解决方案1】:

    是的,这是可能的。我假设您想从 /api/v1/categories URL 返回该 JSON。

    首先,我不同意您提出的 JSON,因为它看起来不正确。如果 Category 与 Topics 有 has_many 关联,则结果 JSON 应返回 Category 属性和其中的所有相关关联。在我看来,它应该是这样的:

    [
        { "id":"1", "category_name": "General Questions", 
              topics: [ { "numbers":["1", "2"], "colors": ["Red", "Blue"] } ] }
    ]
    

    在这种情况下,您必须安装 Grape Entity gem (https://github.com/intridea/grape-entity) 并创建两个这样的实体:

    class CategoryEntity < Grape::Entity
        expose :id
        expose :category_name
        expose :topics, :using => TopicEntity
    end
    
    class TopicEntity < Grape::Entity
        expose :numbers
        expose :colors
    end
    

    最好不要直接从 API 返回模型。您应该使用实体来保护您的模型表示免受 API 客户端的影响。接下来,需要这个 gem 并在你的 API 类中使用你的全新实体,如下所示:

    require 'grape-entity'
    
    module CategoryTopic
      class API < Grape::API
        prefix "api/v1"
        format :json
    
        resource "categories" do
          get do
            present Category.all, :with => CategoryEntity
          end
        end
    
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 2018-08-24
      • 2013-08-02
      • 2014-12-06
      • 1970-01-01
      • 2016-03-02
      • 1970-01-01
      相关资源
      最近更新 更多