This section lists some examples of public HTTP APIs that publish data in JSON format. These are great to get a sense of the complex structures that are encountered in real world JSON data. All services are free, but some require registration/authentication. Each example returns lots of data, therefore not all output is printed in this document.
library(jsonlite)
Github is an online code repository and has APIs to get live data on almost all activity. Below some examples from a well known R package and author:
hadley_orgs <- fromJSON("https://api.github.com/users/hadley/orgs")
hadley_repos <- fromJSON("https://api.github.com/users/hadley/repos")
gg_commits <- fromJSON("https://api.github.com/repos/hadley/ggplot2/commits")
gg_issues <- fromJSON("https://api.github.com/repos/hadley/ggplot2/issues")
#latest issues
paste(format(gg_issues$user$login), ":", gg_issues$title)
[1] "Henrik-P : 'guides' documentation, possible improvement in last example"
[2] "richierocks : scatterplots of categorical variables cause 'row names were found from a short variable' warning"
[3] "lselzer : created fortify.glm"
[4] "petrbouchal : scale_colour_manual fails when elements of named matrix are passed to values"
[5] "smirarab : stat_ecdf plots extra points"
[6] "dorvak : Suggestion: Geom replace infix operator"
[7] "rpruim : documentation of fun.data (in stat_summary) incorrect?"
[8] "ttuggle : Memory overflow with scale_x_discrete()"
[9] "pengyu : Added ..Name to each prototype so that str.proto() can show the names correctly"
[10] "pharaveej : ggplot - geom_step error"
[11] "noamross : New theme option to put panel/grid on top of data"
[12] "krlmlr : geom_boxplot with continuous x and without group aesthetics"
[13] "lccanon : rqss in stat_quantile ignore the quantile with large number of values"
[14] "bergsmat : Geom not exported?"
[15] "iagomosqueira : size in geom_point using variable with all but 1 as NAs"
[16] "xsaintmleux : allow ggplot_build to return an additional value: the processed data as ..."
[17] "mkcor : Edit warning message to reflect intuitive use"
[18] "tsibley : Rebased and redocumented version of PR #744"
[19] "BrianDiggs : sqrt_trans, scale limit expansion, and missing breaks"
[20] "marvel64 : Documentation for geom_boxplot"
[21] "blaquans : Would it be possible to add notes to a ggplot graph ?"
[22] "jiho : New theme_void(), completely empty"
[23] "veraanadi : Add new function geom_curve"
[24] "lionelgit : Facet titles"
[25] "kent37 : Error in stat_density example text"
[26] "tonytonov : geom_violin throws error on data with zero variance"
[27] "cboettig : scales=\"free\" on facet_grid no longer has any effect on `y` axis within rows"
[28] "baptiste : check.class argument to ggsave"
[29] "lionelgit : Coord expand"
[30] "croach : Fix for bad URL in qplot docs"
A single public API that shows location, status and current availability for all stations in the New York City bike sharing imitative.
citibike <- fromJSON("http://citibikenyc.com/stations/json")
stations <- citibike$stationBeanList
colnames(stations)
[1] "id" "stationName"
[3] "availableDocks" "totalDocks"
[5] "latitude" "longitude"
[7] "statusValue" "statusKey"
[9] "availableBikes" "stAddress1"
[11] "stAddress2" "city"
[13] "postalCode" "location"
[15] "altitude" "testStation"
[17] "lastCommunicationTime" "landMark"
nrow(stations)
[1] 332
The Ergast Developer API is an experimental web service which provides a historical record of motor racing data for non-commercial purposes.
res <- fromJSON('http://ergast.com/api/f1/2004/1/results.json')
drivers <- res$MRData$RaceTable$Races$Results[[1]]$Driver
colnames(drivers)
[1] "driverId" "code" "url" "givenName"
[5] "familyName" "dateOfBirth" "nationality" "permanentNumber"
drivers[1:10, c("givenName", "familyName", "code", "nationality")]
givenName familyName code nationality
1 Michael Schumacher MSC German
2 Rubens Barrichello BAR Brazilian
3 Fernando Alonso ALO Spanish
4 Ralf Schumacher SCH German
5 Juan Pablo Montoya MON Colombian
6 Jenson Button BUT British
7 Jarno Trulli TRU Italian
8 David Coulthard COU British
9 Takuma Sato SAT Japanese
10 Giancarlo Fisichella FIS Italian
Below an example from the ProPublica Nonprofit Explorer API where we retrieve the first 10 pages of tax-exempt organizations in the USA, ordered by revenue. The rbind.pages
function is used to combine the pages into a single data frame.
#store all pages in a list first
baseurl <- "http://projects.propublica.org/nonprofits/api/v1/search.json?order=revenue&sort_order=desc"
pages <- list()
for(i in 0:10){
mydata <- fromJSON(paste0(baseurl, "&page=", i), flatten=TRUE)
message("Retrieving page ", i)
pages[[i+1]] <- mydata$filings
}
#combine all into one
filings <- rbind.pages(pages)
#check output
nrow(filings)
[1] 275
filings[1:10, c("organization.sub_name", "organization.city", "totrevenue")]
organization.sub_name organization.city totrevenue
1 KAISER FOUNDATION HEALTH PLAN INC PORTLAND 4.015e+10
2 KAISER FOUNDATION HEALTH PLAN INC PORTLAND 3.779e+10
3 KAISER FOUNDATION HOSPITALS PORTLAND 1.854e+10
4 KAISER FOUNDATION HOSPITALS PORTLAND 1.798e+10
5 PARTNERS HEALTHCARE SYSTEM INC BOSTON 1.045e+10
6 PARTNERS HEALTHCARE SYSTEM INC BOSTON 9.637e+09
7 DIGNITY HEALTH PHOENIX 9.212e+09
8 THRIVENT FINANCIAL FOR LUTHERANS MINNEAPOLIS 8.507e+09
9 UPMC GROUP PITTSBURGH 7.698e+09
10 CLEVELAND CLINIC FOUNDATION CLEVELAND 7.011e+09
The New York Times has several APIs as part of the NYT developer network. These interface to data from various departments, such as news articles, book reviews, real estate, etc. Registration is required (but free) and a key can be obtained at here. The code below includes some example keys for illustration purposes.
#search for articles
article_key <- "&api-key=c2fede7bd9aea57c898f538e5ec0a1ee:6:68700045"
url <- "http://api.nytimes.com/svc/search/v2/articlesearch.json?q=obamacare+socialism"
req <- fromJSON(paste0(url, article_key))
articles <- req$response$docs
colnames(articles)
[1] "web_url" "snippet" "lead_paragraph"
[4] "abstract" "print_page" "blog"
[7] "source" "multimedia" "headline"
[10] "keywords" "pub_date" "document_type"
[13] "news_desk" "section_name" "subsection_name"
[16] "byline" "type_of_material" "_id"
[19] "word_count"
#search for best sellers
bestseller_key <- "&api-key=5e260a86a6301f55546c83a47d139b0d:3:68700045"
url <- "http://api.nytimes.com/svc/books/v2/lists/overview.json?published_date=2013-01-01"
req <- fromJSON(paste0(url, bestseller_key))
bestsellers <- req$results$list
category1 <- bestsellers[[1, "books"]]
subset(category1, select = c("author", "title", "publisher"))
author title publisher
1 Gillian Flynn GONE GIRL Crown Publishing
2 John Grisham THE RACKETEER Knopf Doubleday Publishing
3 E L James FIFTY SHADES OF GREY Knopf Doubleday Publishing
4 Nicholas Sparks SAFE HAVEN Grand Central Publishing
5 David Baldacci THE FORGOTTEN Grand Central Publishing
#movie reviews
movie_key <- "&api-key=5a3daaeee6bbc6b9df16284bc575e5ba:0:68700045"
url <- "http://api.nytimes.com/svc/movies/v2/reviews/dvd-picks.json?order=by-date"
req <- fromJSON(paste0(url, movie_key))
reviews <- req$results
colnames(reviews)
[1] "nyt_movie_id" "display_title" "sort_name"
[4] "mpaa_rating" "critics_pick" "thousand_best"
[7] "byline" "headline" "capsule_review"
[10] "summary_short" "publication_date" "opening_date"
[13] "dvd_release_date" "date_updated" "seo_name"
[16] "link" "related_urls" "multimedia"
reviews[1:5, c("display_title", "byline", "mpaa_rating")]
display_title byline mpaa_rating
1 Boyhood Manohla Dargis R
2 Dawn of the Planet of the Apes A. O. Scott PG-13
3 The Empty Hours Jeannette Catsoulis <NA>
4 Gabrielle Stephen Holden R
5 Wrinkles Jeannette Catsoulis NR
CrunchBase is the free database of technology companies, people, and investors that anyone can edit.
key <- "f6dv6cas5vw7arn5b9d7mdm3"
res <- fromJSON(paste0("http://api.crunchbase.com/v/1/search.js?query=R&api_key=", key))
str(res$results)
The Sunlight Foundation is a non-profit that helps to make government transparent and accountable through data, tools, policy and journalism. Register a free key at here. An example key is provided.
key <- "&apikey=39c83d5a4acc42be993ee637e2e4ba3d"
#Find bills about drones
drone_bills <- fromJSON(paste0("http://openstates.org/api/v1/bills/?q=drone", key))
drone_bills$title <- substring(drone_bills$title, 1, 40)
print(drone_bills[1:5, c("title", "state", "chamber", "type")])
title state chamber type
1 "An Act relating to a prohibition on the ak upper bill
2 DRONE SURVEIL-LAW ENFORCEMENT il upper bill
3 Sets forth certain standards to be follo nj upper bill
4 Unmanned aerial vehicle regulation act. ks lower bill
5 Prohibiting the use of drones by law enf ks lower bill
#Congress mentioning "constitution"
res <- fromJSON(paste0("http://capitolwords.org/api/1/dates.json?phrase=immigration", key))
wordcount <- res$results
wordcount$day <- as.Date(wordcount$day)
summary(wordcount)
count day raw_count
Min. : 1.0 Min. :1996-01-02 Min. : 1.0
1st Qu.: 3.0 1st Qu.:2000-10-26 1st Qu.: 3.0
Median : 8.0 Median :2005-07-16 Median : 8.0
Mean : 25.1 Mean :2005-06-01 Mean : 25.1
3rd Qu.: 21.0 3rd Qu.:2009-11-28 3rd Qu.: 21.0
Max. :1835.0 Max. :2014-08-05 Max. :1835.0
#Local legislators
legislators <- fromJSON(paste0("http://congress.api.sunlightfoundation.com/",
"legislators/locate?latitude=42.96&longitude=-108.09", key))
subset(legislators$results, select=c("last_name", "chamber", "term_start", "twitter_id"))
last_name chamber term_start twitter_id
1 Lummis house 2013-01-03 CynthiaLummis
2 Enzi senate 2009-01-06 SenatorEnzi
3 Barrasso senate 2013-01-03 SenJohnBarrasso
The twitter API requires OAuth2 authentication. Some example code:
#Create your own appication key at https://dev.twitter.com/apps
consumer_key = "EZRy5JzOH2QQmVAe9B4j2w";
consumer_secret = "OIDC4MdfZJ82nbwpZfoUO4WOLTYjoRhpHRAWj6JMec";
#Use basic auth
library(httr)
secret <- RCurl::base64(paste(consumer_key, consumer_secret, sep = ":"));
req <- POST("https://api.twitter.com/oauth2/token",
config(httpheader = c(
"Authorization" = paste("Basic", secret),
"Content-Type" = "application/x-www-form-urlencoded;charset=UTF-8"
)),
body = "grant_type=client_credentials",
encode = "multipart"
);
#Extract the access token
token <- paste("Bearer", content(req)$access_token)
#Actual API call
url <- "https://api.twitter.com/1.1/statuses/user_timeline.json?count=10&screen_name=Rbloggers"
req <- GET(url, config(httpheader = c("Authorization" = token)))
json <- content(req, as = "text")
tweets <- fromJSON(json)
substring(tweets$text, 1, 100)
[1] "LAST CHANCE TO REGISTER FOR EARL (15-17 September, London) http://t.co/7ZT7cKGP8N #rstats"
[2] "Looking For Life http://t.co/luFwXnyF78 #rstats"
[3] "Adding the SPSS MEAN.n Function to R http://t.co/gTw60cxWEd #rstats"
[4] "Brazilian Presidential Election http://t.co/G08Tu63YFn #rstats"
[5] "Hortonworks Seminar Series: The Modern Data Architecture http://t.co/M4A1S3SRMy #rstats"
[6] "Introducing simmer: Discrete Event Simulation for R http://t.co/vBImwcKP3F #rstats"
[7] "Notifications from R http://t.co/KaQqzFKd6F #rstats"
[8] "rNOMADS 2.0.2 released http://t.co/Bcy2D1QBgk #rstats"
[9] "New R job: Senior Operations Research Consultant http://t.co/Fimizb8mwg #rstats #jobs"
[10] "httr 0.5 http://t.co/hGWvZxrhdu #rstats"