使用 httparty ruby​​gem 发出 api 请求时如何处理分页

how to deal with pagination when making api request using httparty rubygem

我正在尝试为我的 Jekyll 站点编写一个插件,该插件将排序后的 JSON 响应写入数据文件,但我在处理响应中的项目限制时遇到了问题。基本响应如下所示:

{
  "current_page": 1,
  "per_page": 50,
  "total_pages": 19,
  "url": "https://web.consonance.app/api/v2/products.json",
  "products": [
    {
      ...
      "pub_date": "2017-05-01"
      ...
    },
    ...
  ]
}

其中 products 是我想按出版日期 (pub_date) 排序的书籍数组。没有next_pageurl,只有current_pagetotal_pages。我的插件非常基础。它使用 httparty 发出 API 请求,然后按 pub_date 将响应排序为散列。到目前为止,它看起来像这样:

require 'rubygems'
require 'httparty'
require 'json'

# http request to api

url = 'https://web.consonance.app/api/v2/products.json'
query = {
}
headers = {
  Authorization: "Token token=**************"
}
response = HTTParty.get(url, query: query, headers: headers)

# convert response to hash array

hash = JSON.parse(response.body)

# reverse sort product in products by date published

hash_sorted = hash['products'].sort_by! { |o| o['pub_date'] }.reverse!

# open _data file and write json response

File.open("./_data/products.json", "w") { |file| 
  file.puts JSON.pretty_generate(hash_sorted)
}

这给了我 JSON 前 50 项按 pub_date 反向排序的响应。我的问题是:

How do I get the most recently published book (product) from the entire array, not just the first 50 results?

我试过将每页的限制增加到最大值,即 500 本书,但总的书数超过一页,所以我仍然遇到分页问题。

记录了请求的可用参数 here

注意 – 我正在使用 httparty,因为我发现提出请求很容易,但我愿意使用其他 gems/methods。刚开始学习Ruby,还请多多包涵

使用 current_pagetotal_pages 作为条件,我遍历了响应页面并将所有产品分配给一个数组:

while current_page <= total_pages do

  url = 'https://web.consonance.app/api/v2/products.json'
  query = {
    'page' => "#{current_page}",
  }
  request = HTTParty.get(url, query: query)

  hash = JSON.parse(request.body)

  hash['products'].each do |item|
    product_array.push(item)
  end

  current_page += 1

end