我正在学习如何使用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
答案 0 :(得分:0)
以下是一些入门指南:
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))
答案 1 :(得分:0)
通过将标头中的内容替换为正文,我能够成功地在 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 错误。一旦我移动它们 o 身体收到 200 状态并且令牌被成功检索。如果您可以提供您在 R 中尝试过的内容,可以帮助您进行故障排除。