So I am trying to call a "Content-Type: text/csv" API and then convert it into a readable format in r.
The call was successful, however managing the returned object is the current challenge.
Although, I have seen examples with just JSON Object, and I believe managing this content-type should be easier to handle but this is my first direct API call.
Here is what I have tried:
library(tidyverse)
library(rjson)
library(jsonlite)
library(RCurl)
library(httr)
## Export Data URL
url = 'http://api.abc.com/api/users'
headers = c('accept' = {'application/json'},
'Accept-Language' = {'hi_IN'},
'User-Agent' = {'Mozilla/4.0'})
## Raw Data
api_raw <- GET(url, add_headers(headers))
api_raw
As Shah as pointed out, I have been able to isolate the text response, however the challenge now is in converting this data into a readable form.
I have tried the following:
setwd("~/Automated Reports/R/BME-Export")
data <- httr::content(api_raw, as = 'text')
data_2 <- jsonlite::fromJSON(data)
Here I get this error
Error: parse error: unallowed token at this point in JSON text ,Lat,Long,Popu (right here) ------^ In addition: Warning messages: 1: package ‘RCurl’ was built under R version 4.1.1 2: package ‘httr’ was built under R version 4.1.1
## Read the data as csv
df_api <- read.csv(data)
Here I get the following error
Error in file(file, "rt") : cannot open the connection In addition: Warning message: In file(file, "rt") : cannot open file
CodePudding user response:
Try using httr::content
function.
data <- httr::content(api_raw, 'text')