使用R

时间:2019-03-31 17:10:52

标签: r rest api httr response.addheader

我想连接到COINAPI资源。它们提供两种类型的授权。 https://docs.coinapi.io/#authorization

  1. 名为X-CoinAPI-Key的自定义授权标头
  2. 查询名为apikey的字符串参数

当我使用第一种方法时,它正在处理基本请求。但是在更高级时会出现错误。

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

但是当我这样指定端点时:

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

我收到错误401。

第二种方法到目前为止还无法正常工作,我不太了解如何在此处指定自定义标头名称。

我需要从此处获取数据:

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

在此问题上的任何帮助,我们将不胜感激。

1。方法(工作)

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。方法(不起作用)

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 个答案:

答案 0 :(得分:0)

通过阅读文档中的示例,看起来它只是在寻找简单的标头,而不是专门的“ Authorization”标头。试试这个

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