Skip to content

Instantly share code, notes, and snippets.

Last active Aug 29, 2015
What would you like to do?
Experimenting with the Guardian Content API
require 'open-uri'
require 'dotenv'
require 'json'
require 'pry'
# Basic structure of a Guardian API request:
# BASE_URI + endpoint + queries + api-key + params
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