library(httr2)
library(jsonlite)
library(dplyr)
library(purrr)
Personal API key was obtained from https://developer.nytimes.com
api_key <- "xuAGuj7bTCDxnEG9DcB4oMuBmVLtqaD6"
I decided to go with the election articles
req <- request("https://api.nytimes.com/svc/search/v2/articlesearch.json?q=election&api-key=xuAGuj7bTCDxnEG9DcB4oMuBmVLtqaD6")
resp <- req_perform(req)
json_data <- resp %>%
resp_body_json(flatten = TRUE)
articles_df <- map_dfr(json_data$response$docs, function(x) {
tibble(
headline = x$headline$main,
pub_date = x$pub_date,
author = x$byline$original,
section_name = x$section_name,
type_of_material = x$type_of_material,
url = x$web_url,
snippet = x$snippet
)
}) %>%
mutate(pub_date = as.Date(pub_date))
head(articles_df)
## # A tibble: 6 × 7
## headline pub_date author section_name type_of_material url snippet
## <chr> <date> <chr> <chr> <chr> <chr> <chr>
## 1 Trump Empowers … 2025-10-22 "By A… U.S. News http… The pr…
## 2 Your November E… 2025-10-20 "By J… U.S. News http… It’s n…
## 3 What to Know Ab… 2025-10-16 "By S… U.S. News http… Some 2…
## 4 U.K. Labour Par… 2025-10-24 "By L… World News http… The go…
## 5 New Jersey Gove… 2025-09-18 "" Polls Interactive Fea… http… Track …
## 6 New York City M… 2025-06-10 "" Polls Interactive Fea… http… Track …