Search code examples
rjsonhttp-headershttr

Calling API in R (httr package)


Hope you can help me, I am not an expert on integrations :)

There is a system called social bakers (doc: https://api.socialbakers.com) where I try to fetch some data. I have a token, a secret and I think I am doing the first part right.

I am just trying to connect using this snippet:

library(httr)

req <- GET("https://api.socialbakers.com/0/facebook/profiles", 
       authenticate("token", "secret", type = "basic"))
stop_for_status(req)
content(req)

This works perfectly. I have a JSON response which I can parse into a table. My question is about another URL like this:

library(httr)

req <- GET("https://api.socialbakers.com/0/facebook/metrics", 
       authenticate("token", "secret", type = "basic"))
stop_for_status(req)
content(req)

The same code, doesn't work anymore, returning

code 405 HTTP Method Invalid

I am not sure if I am doing right, some part of the doc says I have to use base64 on the header, but why is working in the first part? Some advice will be really appreciated :)

EDIT:

SOLVED: In that case, the correct method to interact with the API is using the POST method to send the parameters to the service.

The following snippet was used.

library(httr)
library(RCurl)
library(jsonlite)

doc <- POST("https://api.socialbakers.com/0/facebook/metrics",
        authenticate("user",
                     "pass",
                     type = "basic"), 
        body = list(
          date_start = "2016-01-11",
          date_end = "2016-01-12",
          profiles = c("12345", "123456"),
          metrics = c("fans_count_lifetime", "fans_change"))
        , encode = "json")
stop_for_status(doc)
content(doc)

Solution

  • In that case, the correct method to interact with the API is using the POST method to send the parameters to the service.

    The following snippet was used.

    library(httr)
    library(RCurl)
    library(jsonlite)
    
    doc <- POST("https://api.socialbakers.com/0/facebook/metrics",
        authenticate("user",
                     "pass",
                     type = "basic"), 
        body = list(
          date_start = "2016-01-11",
          date_end = "2016-01-12",
          profiles = c("12345", "123456"),
          metrics = c("fans_count_lifetime", "fans_change"))
        , encode = "json")
    stop_for_status(doc)
    content(doc)enter code here