在 R 中调用 REST API
使用 API 密钥进行身份验证,分页获取结果并存储 API 响应
在 R 中调用 REST API 是 CoddyKit 上的免费 R Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 R Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 R Academy 课程共包含 4 节课。
REST API 概念
REST API 会针对资源 URL 使用 HTTP 方法(GET、POST、PUT、DELETE)。响应通常采用 JSON 格式。API 可能要求身份验证、处理分页并实施速率限制。一个优秀的 R API 客户端应处理这三方面。
library(httr2)
# REST API anatomy:
# Base URL: https://api.example.com/v1
# Resources: /users, /products, /orders
# Methods:
# GET /users -> list users
# POST /users -> create user
# GET /users/42 -> get user 42
# PUT /users/42 -> update user 42
# DELETE /users/42 -> delete user 42
# Query parameters for filtering/pagination:
# GET /users?page=2&size=20&sort=name
cat('REST = stateless + resource-based + HTTP methods')Bearer 令牌身份验证
大多数现代 API 使用 Bearer 令牌(OAuth 2.0)。请使用 Sys.setenv() 将令牌存储在环境变量中,或将其存储在 .Renviron 文件中。切勿将令牌硬编码到脚本中。
library(httr2)
# Store token securely in .Renviron:
# GITHUB_PAT=ghp_your_token_here
# Access at runtime:
token <- Sys.getenv('GITHUB_PAT')
if (nchar(token) == 0) token <- 'demo_token'
# Use in requests:
# resp <- request('https://api.github.com/user') |>
# req_auth_bearer_token(token) |>
# req_headers('Accept' = 'application/vnd.github.v3+json') |>
# req_perform() |>
# resp_check_status()
# result <- resp_body_json(resp)
# result$login # your GitHub username
cat('Token from env:', if(nchar(token)>0) 'found' else 'missing')构建可复用的 API 客户端
请在构造函数中封装基础 URL、身份验证和错误处理。每个 API 端点都应成为调用该基础函数的一个方法——这是 R API 程序包的标准模式。
library(httr2)
# API client constructor
new_api_client <- function(base_url, token) {
list(
base_req = request(base_url) |>
req_auth_bearer_token(token) |>
req_headers('Accept' = 'application/json') |>
req_retry(max_tries = 3)
)
}
# Method: GET /users
get_users <- function(client, page = 1, size = 20) {
resp <- client$base_req |>
req_url_path_append('users') |>
req_url_query(page = page, size = size) |>
req_perform() |>
resp_check_status()
resp_body_json(resp, simplifyVector = TRUE)
}
# client <- new_api_client('https://api.example.com', token)
# users <- get_users(client, page = 1)
cat('Reusable client pattern: base request + methods')使用 resp_link_url() 实现分页
许多 API 使用 Link 标头实现分页(RFC 5988):响应中会包含 Link: <url>; rel="next" 标头。resp_link_url(resp, 'next') 会自动提取下一页的 URL。
library(httr2)
# Generic paginator using Link headers
fetch_all_pages <- function(initial_url, token, max_pages = 50) {
all_results <- list()
next_url <- initial_url
page <- 1
while (!is.null(next_url) && page <= max_pages) {
resp <- request(next_url) |>
req_auth_bearer_token(token) |>
req_perform() |>
resp_check_status()
all_results[[page]] <- resp_body_json(resp, simplifyVector = TRUE)
# Follow Link: <url>; rel='next' header
next_url <- tryCatch(
resp_link_url(resp, 'next'),
error = function(e) NULL
)
page <- page + 1
}
do.call(rbind, all_results)
}
cat('resp_link_url() follows RFC 5988 pagination')基于游标的分页
一些 API(Twitter、Slack)使用游标而不是页码。响应中会包含 next_cursor 或 next_page_token 字段。请将其作为查询参数传递给下一次请求。
library(httr2)
# Cursor-based pagination pattern
fetch_cursor_pages <- function(base_url, token, max_pages = 100) {
all_data <- list()
cursor <- NULL
page <- 1
repeat {
req <- request(base_url) |>
req_auth_bearer_token(token)
if (!is.null(cursor))
req <- req |> req_url_query(cursor = cursor)
resp <- req |> req_perform() |> resp_check_status()
body <- resp_body_json(resp)
all_data[[page]] <- body$results
cursor <- body$next_cursor # NULL if last page
if (is.null(cursor) || page >= max_pages) break
page <- page + 1
}
do.call(c, all_data)
}
cat('Cursor pagination: safer for large/changing datasets')妥善处理错误
用于生产环境的 API 客户端会分别捕获 HTTP 错误和网络故障。请在 req_perform() 外层使用 tryCatch(),并检查 httr2_http_* 错误条件,以便根据状态进行处理。
library(httr2)
safe_api_call <- function(req) {
tryCatch(
req |> req_perform() |> resp_check_status(),
httr2_http_401 = function(e) {
stop('Authentication failed. Check your token.')
},
httr2_http_403 = function(e) {
stop('Forbidden. Insufficient permissions.')
},
httr2_http_404 = function(e) {
message('Resource not found, returning NULL')
return(NULL)
},
httr2_http_429 = function(e) {
stop('Rate limit exceeded. Try again later.')
},
error = function(e) {
stop(paste('Request failed:', conditionMessage(e)))
}
)
}
cat('Match on specific httr2_http_NNN conditions')缓存 API 响应
缓存 API 响应可以避免开发期间发送不必要的请求。httr2 中的 req_cache() 会将响应缓存在磁盘上,并遵循 Cache-Control 标头。手动缓存适用于任何 API。
library(httr2)
# httr2 built-in disk cache
# resp <- request('https://api.example.com/static-data') |>
# req_cache(tempdir(), max_age = 3600) |> # 1 hour TTL
# req_perform()
# Manual cache pattern
cached_api_call <- function(url, cache_file, max_age = 3600) {
if (file.exists(cache_file)) {
age <- as.numeric(Sys.time() - file.mtime(cache_file))
if (age < max_age) {
cat('Cache hit\n')
return(readRDS(cache_file))
}
}
cat('Cache miss, fetching...\n')
# result <- resp_body_json(request(url) |> req_perform())
# saveRDS(result, cache_file)
# result
}
cached_api_call('https://example.com/api', 'cache.rds')使用 req_perform_parallel() 发送并行请求
req_perform_parallel() 会并发发送多个请求,从而大幅缩短批量操作的总耗时。请将其与 req_throttle() 结合使用,以便在并行执行期间遵守速率限制。
library(httr2)
# Build a list of requests
item_ids <- 1:5
reqs <- lapply(item_ids, function(id) {
request(paste0('https://jsonplaceholder.typicode.com/todos/', id))
})
# Execute all in parallel (requires internet)
# resps <- req_perform_parallel(
# reqs,
# on_error = 'continue', # skip failures
# progress = TRUE
# )
# results <- lapply(resps, resp_body_json)
# titles <- sapply(results, function(r) r$title)
# print(titles)
# on_error options:
# 'stop' -> abort on first failure
# 'continue' -> collect errors, keep going
cat('Parallel: much faster for many independent calls')处理速率限制
API 会通过响应标头传达速率限制状态:X-RateLimit-Remaining、X-RateLimit-Reset 和 Retry-After。读取这些标头即可实现智能退避。
library(httr2)
respect_rate_limit <- function(resp) {
# Check remaining calls
remaining <- resp_header(resp, 'x-ratelimit-remaining')
if (!is.na(remaining) && as.integer(remaining) < 5) {
reset_at <- as.integer(
resp_header(resp, 'x-ratelimit-reset')
)
wait_secs <- max(0, reset_at - as.integer(Sys.time()))
cat(sprintf('Rate limit nearly exhausted. Waiting %ds\n', wait_secs))
# Sys.sleep(wait_secs)
}
# Handle 429 Retry-After header
if (resp_status(resp) == 429) {
retry_after <- resp_header(resp, 'retry-after')
cat(sprintf('Rate limited. Retry after %s seconds\n', retry_after))
}
resp
}
cat('Always respect X-RateLimit-* headers')完整 API 客户端:GitHub 示例
将所学内容结合起来:构建一个完整的 GitHub API 客户端,实现身份验证、获取分页的存储库列表以及处理错误,展示到目前为止学到的所有模式。
library(httr2)
# GitHub API client
github_repos <- function(username, token = NULL, n_pages = 3) {
base <- 'https://api.github.com'
req_base <- request(base) |>
req_headers(
'Accept' = 'application/vnd.github.v3+json',
'User-Agent' = 'R-API-Client/1.0'
)
if (!is.null(token))
req_base <- req_base |> req_auth_bearer_token(token)
all_repos <- list()
for (page in seq_len(n_pages)) {
# resp <- req_base |>
# req_url_path_append('users', username, 'repos') |>
# req_url_query(page = page, per_page = 30, sort = 'updated') |>
# req_perform() |> resp_check_status()
# repos <- resp_body_json(resp, simplifyVector = TRUE)
# if (length(repos) == 0) break
# all_repos[[page]] <- repos
cat(sprintf('Would fetch page %d for %s\n', page, username))
}
do.call(rbind, all_repos)
}
github_repos('hadley')OAuth 2.0 客户端凭据
一些 API 要求使用 OAuth 2.0 客户端凭据流程:用 client_id + client_secret 换取访问令牌。httr2 的 oauth_client() 和 req_oauth_client_credentials() 会自动处理此流程。
library(httr2)
# OAuth 2.0 Client Credentials flow:
# client <- oauth_client(
# id = Sys.getenv('CLIENT_ID'),
# secret = Sys.getenv('CLIENT_SECRET'),
# token_url = 'https://auth.example.com/oauth/token'
# )
# Automatic token management:
# resp <- request('https://api.example.com/data') |>
# req_oauth_client_credentials(client) |>
# req_perform()
# httr2 automatically:
# 1. Gets access token using client credentials
# 2. Adds 'Authorization: Bearer <token>' header
# 3. Refreshes token when expired
cat('req_oauth_client_credentials() handles token lifecycle')
cat('Token is cached in memory automatically')快速检查
测试您对使用 httr2 在 R 中构建 REST API 客户端的理解。
回顾:调用 REST API
要点: 在构造函数中封装基础 URL、身份验证和重试逻辑,即可构建可复用的客户端。使用 req_auth_bearer_token() 进行身份验证,并将令牌存储在环境变量中。通过 Link 标头配合 resp_link_url() 实现分页,或使用基于游标的模式。始终使用 resp_check_status() 和 tryCatch() 处理 HTTP 错误。使用 req_perform_parallel() 执行批量调用。开发期间请缓存结果。
library(httr2)
# REST API client template:
make_api_call <- function(url, token,
method = 'GET',
body = NULL,
query = list()) {
req <- request(url) |>
req_method(method) |>
req_auth_bearer_token(token) |>
req_headers('Accept' = 'application/json') |>
req_retry(max_tries = 3) |>
req_throttle(rate = 10/60)
if (length(query) > 0)
req <- do.call(req_url_query, c(list(req), query))
if (!is.null(body))
req <- req |> req_body_json(body)
req |> req_perform() |> resp_check_status()
}
cat('Template: auth + retry + throttle + error check')常见问题解答
「在 R 中调用 REST API」课时是免费的吗?
是的 — 「在 R 中调用 REST API」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 R Academy 课程的其余内容,请升级到 CoddyKit PRO。 R Academy 课程共包含 4 节课。
「在 R 中调用 REST API」这节课中我会学到什么?
使用 API 密钥进行身份验证,分页获取结果并存储 API 响应 你通过在浏览器中直接运行的动手代码来练习 R Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 R Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 R Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「在 R 中调用 REST API」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 R Academy 课中编写并运行代码吗?
能。每节 R Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用 jsonlite 解析 JSON
- 使用 httr2 发起 HTTP 请求
- 在 R 中调用 REST API
- 处理嵌套 JSON 结构