在发出API请求时使用httr软件包进行身份验证

问题描述 投票:0回答:1

我正在学习如何使用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 api httr jsonlite
1个回答
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))
© www.soinside.com 2019 - 2024. All rights reserved.