Code
nyt_key <- Sys.getenv("NYT_API_KEY")
mg_books_url <- "https://api.nytimes.com/svc/books/v3/lists/current/childrens-middle-grade-hardcover.json"
response <- GET(mg_books_url, query = list(`api-key` = nyt_key))Using the NYTimes API, I explore which books are listed as the top 10 best sellers in the middle grade hardback category.
First I make the request. This requires access to the “Books” API. My endpoint is the list of top middle grade hardcover books. I have my API key saved in my R environment file, not hardcoded into my quarto file or uploaded to github.
nyt_key <- Sys.getenv("NYT_API_KEY")
mg_books_url <- "https://api.nytimes.com/svc/books/v3/lists/current/childrens-middle-grade-hardcover.json"
response <- GET(mg_books_url, query = list(`api-key` = nyt_key))Once we have the response to our API query, we can parse the JSON request and convert it to data frame.
# Parse the JSON
json_text <- content(response, as = "text", encoding = "UTF-8")
parsed_data <- fromJSON(json_text, flatten = TRUE)
# Extract into a data frame
mgbooks_df <- parsed_data$results$booksFinally I tidy the data frame by selecting only relevant, non-empty columns. A preview of the first 10 entries in that list is displayed:
clean_mgbooks <- mgbooks_df %>%
select(
rank,
title,
author,
publisher,
description,
weeks_on_list,
primary_isbn13,
age_group
)
# Display the top 5 middle grade best sellers
head(clean_mgbooks %>% select(rank,title, author), n=10) rank title author
1 1 THE WILD ZONE Rick Riordan and Annabelle Oh
2 2 BUILDING 903 Lois Lowry
3 3 WONDER R.J. Palacio
4 4 THE COMPLETE COOKBOOK FOR YOUNG CHEFS America's Test Kitchen Kids
5 5 KIKI'S DELIVERY SERVICE Eiko Kadono
6 6 GAME OF PETS: THE BOY WHO KNEW TOO MUCH Aaron Blabey
7 7 THE WUMP Tony DiTerlizzi
8 8 POCKET BEAR Katherine Applegate
9 9 KIKI AND THE NEW MAGIC Eiko Kadono
10 10 SPOOKY RIVERS Geo Rutherford