Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How correctly use request header with API data requests?

Tags:

r

api

httr

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?

like image 347
andrew-zmeul Avatar asked Mar 26 '14 17:03

andrew-zmeul


People also ask

How headers are used in API?

HTTP Headers are an important part of the API request and response as they represent the meta-data associated with the API request and response. Headers carry information for: Request and Response Body. Request Authorization.

What is a good example of when you would use a request header in an API?

Some common examples of Request Headers would be: Authorization: Send credentials for basic HTTP authentication to give permission for access. Cache-Control: Tell the browser how long a resource is eligible to be cached and re-used.

What is request header in REST API example?

Request headersIndicates the content type that is used in the body of the request. The supported content type is XML. application/xml. If-Match. Including If-Match in the header enables optimistic updating with ETag.


1 Answers

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.

like image 175
jlhoward Avatar answered Oct 07 '22 00:10

jlhoward