如何使用Grape-API解码GET请求中的编码查询参数

时间:2018-08-07 13:34:45

标签: ruby-on-rails ruby rack grape grape-api

我正在使用 grape-api ,并且从带有编码查询参数的前端服务发出 GET 请求时遇到问题。这是我的端点设置为接收参数的方式:

params do
  requires :event_id, type: String, desc: 'Event id'
  requires :tickets, type: Array, desc: 'Array of each ticket data ex:  [ {id: "", count: 1 , coupon_code: ""} ]', allow_blank: false do
    requires :id, type: String, desc: 'Ticket id'
    requires :count, type: Integer, desc: 'Number of tickets to get'
    optional :coupon_code, type: String, desc: 'Promocode to apply if any'
  end
end

如您所见,我期望一个 event_id 参数和另一个对象数组 tickets ,这是请求URL的样子:

http://localhost:3000/api/service_fees/calculate?eventId=2xy6rft69azlu2mtppnzb1xe6olzd3f0&tickets[]=%7B%22id%22:%22vohd3y3n25cdgbvi3uzmqhcyie3zi53a%22,%22count%22:2%7D

但是,grape似乎不理解这些编码的查询参数,而我得到了这个异常:

[Exception: event_id is missing, tickets[0][id] is missing, tickets[0][id] is invalid, tickets[0][count] is missing, tickets[0][count] is invalid]

我的问题是:有没有办法告诉葡萄正确解码和解析查询参数?我在这里想念东西吗?

1 个答案:

答案 0 :(得分:0)

http://localhost:3000/api/service_fees/calculate?eventId=2xy6rft69azlu2mtppnzb1xe6olzd3f0&tickets[]=%7B%22id%22:%22vohd3y3n25cdgbvi3uzmqhcyie3zi53a%22,%22count%22:2%7D

对于上述请求URL,发送的参数名称为eventID,而Grape API要求/期望event_id。另外,tickets URL查询字符串参数构造错误。

您能试试看吗-http://localhost:3000/api/service_fees/calculate?eventId=2xy6rft69azlu2mtppnzb1xe6olzd3f0&tickets[0][id] =12&tickets[0][count] =13&tickets[0][coupon_code]=amrrbakry