Say*_*ari 5 api r httr jsonlite
我正在学习如何使用 R 中的 API 获取数据。我知道其目的httr
是为curl 包提供一个包装器。\n我为了向 API 发出请求而遵循的文档具有以下 HTTP 请求格式。下面的代码将用于生成令牌
curl -s \\\n -d "client_id=clientid\xe2\x80\x9d \\\n -d "username=user\xe2\x80\x9d \\\n -d "password=pwd\xe2\x80\x9d \\\n -d "grant_type=password" \\\n -d "scope=openid email" \\\n "https://auth.com/token"\n
Run Code Online (Sandbox Code Playgroud)\n\n之后,我将使用令牌通过此请求与 API 进行通信
\n\ncurl --header "Content-Type: application/json" \\\n --header "Accept: application/+json" \\\n --header "Authorization: Bearer token_goes_here\xe2\x80\x9c \\\n --request GET \\\n --url "https://api-sitename.org/sections?parent_id=0"\n
Run Code Online (Sandbox Code Playgroud)\n\n最初,我在终端中运行这两个请求,它们成功了,我收到了 JSON 格式的响应。我的问题是,如何在 R 脚本中运行这些请求,以便获得响应并将它们存储在 R studio 全局环境中?我的目标是最终将数据集从API加载到Rstudio工作环境中。\nT
\n这里有一些可以帮助您开始的东西:
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))
Run Code Online (Sandbox Code Playgroud)