【发布时间】:2021-06-23 03:02:11
【问题描述】:
对 API 来说是全新的,而且有点过头了。阅读了一下并四处寻找,但仍然感到困惑。我得到了在 curl 中运行的以下代码,以使用 oauth2 和密码授权生成令牌。我想在 R 中实现这段代码并遇到一些问题。
curl -H "Content-type: application/x-www-form-urlencoded" -H "Authorization: Basic xxxyyy123xxx==" -d "grant_type=password&username={username}&password={password}" https://{website}.com/rest/v2/oauth/token
当我在终端中运行上述命令时,它会生成一个令牌,我已使用此代码在 R 中成功使用该令牌:
token <- {character string generated by the above curl command}
call <- "https://{website}.com/rest/v2/services/APIService/getRegistryRecordByAccessionID?id={id#}"
df <- as.data.frame(fromJSON(content(httr::GET(call, add_headers(Authorization = paste("Bearer", token))), "text"), flatten = TRUE))
我想要的只是在 R 中生成令牌,而不是像以前那样使用另一个程序。这就是我的错误出现的地方。我认为的基本格式是:
token <- oauth2.0_token(endpoint = oauth_endpoint(
authorize = NULL,
access = "https://{website}.com/rest/v2/oauth/token"),
app = oauth_app(), #not sure how to set this up
use_basic_auth = T,
add_headers(Content-type = "application/x-www-form-urlencoded",
Authorization = "Basic xxxyyy123xxx==") #not sure if i need the authorization header here, I believe I need the content-type heder
)
【问题讨论】:
-
如果你只是想复制那个 CURL 命令,那么你不需要
oauth2.0_token。您可以使用httr::POST更轻松地执行基本请求。还有 curlconverter 包可以更直接地将 CURL 转换为 R。 -
我将如何使用上面的 CURL 命令通过 POST 来解决这个问题?
-
你可以试试
httr::POST("https://{website}.com/rest/v2/oauth/token", body=list(grant_type="password", "username="{username}", password="{password}"), encode="form")查看帮助页面:httr.r-lib.org/reference/POST.html -
@MrFlick 我刚刚使用您以前喜欢的 curlconverter 包创建了它。谢谢你。但这会返回一个响应对象,其中不包含我要集成到我的 GET 动词中的令牌。谢谢。
-
当我们无法实际运行和测试代码时,很难提供具体的建议。如果您是
httr的新手,请务必阅读帮助页面和可用示例。您使用content()从响应对象中获取数据。