Assignment overview: Download JSON data provided through New York Times Web API portal into R data frame.
Data of choice: New York Times Best Sellers Books
library(jsonlite)
library(dplyr)
library(knitr)
#Get books ranked 1st for the type provided in the argument
getBestSeller <- function(uri, format=".json", list_type, rank=1,api_key){
json_output <- fromJSON(paste(uri, format,
"?list-name=", list_type,
"&rank=", rank,
"&api-key=", api_key,
sep=""))
results <- json_output$results
# book_detail contains list so convert it to data frame and then bind it to results
details <- as.data.frame(results$book_detail)
final_output <- cbind(results, details) %>% select(list_name, rank,title, author, description)
return(final_output)
}
Store api-key and base url into variables
nyt_api_key <- "543adc61e14cf137f5a2121ec35d7d35:4:73310298"
nyt_uri <- "http://api.nytimes.com/svc/books/v3/lists"
Call getBestSeller one at a time
# get hardcover-fiction
kable(getBestSeller(uri = nyt_uri,list_type = "hardcover-fiction", api_key = nyt_api_key))
| list_name | rank | title | author | description |
|---|---|---|---|---|
| Hardcover Fiction | 1 | ROGUE LAWYER | John Grisham | The attorney Sebastian Rudd is a “lone gunman” who hates injustice and the system and defends unpopular clients. |
# e-book-fiction
kable(getBestSeller(uri = nyt_uri,list_type = "e-book-fiction", api_key = nyt_api_key))
| list_name | rank | title | author | description |
|---|---|---|---|---|
| E-Book Fiction | 1 | ROGUE LAWYER | John Grisham | The attorney Sebastian Rudd is a “lone gunman” who hates injustice and the system and defends unpopular clients. |
Or create a vector of items and then call the function
list_names <- c("hardcover-fiction","e-book-fiction","trade-fiction-paperback", "hardcover-nonfiction")
best_sellers <- lapply(list_names, function(x) getBestSeller(uri = nyt_uri,list_type = x, api_key = nyt_api_key))
best_sellers_df <- dplyr::rbind_all(best_sellers)
kable(best_sellers_df)
| list_name | rank | title | author | description |
|---|---|---|---|---|
| Hardcover Fiction | 1 | ROGUE LAWYER | John Grisham | The attorney Sebastian Rudd is a “lone gunman” who hates injustice and the system and defends unpopular clients. |
| E-Book Fiction | 1 | ROGUE LAWYER | John Grisham | The attorney Sebastian Rudd is a “lone gunman” who hates injustice and the system and defends unpopular clients. |
| Trade Fiction Paperback | 1 | THE MARTIAN | Andy Weir | After a dust storm forces his crew to abandon him, an astronaut embarks on a dogged quest to stay alive on Mars. |
| Hardcover Nonfiction | 1 | KILLING REAGAN | Bill O’Reilly and Martin Dugard | The host of “The O’Reilly Factor” recounts the events surrounding the attempted assassination of President Reagan in 1981. |