Introduction

For this week’s assignment, we will practice with APIs. We will choose one of the New York Times APIs and read the JSON data into R and transform it into a data frame. I chose Most Popular API from the New York Times APIs. I will be retrieving data for most viewed articles on NYTimes.com for 7 days.

knitr::opts_chunk$set(echo = TRUE)

#Load the necessary libraries

library(httr)
library(jsonlite)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
#create function to retrieve data for most viewed articles for a period of 7 days
popular_nyt_articles <- function(popular_nyt_api_key, type = "viewed", period = 7) {
  
  #Construct API URL
  url <- paste0("https://api.nytimes.com/svc/mostpopular/v2/", type, "/", period, ".json?api-key=", popular_nyt_api_key)

  #Send API request
  response <- GET(url)

  #Check for errors
  if (status_code(response) != 200) {
    stop("Error: Failed to fetch data from NYT API")
  }
  
  #Convert API response to JSON
  popular_article_response <- content(response, as = "text", encoding = "UTF-8")
  popular_article_json <- fromJSON(popular_article_response, flatten = TRUE)
  
  #Extract article details
  popular_articles <- popular_article_json$results %>%
    select(title, abstract, url, byline, published_date, section)
  
  return(popular_articles)
}

#API Key
popular_nyt_api_key = "mVRobcOljNxJoRsjiX4TSInaXcU7O7Rd"

# Fetch most viewed articles in the last 7 days
popular_articles_df <- popular_nyt_articles(popular_nyt_api_key, type = "viewed", period = 7)

# Print Data Frame
print(popular_articles_df)
##                                                                               title
## 1                                   Hillary Clinton: How Much Dumber Will This Get?
## 2                                                 The Leaked Signal Chat, Annotated
## 3  ‘Should I Fire Him?’ Inside Trump’s Deliberations Over the Fate of Michael Waltz
## 4                                            Trump Has Had Enough. He Is Not Alone.
## 5            Trump Administration Abruptly Cuts Billions From State Health Services
## 6                        Columbia Student Hunted by ICE Sues to Prevent Deportation
## 7                                   This Is Why Young People Really Voted for Trump
## 8                                Trump’s Moves on Greenland Appear to Be Backfiring
## 9                                          The Secret History of the War in Ukraine
## 10             Visiting Greenland, Vance Finds the Weather and the Reception Chilly
## 11                                      What Happens to Your Brain When You Retire?
## 12          Spring Break for the Teens of New York’s Elite: Sun, Fun and Networking
## 13                                   The ‘Iconic’ Stare That Conquered the Internet
## 14                               At a Prison Appearance, a $50,000 Watch Stands Out
## 15            Online ‘Pedophile Hunters’ Are Growing More Violent — and Going Viral
## 16                       It’s Trump vs. the Courts, and It Won’t End Well for Trump
## 17                                     Signal Chat Leak Angers U.S. Military Pilots
## 18                              The Worst Part of Pete Hegseth’s Group Chat Debacle
## 19                        Trump Asks Stefanik to Withdraw Bid to Be U.N. Ambassador
## 20                                   If Pete Hegseth Had Any Honor, He Would Resign
##                                                                                                                                                                                                           abstract
## 1                                                                                                         The Signal group chat is only the latest in a string of self-inflicted wounds by the new administration.
## 2  The chat’s contents, which were obtained by The Atlantic after its editor in chief was added to the Signal group, provide a revealing look at private conversations between top Trump administration officials.
## 3                                                                                     In public, President Trump has defended his national security adviser. But behind the scenes, he has cast around for advice.
## 4                                                                                                             This is certainly an administration that reminds us why the framers decided on separation of powers.
## 5                                                                                 States have been told that they can no longer use grants that were funding infectious disease management and addiction services.
## 6                       Yunseo Chung, a legal permanent resident who has lived in the U.S. since she was 7, participated in pro-Palestinian demonstrations. Immigration agents visited residences looking for her.
## 7                                                                                                                                                            Feeling empowered is different from numerical growth.
## 8                                                                      The Greenlandic government is calling an upcoming visit by Trump officials “aggressive,” pushing the island further from the United States.
## 9                                                                                             This is the untold story of America’s hidden role in Ukrainian military operations against Russia’s invading armies.
## 10                                  The trip was both a reconnaissance mission and a passive-aggressive reminder of President Trump’s determination to fulfill his territorial ambitions, no matter the obstacles.
## 11                                                                                                      It’s challenging to stay mentally sharp and healthy through the major transition. Careful planning is key.
## 12                                                Seniors from some of the nation’s most expensive high schools travel each year to a luxury resort in the Bahamas — trips that make school administrators cringe.
## 13                                                  Millions have been transfixed by videos of Karis Dadson, a California teenager who shows pigs at livestock competitions. She finds the whole thing very weird.
## 14                                                  Kristi Noem’s trip to a prison in El Salvador drew social media attention for the homeland security secretary’s choice to wear a gold Rolex in such a setting.
## 15                                                                                   With the rise of loosely moderated social media platforms, a fringe vigilante movement is experiencing a dangerous evolution.
## 16                                                                                                      The judiciary will never surrender to the president its constitutional role to interpret the Constitution.
## 17                                  Men and women who have taken to the air on behalf of the United States expressed bewilderment after the leak of attack plans. “You’re going to kill somebody,” one pilot said.
## 18                                                                                                                                                        And why the careless secretary of defense should resign.
## 19                                                                         The president said he wanted the New York Republican to stay in Congress to bolster the party’s slim House margin and protect her seat.
## 20                                                           A defense secretary intentionally using a civilian app to share sensitive war plans without noticing a journalist was in the chat would be egregious.
##                                                                                                   url
## 1                           https://www.nytimes.com/2025/03/28/opinion/trump-hegseth-signal-chat.html
## 2           https://www.nytimes.com/interactive/2025/03/25/us/signal-group-chat-text-annotations.html
## 3                      https://www.nytimes.com/2025/03/29/us/politics/trump-signal-michael-waltz.html
## 4                     https://www.nytimes.com/2025/03/24/opinion/trump-columbia-courts-law-firms.html
## 5                       https://www.nytimes.com/2025/03/26/health/trump-state-health-grants-cuts.html
## 6             https://www.nytimes.com/2025/03/24/nyregion/columbia-student-ice-suit-yunseo-chung.html
## 7                               https://www.nytimes.com/2025/03/26/opinion/young-maga-trump-vote.html
## 8                             https://www.nytimes.com/2025/03/24/world/europe/trump-greenland-us.html
## 9  https://www.nytimes.com/interactive/2025/03/29/world/europe/us-ukraine-military-war-wiesbaden.html
## 10                        https://www.nytimes.com/2025/03/28/us/politics/greenland-jd-vance-usha.html
## 11              https://www.nytimes.com/2025/03/26/well/mind/retirement-brain-mental-health-tips.html
## 12              https://www.nytimes.com/2025/03/25/nyregion/spring-break-paradise-island-bahamas.html
## 13                        https://www.nytimes.com/2025/03/23/style/karis-dadson-show-pigs-tiktok.html
## 14             https://www.nytimes.com/2025/03/28/style/kristi-noem-venezuela-prison-rolex-watch.html
## 15                  https://www.nytimes.com/interactive/2025/03/26/us/pedophile-hunting-violence.html
## 16                  https://www.nytimes.com/2025/03/23/opinion/trump-judge-venezuela-deportation.html
## 17                             https://www.nytimes.com/2025/03/27/us/politics/pilots-signal-leak.html
## 18                https://www.nytimes.com/2025/03/25/opinion/pete-hegseth-security-breach-resign.html
## 19                         https://www.nytimes.com/2025/03/27/us/politics/stefanik-trump-cabinet.html
## 20                     https://www.nytimes.com/2025/03/24/opinion/atlantic-hegseth-vance-houthis.html
##                                                                                    byline
## 1                                                                      By Hillary Clinton
## 2                                                                                        
## 3                                                      By Maggie Haberman and Tyler Pager
## 4                                                       By Gail Collins and Bret Stephens
## 5                               By Apoorva Mandavilli, Margot Sanger-Katz and Jan Hoffman
## 6                                                  By Jonah E. Bromwich and Hamed Aleaziz
## 7                                                                           By Neil Gross
## 8                                                    By Jeffrey Gettleman and Maya Tekeli
## 9                                                                          By Adam Entous
## 10                                                                     By David E. Sanger
## 11                                                                 By Mohana Ravindranath
## 12                                                                      By Dionne Searcey
## 13                                                                      By Scott Cacciola
## 14                                                                    By Joseph Bernstein
## 15 By Aric Toler, Neil Bedi, Aliza Aufrichtig, Joyce Ho, Natalie Reneau and Rumsey Taylor
## 16                                                                   By J. Michael Luttig
## 17                                                      By Helene Cooper and Eric Schmitt
## 18                                                    By David French and Vishakha Darbha
## 19                                                     By Annie Karni and Maggie Haberman
## 20                                                                        By David French
##    published_date  section
## 1      2025-03-28  Opinion
## 2      2025-03-25     U.S.
## 3      2025-03-29     U.S.
## 4      2025-03-24  Opinion
## 5      2025-03-26   Health
## 6      2025-03-24 New York
## 7      2025-03-26  Opinion
## 8      2025-03-24    World
## 9      2025-03-29    World
## 10     2025-03-28     U.S.
## 11     2025-03-26     Well
## 12     2025-03-25 New York
## 13     2025-03-23    Style
## 14     2025-03-28    Style
## 15     2025-03-26     U.S.
## 16     2025-03-23  Opinion
## 17     2025-03-27     U.S.
## 18     2025-03-25  Opinion
## 19     2025-03-27     U.S.
## 20     2025-03-24  Opinion

The “popular_articles_df” data frame shows the top 20 most popular NY Times viewed articles in the 7 days.