Last active
August 29, 2015 14:04
-
-
Save O-I/e198b383906f8f31cf3b to your computer and use it in GitHub Desktop.
Experimenting with the Guardian Content 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 'open-uri' | |
require 'dotenv' | |
require 'json' | |
require 'pry' | |
Dotenv.load | |
# Basic structure of a Guardian API request: | |
# BASE_URI + endpoint + queries + api-key + params | |
BASE_URI = 'http://beta.content.guardianapis.com/' | |
endpoint = 'search?' | |
query = nil # I'm not adding one, but you could do, e.g., 'q=israel' | |
api_key = "api-key=#{ENV['API_KEY']}" | |
params = "&page-size=10" + # give me 10 records | |
"&show-fields=all" # give me all possible fields (you want "body") | |
# So this will be an API call for the newest 10 articles | |
api_call = "#{BASE_URI}#{endpoint}#{query}#{api_key}#{params}" | |
# Here's a Ruby hash representation of the JSON response | |
response = JSON.parse(open(api_call).read) | |
# Use pry to get familiar with the structure of the response | |
# binding.pry | |
# This is, hopefully, what you want | |
# an array of the full body text of the 10 articles returned | |
body_text = response["response"]["results"].map { |item| item["fields"]["body"] } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment