Problem with authorization to COINAPI REST API with custom header and key in R

1k Views Asked by At

I would like to connect to COINAPI resources. They provide two types of authorization. https://docs.coinapi.io/#authorization

  1. Custom authorization header named X-CoinAPI-Key
  2. Query string parameter named apikey

When I am using the first method, it is working with basic requests. But respond with an error in more advanced.

endpoint<-"/v1/exchangerate/BTC?apikey="

But when I specify endpoint like this:

endpoint <- "/v1/trades/BITSTAMP_SPOT_BTC_USD/history?time_start=2016-01-01T00:00:00/?apikey="

I got error 401.

The second method is not working so far, I do not really understand how can I specify custom header name here.

I need to get data from here:

https://rest.coinapi.io/v1/ohlcv/BTC/USD/history?period_id=1DAY&time_start=2017-01-02T00:00:00.0000000Z&time_end=2019-01-02T00:00:00.0000000Z&limit=10000&include_empty_items=TRUE

I would appreciate any help on this issue.

1. method (working)

library(httr)
library(jsonlite)

base     <- "https://rest.coinapi.io"
endpoint <- "/v1/exchangerate/BTC?apikey="
api_key  <- <KEY>
call <- paste0(base, endpoint, api_key)
call  

get_prices <- GET(call)
http_status(get_prices)
class(get_prices)
get_prices_text <- content(get_prices, "text", encoding = 'UTF-8')  
get_prices_json <- fromJSON(get_prices_text, flatten = TRUE) 
names(get_prices_json)
get_prices_json$asset_id_base
head(get_prices_json$rates)
data<-as.data.frame(get_prices_json)

2. method (not working)

key<-<KEY>
GET(
  url = sprintf("https://rest.coinapi.io/v1/exchangerate/BTC"),
  add_headers(`Authorization` = sprintf("X-CoinAPI-Key: ", key))
) -> res
http_status(res)
1

There are 1 best solutions below

0
On

From reading the examples in the documentation, it looks like it's just looking for a simple header, not an "Authorization" header specifically. Try this

GET(
  url = sprintf("https://rest.coinapi.io/v1/exchangerate/BTC"),
  add_headers(`X-CoinAPI-Key` = key)
) -> res
http_status(res)