Read JSON Data from Web APIs using R
Last Updated :
30 Jan, 2023
The Application Programming Interface allows users to use certain features like creating, reading, updating, and deleting CRUD actions without directly exposing the code. This is mostly done in the form of JavaScript Object Notation which is a text-based format for representing structured data.
Before going forward we should understand basic API calls. The CRUD operations can be performed with an API by POST, GET, PUT, and DELETE methods respectively. Of course, some methods like PUT, POST, and DELETE need authentication. In this article, we are going to see how to make an API call for getting the information using the GET method.
Take a look at this API documentation. It gives information about a word, its synonyms, etc. And if you look at this URL, it is giving us information about the word geek which is in JSON format, and looks like this:
Dictionary API to get the meaning of words
Calling from R
To call this URL with a GET request in R Programming Language, we need a library called httr which does not come pre-installed. So go ahead and install it. To use its functionalities, include this library in the code.
R
install.packages ( "httr" )
library (httr)
|
Now, let’s call the URL with the GET method and store it in wordInfo:
The GET function returns a list with all the information about the server as well.
Raw data fetched via API
To get the content out of it, we need to convert this using the rawToChar function. But before that install, a library called jsonlite to work with JSON format.
R
install.packages ( "jsonlite" )
library (jsonlite)
rawToChar (wordInfo$content)
|
Output:
Raw data fetched via API
Now that we got our data in JSON format, to make it more clean and easy to work, we will use fromJSON function.
R
data <- fromJSON ( rawToChar (wordInfo$content))
|
Output:
Using fromJSON method to get data from JSON to R
To extract the meanings,
Output:
Data extracted from the JSON File
It is a list, so we can use:
R
data$meanings[[1]][[2]][[1]]$definition
|
Output:
'A carnival performer specializing in bizarre and unappetizing behavior.'
'A person who is intensely interested in a particular field or hobby
and often having limited or nonstandard social skills. Often used with
an attributive noun.'
'(by extension) An expert in a technical field, particularly one having
to do with computers.''The subculture of geeks; an esoteric subject of
interest that is marginal to the social mainstream; the philosophy, events,
and physical artifacts of geeks; geekness.''An unfashionable or socially
undesirable person.'
You can also play with strings and do something like this:
R
library (httr)
library (jsonlite)
word <- "competition"
data <- fromJSON ( rawToChar (wordInfo$content))
data$meanings[[1]][[2]][[1]]$definition
|
Output:
'The action of competing.'
'A contest for a prize or award.'
'The competitors in such a contest.'
Share your thoughts in the comments
Please Login to comment...