1

I am trying to get data from the mobile analytics service Localytics via their API (https://api.localytics.com/docs#query). In particular I would like to translate the following cURL command in R:

curl --get  'https://api.localytics.com/v1/query' \
 --user 'API_KEY:API_SECRET' \
 --data 'app_id=APP_ID' \
 --data 'metrics=users' \
 --data 'dimensions=day' \
 --data-urlencode 'conditions={"day":["between","2013-04-01","2013-04-07"]}'

My R code looks like this at the moment. APIKey and API secret are of course replaced by the actual keys. However, I receive an error stating that at least a dimension or a metric has to be specified.

object <- getURL('https://api.localytics.com/v1/query', userpwd = "API_Key:API_Secret", httpheader=list(app_id = "app_id=03343434353534",
metrics = "metrics=users",
dimensions = "dimensions=day",
conditions = toJSON('conditions={"day":["between","2014-07-01","2014-07-10"]}')),  ssl.verifypeer = FALSE)

What changes would be necessary to get it to work.

Thanks in advance for helping me out, Peter

2 Answers2

1

This is particular easy with the dev version of httr:

library(httr)

r <- POST('https://api.localytics.com/v1/query',  
  body = list(
    app_id = "APP_ID",
    metrics = "users",
    dimensions = "day",
    conditions = list(
      day = c("between", "2014-07-01", "2004-07-10")
    )
  ), 
  encode = "json",
  authenticate("API_key", "API_secret")
)
stop_for_status(r)
content(r)

(I converted the request to a POST and used json encoding for everything, as describe in the API docs).

If you want to see exactly what's being sent to the server, use the verbose() config.

hadley
  • 102,019
  • 32
  • 183
  • 245
0

It looks like getURL passes the parameters you quested as HTTP headers and not as querystring data as your curl call does. You should use getForm instead. Also, I wasn't sure from which library your toJSON function came form, but that's at least not the right syntax for the one from rsjon.

Anyway, here's a call from R which should produce the same HTTP call are your curl command

library(rjson)
library(RCurl)
object <- getForm('https://api.localytics.com/v1/query',  
    app_id = "APP_ID",
    metrics = "users",
    dimensions = "day",
    conditions = toJSON(list(day=c("between","2014-07-01","2004-07-10"))),  
    .opts=curlOptions(
        userpwd = "API_Key:API_Secret",  httpauth = 1L)
)

I found that using the site http://requestb.in/ is very helpful in debugging these problems (and that's exactly what I used to create this solution). You can send requests to their site and they record the exact HTTP message that was sent so you can compare different methods.

The httpauth part was from this SO question which seemed to be required to trigger authentication for the test site; you may not need it for the "real" site.

Community
  • 1
  • 1
MrFlick
  • 195,160
  • 17
  • 277
  • 295