Search code examples
rapihttr

How correctly use request header with API data requests?


I'm trying to find the way to connect to Appannie's API with R using the httr package (have no experience with API connection at all). The API requires to include the request header Citation from appannie's site: Register an App Annie account and generate an API key. Add this key to your request header as follows:
Authorization: Bearer ''
citation over

I wrote the code which looks like this

query <- "http://api.appannie.com/v1/accounts/1000/sales?break_down=application+dat
&start_date=2012-01-01
&end_date=2012-02-01
&currency=USD
&countries=US
&page_index=1"
getdata<-GET(url=query, add_headers("Authorization: bearer 811b..."))

the command http_status(getdata) shows me "client error: (401) Unauthorized" can someone please help me with it, what do I do wrong?


Solution

  • You are not specifying the header correctly. add_headers(...) requires a named list.

    library(httr)    # for GET(...)
    library(rjson)   # for fromJSON(...)
    query <- "https://api.appannie.com/v1/accounts/1000/sales?break_down=application+dat&start_date=2012-01-01&end_date=2012-02-01&currency=USD&countries=US&page_index=1"
    getdata<-GET(url=query, add_headers(Authorization="bearer <your api key>"))
    fromJSON(content(getdata,type="text"))
    # $code
    # [1] 403
    # 
    # $error
    # [1] "Invalid connection account"
    

    This "works" in the sense that I don't get the 401 error. In my case the account 1000 does not exist.

    Regarding the http/https issue from the comment, http is despreciated and will no longer be accepted as of 2014-04-01, so you might as well start using https.