使用密钥连接到R中的Rest API

贾里德·马克斯

这是一个简单的问题,但我仍然不知道。我想用我的API密钥连接到REST API。我已经浏览了上的文档httrjsonlite但仍然不知道如何设置API密钥。

这是端点-https://api.tiingo.com/tiingo/daily//prices?startDate=2012-1-1&endDate=2016-1-1?

我尝试GET在此URL上使用该函数,并key在调用中指定我的API密钥我也试过了api_key = key我总是收到401错误。

谢谢

hrbrmstr

API期望其中包含Authorization标头Token yOuRAsSiGnEdT0k3n您应该将令牌存储在诸如环境变量之类的东西中,这样它就不会卡在脚本中。TIINGO_TOKEN把它放进去了~/.Renviron

您可以创建一个辅助函数,以减少调用的麻烦:

library(httr)
library(jsonlite)
library(tidyverse)
library(hrbrthemes)

get_prices <- function(ticker, start_date, end_date, token=Sys.getenv("TIINGO_TOKEN")) {

  GET(
    url = sprintf("https://api.tiingo.com/tiingo/daily/%s/prices", ticker),
    query = list(
      startDate = start_date,
      endDate = end_date
    ),
    content_type_json(),
    add_headers(`Authorization` = sprintf("Token %s", token))
  ) -> res

  stop_for_status(res)

  content(res, as="text", encoding="UTF-8") %>%
    fromJSON(flatten=TRUE) %>%
    as_tibble() %>%
    readr::type_convert()

}

现在,您只需传递参数即可:

xdf <- get_prices("googl", "2012-1-1", "2016-1-1")

glimpse(xdf)
## Observations: 1,006
## Variables: 13
## $ date        <dttm> 2012-01-03, 2012-01-04, 2012-01-05, 2012-01-06, 2...
## $ close       <dbl> 665.41, 668.28, 659.01, 650.02, 622.46, 623.14, 62...
## $ high        <dbl> 668.15, 670.25, 663.97, 660.00, 647.00, 633.80, 62...
## $ low         <dbl> 652.3700, 660.6200, 656.2300, 649.7900, 621.2300, ...
## $ open        <dbl> 652.94, 665.03, 662.13, 659.15, 646.50, 629.75, 62...
## $ volume      <int> 7345600, 5722200, 6559200, 5380400, 11633500, 8782...
## $ adjClose    <dbl> 333.7352, 335.1747, 330.5253, 326.0164, 312.1937, ...
## $ adjHigh     <dbl> 335.1095, 336.1627, 333.0130, 331.0218, 324.5017, ...
## $ adjLow      <dbl> 327.1950, 331.3328, 329.1310, 325.9010, 311.5768, ...
## $ adjOpen     <dbl> 327.4809, 333.5446, 332.0901, 330.5955, 324.2509, ...
## $ adjVolume   <int> 3676476, 2863963, 3282882, 2692892, 5822572, 43955...
## $ divCash     <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,...
## $ splitFactor <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,...

而且,它“有效”:

ggplot(xdf, aes(date, close)) +
  geom_segment(aes(xend=date, yend=0), size=0.25) +
  scale_y_comma() +
  theme_ipsum_rc(grid="Y")

在此处输入图片说明

您可以针对其他API端点遵循此惯用法。完成后,考虑制作一个包装,以便社区可以使用您所获得的知识。

您可以执行一些额外的步骤,并实际制作带有日期或数字参数的函数,以实际采用那些类型的R对象,并在输入时对其进行验证。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章