Search code examples
rapihttr

Calling API with header from R


I have an api like below. This code sample for Node.js. Without header it is easy to call an api from R but with header i could not do it. API address and header info is given in the sample code so who can help me to convert this code to R code. Thanks.

var request = require("request");

var options = {
  method: 'GET',
  url: 'https://covid-193.p.rapidapi.com/statistics',
  headers: {
    'x-rapidapi-host': 'covid-193.p.rapidapi.com',
    'x-rapidapi-key': 'cc818ada02msh65ebe8a8658d181p130600jsn1ee371ee7fbe'
  }
};

request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log(body);
});

Solution

  • httr::add_headers just requires "named header values". So you just need

    library(httr)
    
    GET("https://covid-193.p.rapidapi.com/statistics")
    # Response [https://covid-193.p.rapidapi.com/statistics]
    #   Date: 2020-03-29 05:02
    #   Status: 401
    #   Content-Type: application/json
    #   Size: 139 B
    
    GET("https://covid-193.p.rapidapi.com/statistics",
        add_headers(`x-rapidapi-host`='covid-193.p.rapidapi.com',
                    `x-rapidapi-key`= 'cc818ada02msh65ebe8a8658d181p130600jsn1ee371ee7fbe'))
    # Response [https://covid-193.p.rapidapi.com/statistics]
    #   Date: 2020-03-29 05:02
    #   Status: 200
    #   Content-Type: application/json
    #   Size: 37.9 kB
    

    The first response is "401 Unauthorized", the second is "200 Success". BTW, if that API key is important to you, you might want to revoke it now that the rest of the world has it.