Open In App

How to Make HTTP request using httr package in R Language

Last Updated : 28 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to make an HTTP request using the GET method in R Programming Language with httr library. 

We will be covering basic steps to get you started by making HTTP requests and scrapping all the data from a site in a simple way. You can also use it to scrape data from any website and use it to access API and much more. HTTP requests might be complicated but R language syntax makes it much easier in comparison with other languages.

Installation

httr library is used to make http requests in R language as it provides a wrapper for the curl package.

Syntax to install httr package:

install.packages(“httr”)

Making a simple HTTP request

Now we have httr package installed so we need to import it to make our HTTP request. library(httr) will import httr package. Now to make an HTTP request we will be using GET() of httr package and pass a URL, the GET() will return raw data so we will store it in a variable and then print it using print().

Note: You need not use install.packages() if you have already installed the package once.

R




# installing packages
install.packages("httr")
  
# importing packages
library(httr)
  
# GET() method will store the raw data
# in response variable
response < - GET("https://geeksforgeeks.org")
  
# printing response/data
print(response)


Output:

You might have noticed this output is not exact URL data that’s because it is raw data.

Convert raw data to char format

To convert raw data in char format we need to use rawToChar() and pass variable_name$content in it just like we did in this example.

R




# installing packages
install.packages("httr")
  
# importing packages
library(httr)
  
# GET() method will store the raw 
# data in r variable
  
# rawToChar() will convert raw data 
# to char and store in response variable
response < - rawToChar(r$content)
  
# print response
print(response)


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads