4.12 Lab: Scraping data from APIs

To understand how APIs work, we’ll take the New York Times API as an example. This API allows users to search articles by string and dates, and returns counts of articles and a short description of each article (but not the full text). You can find the documentation here. Get a new API token (setup a developer account and create and app here) and paste the key here:

The fist step is to identify the base url and the parameters that we can use to query the API. Now we can do a first API call using the httr package. (You can use the my API key above.. as long as we don’t hit the rate limit!)

You can find a description of how the article search api works here: http://developer.nytimes.com/article_search_v2.json#/README

From the output of r, we can see that the query was successful (Status: 200), the content is in json format, and its size is 17.3kB.

To extract the text returned by this API call, you can use content. You can write it to a file to take a look at it.

We can save the output into an object in R to learn more about its structure.

If we check the documentation, we find that we can subset by date with the begin_date and end_date parameters. Let’s see how this works…

Between these two dates, there were X articles in the NYT mentioning “inequality”.

Now imagine we want to look at the evolution of mentions of this word over time. Following the best coding practices we introduced earlier, we want to write a function that will take a word and a set of dates as arguments and return the counts of articles.

This would be a first draft of that function:

Ok, so this seems to work. But we want to run this function multiple times across different years, so let’s write another function that helps us do that.

Oops! What happened? Why the error? Maybe we’re querying the API too fast. Let’s modify the nyt_count function to add a while loop that will wait a couple of seconds in case there’s an error:

And let’s see if this does the trick…

Some additional code

We can try to generalize the function even more so that it works with any date interval, not just years:

And now we can count articles at the month level…