【问题标题】:Authenticate using httr package when Making API Requests发出 API 请求时使用 httr 包进行身份验证
【发布时间】:2020-05-12 10:11:55
【问题描述】:

我正在学习如何使用 R 中的 API 获取数据。我知道 httr 的目的是为 curl 包提供一个包装器。 为了向 API 发出请求,我正在遵循的文档具有以下 HTTP 请求格式。下面这段代码将用于生成令牌

curl -s \
     -d "client_id=clientid” \
     -d "username=user” \
     -d "password=pwd” \
     -d "grant_type=password" \
     -d "scope=openid email" \
     "https://auth.com/token"

之后,我将使用令牌通过此请求与 API 进行通信

curl --header "Content-Type: application/json" \
     --header "Accept: application/+json" \
     --header "Authorization: Bearer token_goes_here“ \
     --request GET \
     --url "https://api-sitename.org/sections?parent_id=0"

最初,我在终端中运行这两个请求,它们都成功了,我得到了 JSON 格式的响应。我的问题是,如何在 R 脚本中运行这些请求,以便我得到响应并且它们是否存储在 R Studio 全局环境中?我的目标是最终将数据集从 API 加载到 Rstudio 工作环境。 T

【问题讨论】:

  • 你成功了吗?我有类似的问题,它在终端中工作但在 R 中失败。我传递它的方式有些问题

标签: r api httr jsonlite


【解决方案1】:

以下是帮助您入门的内容:

library(httr)
resp <- POST("https://auth.com/token", 
    body=list(client_id="clientid",
        username="user",
        password="pwd",
        grant_type="password",
        scope="openid email")
)
#parse for auth token here
content(resp, "text")

get_resp <- GET("https://api-sitename.org/sections?parent_id=0",
    add_headers("Content-Type"="application/json",
        Accept="application/+json",
        "Authorization"=paste("Bearer", token))

【讨论】:

    【解决方案2】:

    通过将标题中的内容替换为正文,我能够在 R 中成功获取 API 调用。 这是我的代码

    #' Th base url
    base_url <- "your/url/endpoint/for/token"
    #  base64 encoded client id, my end-point requires to encone the client id to base64
    c_id <- RCurl::base64(txt = "clinetid:sceret", mode = "character")
    #' headers
    headers <- httr::add_headers(
      "Authorization" = paste("Basic",c_id, sep = " ")
    )
    # move everything else to the body. grant_type and password were requested by the endpoint
    body <- list(
      username = "your username",
      password = "your password",
      grant_type = "password",
      scope = "read"
    )
    
    #' post call to get the token
    httr::POST(
      url  = base_url,
      body = body,
      config  = headers,
      httr::accept_json()
    )
    

    当我在正文中有用户名和密码时,我收到了 400 和 403 错误。一旦我将它们移开,身体就会收到 200 状态,并且成功检索了令牌。如果您可以提供您在 R 中尝试过的内容,可以帮助您进行故障排除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-14
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 2014-10-02
      相关资源
      最近更新 更多