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

标签 json ruby get jekyll httparty

我正在尝试为我的 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_page 网址,只有 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)
}

它为我提供了按 pub_date 反向排序的前 50 个项目的 JSON 响应。我的问题是:

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

我尝试将每页的限制增加到最大,即 500 项,但图书总数跨越一页以上,所以我仍然遇到分页问题。

记录了请求的可用参数 here .

注意 – 我使用 httparty 因为我发现发出请求很容易,但我愿意使用其他 gems/方法。我刚刚开始学习 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

关于json - 使用 httparty ruby​​gem 发出 api 请求时如何处理分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56449619/

相关文章:

php如何在成功登录时将用户重定向到index.html

php - 如何从 PHP 中获取远程 JSON 或 XML API 数据并将返回对象分配为 PHP 变量?

java - Rails 应用程序,但所有数据层都使用基于 json/xml 的 Web 服务

ruby - 如何从 Mechanize::Page 的搜索方法中获取 Mechanize 对象?

json - 如何解码具有剩余值的异构数组作为列表

ruby-on-rails - NoMethodError (filtered_pa​​rameters)

Ruby Mechanize,填充动态表单/发送 JSON(Airbnb 日历)

get - 带有正文的 Angular2 http GET?

javascript - 加载 .json/.csv 时出错

javascript - 使用 Javascript 解析 JSON