api_list <- c("httr","jsonlite")
for(i in api_list){
if(!(i %in% installed.packages())){
install.packages(i)
}
}
library(httr)
library(jsonlite)
Link: https://rapidapi.com/api-sports/api/api-nba
url <- "https://api-nba-v1.p.rapidapi.com/seasons"
api_response <- VERB("GET", url,
add_headers('X-RapidAPI-Key' = Sys.getenv('RAPID_API'),
'X-RapidAPI-Host' = 'api-nba-v1.p.rapidapi.com'),
content_type("application/octet-stream"))
api_response
## Response [https://api-nba-v1.p.rapidapi.com/seasons]
## Date: 2023-09-05 22:36
## Status: 200
## Content-Type: application/json
## Size: 112 B
content(api_response, "text")
## No encoding supplied: defaulting to UTF-8.
## [1] "{\"get\":\"seasons\\/\",\"parameters\":[],\"errors\":[],\"results\":8,\"response\":[2015,2016,2017,2018,2019,2020,2021,2022]}"
Response [https://api-nba-v1.p.rapidapi.com/seasons]
Date: 2023-09-04 20:05
Status: 200
Content-Type: application/json
Size: 112 B
The status of the response should be 200 indicating that the request was successful and a response was generated.
There should be information on the content type as well.
A quick preview of the content can be achieved by using the code snippet below and the output is shown for demonstration purposes.
content(api_response, "text")
[1] "{\"get\":\"seasons\\/\",\"parameters\":[],\"errors\":[],\"results\": 8,\"response\":[2015,2016,2017,2018,2019,2020,2021,2022]}"
typeof(api_response)
## [1] "list"
The json format which I initially learned about when studying python through the University of Michigan Runestone platform is a format of storing data as key-value pairs often also referred to as the dictionary format.
{
"name": "swaggy T"
"number of years": 32
}
rawToChar(api_response$content)
## [1] "{\"get\":\"seasons\\/\",\"parameters\":[],\"errors\":[],\"results\":8,\"response\":[2015,2016,2017,2018,2019,2020,2021,2022]}"
nba_data <- fromJSON(rawToChar(api_response$content))
nba_data <- as.data.frame(nba_data$response)
print(nba_data)
## nba_data$response
## 1 2015
## 2 2016
## 3 2017
## 4 2018
## 5 2019
## 6 2020
## 7 2021
## 8 2022