In this assignment, I will use The New York Times APIs, which provide a variety of data. First, I will sign up for an API key. Then, I’ll choose one API to work with and create an interface in R to fetch and read the JSON data from it. Finally, I will convert this data into an R DataFrame, making it easier to analyze and manipulate. This will help me learn how to work with web APIs and handle data in R.
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
# API Key
apikey <- "IsXIAthPjA6e9jFJJevYb5xrlSfecGDf"
# Construct the URL with the API key as a query parameter
theURL <- paste0("https://api.nytimes.com/svc/topstories/v2/world.json?api-key=", apikey)
# Make the GET request
stories <- GET(theURL)
# Check the status code
print(stories$status_code)
## [1] 200
summary(stories)
## Length Class Mode
## url 1 -none- character
## status_code 1 -none- numeric
## headers 23 insensitive list
## all_headers 1 -none- list
## cookies 7 data.frame list
## content 77089 -none- raw
## date 1 POSIXct numeric
## times 6 -none- numeric
## request 7 request list
## handle 1 curl_handle externalptr
#Parse data
parsed_data <- content(stories, "text", encoding = "UTF-8")
stories_df <- fromJSON(parsed_data)
#Extract relevant parts of the data
articles <- stories_df$results
#Convert to DataFrame
articles_df <- as.data.frame(articles, stringsAsFactors = FALSE)
# Rename the byline column to author
articles_df <- articles_df %>%
rename(author = byline)
# Remove "By " from the author column
articles_df$author <- gsub("^By ", "", articles_df$author)
# Select and print the title and author columns
selected_columns <- articles_df[, c("title", "author")]
print(selected_columns)
## title
## 1 Iran’s Supreme Leader Threatens Israel With ‘Crushing Response’ to Strikes
## 2 Israel Says Elite Naval Commandos Abducted Hezbollah Operative
## 3 Split on Economic Policy Puts Germany’s Government at Risk of Collapse
## 4 Kemi Badenoch Becomes First Black Woman to Lead Britain’s Conservative Party
## 5 How Missile Defense Works (and Why It Fails)
## 6 A Way Out of Mexico’s Constitutional Crisis? One Idea for Compromise Emerges.
## 7 Amid Flood Cleanup in Spain, Residents Try to Make Sense of the Disaster
## 8 Behind a Wall of Trees, Archaeologists Discover a Maya City
## 9 To Join This Club, a Member Must Die. And You Must Adore Verdi.
## 10 Russia Showers Cash on Men Enlisting in Ukraine War, Bringing Prosperity to Some Towns
## 11 Young African Voters Sour on the Parties That Ushered in Liberation
## 12 Israel’s Peace Talks in Gaza and Lebanon: What to Know
## 13 Can Iran and Israel Find a New Equilibrium?
## 14 Scenes of Trench Warfare in the Age of Drones
## 15 Global Summit on Nature Adopts a Novel Way to Pay for Conservation
## 16 Taking Time
## 17 Abortion Rights Issue Surfaces in Canada Before U.S. Election
## 18 Canadian Police Say They Dismantled Country’s Largest Drug Lab
## 19 How a Year of Rain Fell on Parts of Spain in Eight Hours
## 20 All Trick, No Treat: Dublin Crowds Turn Up for Halloween Parade That Wasn’t
## 21 How to Keep Traffic Moving? An Airport Puts Hugs on a Timer.
## 22 Israel Strikes Near Beirut as Diplomatic Push Shows No Sign of Success
## 23 As Russia Advances, U.S. Fears Ukraine Has Entered a Grim Phase
## 24 Rúben Amorim and the Unhelpful Burden of History
## 25 Death Toll Rises to 205 as More Rain Batters Spain
## 26 Destructive Israeli Raid in West Bank Kills 5, Palestinians Say
## 27 As Famine Stalks Gaza, Farmers Lament Their Many Losses
## 28 How Wagner’s Ruthless Image Crumbled in Mali
## 29 Repression Intensifies in the Country Hosting a Major Climate Meeting
## 30 She Was the First Nicaraguan to Be Crowned Miss Universe. Can She Ever Go Home?
## 31 Can Axions Save the Universe?
## 32 Botswana Voters Hand Governing Party a Stunning Rebuke
## 33 Friday Briefing
## 34 In Spanish Town Devastated by Flood, a Grim Search for Bodies
## 35 Mexico’s New President Faces Her First Major Crisis
## 36 Trump Had an ‘America First’ Foreign Policy. But It Was a Breakdown in American Policymaking.
## 37 Friday Briefing: The Global Stakes of the U.S. Election
## author
## 1 Liam Stack
## 2 Euan Ward, Aaron Boxerman and Maria Abi-Habib
## 3 Steven Erlanger and Christopher F. Schuetze
## 4 Mark Landler and Stephen Castle
## 5 Agnes Chang and Samuel Granados
## 6 Simon Romero and Paulina Villegas
## 7 Emma Bubola
## 8 Alan Yuhas
## 9 Elisabetta Povoledo
## 10 Neil MacFarquhar and Milana Mazaeva
## 11 John Eligon and Yvonne Mooka
## 12 Ephrat Livni
## 13 Amanda Taub
## 14 Tyler Hicks
## 15 Catrin Einhorn
## 16 Melissa Kirsch
## 17 Vjosa Isai
## 18 Vjosa Isai
## 19 Raymond Zhong
## 20 Claire Moses and Victor Mather
## 21 Eve Sampson
## 22 Aaron Boxerman
## 23 Julian E. Barnes, Eric Schmitt, Helene Cooper and Kim Barker
## 24 Rory Smith
## 25 José Bautista and Lynsey Chutel
## 26 Liam Stack and Fatima AbdulKarim
## 27 Liam Stack and Abu Bakr Bashir
## 28 Christiaan Triebert, Elian Peltier, Riley Mellen and Sanjana Varghese
## 29 Anton Troianovski
## 30 James Wagner and Kirsten Luce
## 31 Dennis Overbye and Katrina Miller
## 32 Yvonne Mooka and John Eligon
## 33 Natasha Frost
## 34 Emma Bubola
## 35 Natalie Kitroeff and Emiliano Rodríguez Mega
## 36 David E. Sanger
## 37 Gaya Gupta
In this assignment, I faced challenges when attempting to create a DataFrame before properly parsing the JSON data. Parsing is essential when working with JSON because it converts the structured text into a format that R can easily manipulate. Through this process, I learned the importance of extracting relevant information from the API response and transforming it into a usable DataFrame.