Last active
December 15, 2015 15:29
-
-
Save steveklabnik/5282209 to your computer and use it in GitHub Desktop.
Fetch Gists from the API
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' | |
# a simple wrapper to do an HTTP GET | |
def fetch_uri(uri) | |
Net::HTTP.get_response(URI(uri)) | |
end | |
# GETs the URI and returns a Ruby hash. | |
def fetch_json(uri) | |
result = fetch_uri(uri) | |
JSON.load(result.body) | |
end | |
# Gets the next uri via pagination in headers | |
def next_uri(uri) | |
result = fetch_uri(uri) | |
links = result.to_hash['link'] | |
# stupid parsing. We'd use something real here in | |
# production | |
link_array = links.first.split(",") | |
link_array.collect! do |string| | |
string =~ /\<(.*)\>; rel="(.*)"/ | |
[$2, $1] | |
end | |
Hash[link_array]["next"] | |
end | |
# omg hax! I don't want to deal with templates, so | |
# let's punt on that. You'd use a real URI templates | |
# parser in real code. | |
def parse_uri_template(uri) | |
uri[0..-11] | |
end | |
# Let's begin! | |
json = fetch_json('https://api.github.com/') | |
base_uri = parse_uri_template(json["gists_url"]) | |
next_uri = next_uri(base_uri) | |
json = fetch_json(next_uri) | |
first_entry = json[0] | |
puts "DATA:" | |
puts "ID:\t#{first_entry["id"]}" | |
puts "URL:\t#{first_entry["url"]}" | |
puts "USER:\t#{first_entry["user"]["login"]}" | |
oh? This worked for me, unmodified. weird.
I'm getting 400 The plain HTTP request was sent to HTTPS port
with this code on ruby 1.9.3p392 (2013-02-22 revision 39386) [x86_64-darwin12.2.1]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
had to modify for https to work