在 Rails 上通过 Ruby 使用 HTTP 使用分页资源

Consuming paginated resources using HTTP with Ruby on Rails

我正在构建一个平台,用于在从 Zendesk 的 API 中提取的图表中显示数据。我 运行 遇到了麻烦,因为一次只能提取 100 条记录。如何从此资源中提取多页记录?

这是我用来拨打电话的代码:

require 'net/http'
require 'uri'
require 'json'

#imports User data from the zendesk api and populates the database with it. 

uri = URI.parse("https://samplesupport.zendesk.com/api/v2/users.json")
request = Net::HTTP::Get.new(uri)
request.content_type = "application/json"
request.basic_auth("sampleguy@sample.com", "samplepass")

req_options = {
  use_ssl: uri.scheme == "https",
}

@response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
  http.request(request)
end
puts @response.body
puts @response.message
puts @response.code

这对于调用一个 'page' 资源来说效果很好...如果您能帮助我们使用我的脚本抓取多个页面,我们将不胜感激。谢谢!

基于 ZenDesk's documentation 他们 return 他们的负载中有一个 next_page 属性。所以你应该只检查它是否存在,然后再次查询它是否存在。根据需要重复。

require 'json'
# setup to query for the first page
results = JSON.parse(@response.body)

users = results['users'] #to get the users
if results['next_page']
  # Do another query to results['next_page'] URL and add to users list