library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.4 ✔ readr 2.1.5
## ✔ forcats 1.0.0 ✔ stringr 1.5.1
## ✔ ggplot2 3.5.1 ✔ tibble 3.2.1
## ✔ lubridate 1.9.3 ✔ tidyr 1.3.1
## ✔ purrr 1.0.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(httr2)
library(dotenv)
library(purrr)
Make secret key
nytimes_a<- secret_make_key()
nytimes_token<- secret_encrypt(Sys.getenv('nytimes'), nytimes_a)
nytimes_API_key<- secret_decrypt(nytimes_token, nytimes_a)
https://api.nytimes.com/svc/topstories/v2/us.json?api-key=yourkey
base_url<- "https://api.nytimes.com/svc/topstories/v2/"
section<- 'home'
re<- request(base_url) %>%
req_url_path_append(paste0(section, '.json')) %>%
req_url_query(
`api-key` = nytimes_API_key) %>%
req_perform()
#preview the first article
nytimes_home<- re %>%
resp_body_json() %>%
pluck('results') %>%
map(~ list('Title'=.x$title, 'Author'=.x$byline, 'Pub_date'=.x$published_date, 'Section'=.x$section)) %>%
map_dfr(as.data.frame)
#format the date:
nytimes_home %>%
mutate(Pub_date=ymd_hms(Pub_date))
Group by sections:
sorted<- nytimes_home %>%
group_by(Section) %>%
summarise(numbers=n())
ggplot(sorted, aes(x=Section, y=numbers, fill=Section)) +
geom_bar(stat='identity')+
labs(title='Types of news in the top stories section')