#Load library

library(httr)
library(jsonlite)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.2     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.3     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.1     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter()  masks stats::filter()
## ✖ purrr::flatten() masks jsonlite::flatten()
## ✖ dplyr::lag()     masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(data.table)
## 
## Attaching package: 'data.table'
## 
## The following objects are masked from 'package:lubridate':
## 
##     hour, isoweek, mday, minute, month, quarter, second, wday, week,
##     yday, year
## 
## The following objects are masked from 'package:dplyr':
## 
##     between, first, last
## 
## The following object is masked from 'package:purrr':
## 
##     transpose

#Access API

#Save API key
api_csv <- "C:/Users/NBMF48/Desktop/SPS/Data607/Homework/Assignment 9/API_Key.csv"
api_key <- fread(api_csv, header = TRUE)

#API access HTTP
url <- paste0("https://api.nytimes.com/svc/books/v3/lists/names.json?api-key=", api_key$Key)

#Access API information
response <- GET(url)
data <- fromJSON(content(response, "text"))

#Convert to data frame
books <- as_tibble(data$results)

head(books, 10)
## # A tibble: 10 × 6
##    list_name                display_name list_name_encoded oldest_published_date
##    <chr>                    <chr>        <chr>             <chr>                
##  1 Combined Print and E-Bo… Combined Pr… combined-print-a… 2011-02-13           
##  2 Combined Print and E-Bo… Combined Pr… combined-print-a… 2011-02-13           
##  3 Hardcover Fiction        Hardcover F… hardcover-fiction 2008-06-08           
##  4 Hardcover Nonfiction     Hardcover N… hardcover-nonfic… 2008-06-08           
##  5 Trade Fiction Paperback  Paperback T… trade-fiction-pa… 2008-06-08           
##  6 Mass Market Paperback    Paperback M… mass-market-pape… 2008-06-08           
##  7 Paperback Nonfiction     Paperback N… paperback-nonfic… 2008-06-08           
##  8 E-Book Fiction           E-Book Fict… e-book-fiction    2011-02-13           
##  9 E-Book Nonfiction        E-Book Nonf… e-book-nonfiction 2011-02-13           
## 10 Hardcover Advice         Hardcover A… hardcover-advice  2008-06-08           
## # ℹ 2 more variables: newest_published_date <chr>, updated <chr>