Created
December 8, 2014 19:44
-
-
Save aq1018/2272cd8953225ee42447 to your computer and use it in GitHub Desktop.
NationBuilder API Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
require 'json' | |
class APIClient | |
class Error < RuntimeError; end | |
class ClientError < Error; end | |
class ServerError < Error; end | |
def initialize(host, token) | |
@host, @token = URI(host), token | |
end | |
def get(uri) | |
rsp = http.get(uri, headers) | |
format_json(rsp) | |
end | |
def format_json(rsp) | |
return JSON.parse(rsp.body) if (200..299).include?(rsp.code.to_i) | |
fail Error, "Request failed with status: #{rsp.code}, body: #{rsp.body}" | |
end | |
def http | |
@http ||= Net::HTTP.start( | |
@host.host, | |
@host.port, | |
use_ssl: @host.scheme == 'https' | |
) | |
end | |
def headers | |
@headers ||= { | |
"Accept" => "application/json", | |
"Content-Type" => "application/json", | |
"Authorization" => "Bearer #{@token}" | |
} | |
end | |
end | |
puts 'Trying to fetch 10 pages of people data from your nation.' | |
puts 'Please enter your nation:' | |
print '> ' | |
nation = STDIN.gets.chomp | |
puts 'Please enter your access token:' | |
print '> ' | |
token = STDIN.gets.chomp | |
host = "http://#{nation}.nbuild.dev" | |
client = APIClient.new(host, token) | |
# `token_pagniator` query paramter needs to be present for older nations. | |
# Newer nations defaults to new token paginator and can safely ignore this | |
# query parameter. | |
uri = "/api/v1/people?limit=100&token_paginator=true" | |
# uri = "/api/v1/people?limit=100" | |
current_page = 1 | |
begin | |
puts "========Current page: #{current_page}=======" | |
rsp = client.get(uri) | |
people = rsp["results"] | |
next_page = rsp["next"] | |
prev_page = rsp["prev"] | |
people.each do |person| | |
email = person['email'] | |
first_name = person['first_name'] | |
last_name = person['last_name'] | |
puts "#{email} #{first_name} #{last_name}" | |
end | |
uri = next_page | |
current_page += 1 | |
end while next_page && current_page <= 10 | |
puts "Completed fetching #{current_page - 1 } pages! Have a good day!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment