0Pricing
R Academy · レッスン

httr2 で HTTP リクエストを送信する

GET リクエストと POST リクエストを送信し、ヘッダーを処理してレスポンスを扱います。

「httr2 で HTTP リクエストを送信する」はCoddyKit上の無料R Academyレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはR Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 R Academyコースには全4レッスンが含まれています。

httr2の概要

httr2はHTTPリクエスト向けの最新のRパッケージで、httrの後継です。パイプベースのビルダーパターンを使用し、request(url)で開始して修飾子を追加し、最後にreq_perform()で実行します。

library(httr2)

# Basic GET request pattern:
# request(url)     -> create request object
# |> req_*()       -> modify request
# |> req_perform() -> send request
# |> resp_*()      -> extract from response

# Minimal example (requires internet):
# resp <- request('https://httpbin.org/get') |>
#   req_perform()
# resp_status(resp)     # 200
# resp_body_json(resp)  # parsed JSON body

cat('httr2 follows: build -> perform -> extract')

request()とreq_perform()

request(url)はリクエストオブジェクトを作成します。req_perform()はリクエストを実行し、レスポンスオブジェクトを返します。その後、resp_*関数でレスポンスを調べられます。

library(httr2)

# Build and send a GET request
# resp <- request('https://httpbin.org/get') |>
#   req_perform()

# Inspect response
# resp_status(resp)          # 200
# resp_status_desc(resp)     # 'OK'
# resp_headers(resp)         # list of headers
# resp_header(resp, 'content-type')  # single header
# resp_body_string(resp)     # raw body as string
# resp_body_json(resp)       # parsed JSON
# resp_body_raw(resp)        # raw bytes

cat('Response hierarchy:')
cat('status -> headers -> body')

req_headers():カスタムヘッダー

req_headers()はHTTPヘッダーを追加または上書きします。認証トークン、コンテンツタイプの指定、APIバージョンのヘッダー、カスタムリクエストメタデータなどに使用します。

library(httr2)

# Add custom headers
# resp <- request('https://api.example.com/data') |>
#   req_headers(
#     'Authorization' = 'Bearer my_token',
#     'X-API-Version' = '2',
#     'Accept'        = 'application/json'
#   ) |>
#   req_perform()

# Common headers:
# 'Content-Type' = 'application/json' for POST with JSON body
# 'Accept'       = 'application/json' to request JSON response
# 'User-Agent'   = 'MyApp/1.0' for polite identification
# 'X-API-Key'    = key  for key-based auth

cat('req_headers() sets HTTP request headers')

req_url_query():クエリパラメーター

req_url_query()は、特殊文字をエンコードしながら、クエリパラメーターを安全にURLへ追加します。paste0()で文字列を手動連結するよりも明快です。

library(httr2)

# Add query parameters
# resp <- request('https://api.example.com/search') |>
#   req_url_query(
#     q      = 'R programming',
#     page   = 1,
#     size   = 20,
#     sort   = 'relevance'
#   ) |>
#   req_perform()
# Resulting URL:
# https://api.example.com/search?q=R+programming&page=1&size=20&sort=relevance

# Inspect the URL without performing:
req <- request('https://api.example.com/search') |>
  req_url_query(q = 'hello world', page = 2)
req$url
# 'https://api.example.com/search?q=hello+world&page=2'

req_body_json()でPOSTリクエストを送信する

req_body_json()を使うと、POSTリクエストでJSONデータを送信できます。Content-Type: application/jsonヘッダーを自動的に設定し、RのリストをJSONにシリアライズします。

library(httr2)

# POST request with JSON body
# resp <- request('https://api.example.com/users') |>
#   req_method('POST') |>
#   req_body_json(list(
#     name  = 'Alice',
#     email = 'alice@example.com',
#     role  = 'admin'
#   )) |>
#   req_perform()

# resp_status(resp)     # 201 Created (if success)
# resp_body_json(resp)  # returned user object

# Other body methods:
# req_body_form(...)  -> application/x-www-form-urlencoded
# req_body_raw(bytes) -> raw bytes
# req_body_file(path) -> file upload
cat('req_body_json() handles Content-Type automatically')

resp_body_json():レスポンスを解析する

resp_body_json()は、レスポンスボディをJSONとして解析し、Rのリストに変換します。simplifyVector=TRUE(デフォルト)を使うと、JSON配列をRのベクトルに、オブジェクトを名前付きリストに自動変換できます。

library(httr2)
library(jsonlite)

# Simulated API response handling
# resp <- request('https://api.github.com/users/hadley') |>
#   req_perform()
# user <- resp_body_json(resp)
# user$name    # 'Hadley Wickham'
# user$public_repos  # number of repos
# user$followers     # follower count

# For arrays (simplifyVector=TRUE converts to data frame):
# resp <- request('https://api.github.com/users/hadley/repos') |>
#   req_perform()
# repos <- resp_body_json(resp, simplifyVector = TRUE)
# repos$name  # vector of repo names

cat('resp_body_json() with simplifyVector=TRUE -> data frame')

resp_status()とエラー処理

resp_check_status()は、4xxまたは5xxのレスポンスに対して自動的にエラーを発生させます。これを使わない場合、httr2は不正なステータスコードでエラーにしないため、明示的に確認するかresp_check_status()を呼び出す必要があります。

library(httr2)

# Pattern: check status after perform
# resp <- request('https://api.example.com/data') |>
#   req_perform() |>
#   resp_check_status()  # errors on 4xx/5xx

# Manual status checks:
# status <- resp_status(resp)
# if (status == 200) { ... }
# if (status == 404) { stop('Not found') }
# if (status == 401) { stop('Unauthorized') }
# if (status == 429) { Sys.sleep(60); retry() }

# HTTP status codes:
# 200 OK, 201 Created, 204 No Content
# 400 Bad Request, 401 Unauthorized, 403 Forbidden
# 404 Not Found, 429 Rate Limited
# 500 Server Error, 503 Service Unavailable
cat('Always check response status codes')

req_retry():自動リトライ

req_retry()は失敗したリクエストを自動的に再試行します。max_triesを指定し、必要に応じて、429や503など再試行可能なエラーを識別する関数is_transientを指定します。堅牢なAPIクライアントには不可欠です。

library(httr2)

# Automatic retry with exponential backoff
# resp <- request('https://api.example.com/data') |>
#   req_retry(
#     max_tries = 3,
#     is_transient = function(resp) {
#       resp_status(resp) %in% c(429, 500, 503)
#     },
#     backoff = ~ 2^.x  # exponential: 2, 4, 8 seconds
#   ) |>
#   req_perform()

# Default retry behavior:
# - Retries on 429 Too Many Requests automatically
# - Uses Retry-After header if present
# - max_tries = 1 by default (no retry)

# Simple retry:
# req_retry(max_tries = 3)  # retry up to 3 times total
cat('req_retry() adds resilience to API calls')

req_throttle():レート制限

req_throttle(rate)は、最大リクエストレートを超えないようにします。rate = n/period(例:1分あたり10リクエスト)の形式で指定します。httr2は必要に応じてリクエスト間に自動的に待機します。

library(httr2)

# Throttle to at most 10 requests per minute
# urls <- paste0('https://api.example.com/items/', 1:50)
# resps <- lapply(urls, function(url) {
#   request(url) |>
#     req_throttle(rate = 10 / 60) |>  # 10/min
#     req_perform()
# })

# Alternative: use req_perform_parallel() for parallel
# with throttle built in:
# reqs <- lapply(urls, \(u) request(u))
# resps <- req_perform_parallel(
#   reqs,
#   on_error = 'continue',  # skip failures
#   progress = TRUE
# )

cat('req_throttle(rate = 10/60) = 10 req/min')

認証ヘルパー

httr2には、Basic認証用のreq_auth_basic(user, pass)、Bearerトークン用のreq_auth_bearer_token(token)、OAuthフロー用のreq_oauth_*()など、組み込みの認証ヘルパーが用意されています。

library(httr2)

# Bearer token (most common for modern APIs)
# resp <- request('https://api.example.com/data') |>
#   req_auth_bearer_token('my_api_token_here') |>
#   req_perform()

# Basic authentication
# resp <- request('https://api.example.com/data') |>
#   req_auth_basic('username', 'password') |>
#   req_perform()

# Store tokens securely in environment variables
# token <- Sys.getenv('MY_API_TOKEN')
# resp <- request('https://api.example.com') |>
#   req_auth_bearer_token(token) |>
#   req_perform()

cat('Never hardcode tokens in scripts!')
cat('Use Sys.getenv() or the keyring package')

req_dry_run()でドライランを実行する

req_dry_run()は、実際には送信せずに、送信されるリクエスト(メソッド、URL、ヘッダー、ボディ)を正確に表示します。実際のAPIにアクセスする前に複雑なリクエストをデバッグするために不可欠です。

library(httr2)

# Inspect the request without sending it
req <- request('https://api.example.com/users') |>
  req_method('POST') |>
  req_headers(
    'X-API-Version' = '2',
    'Accept'        = 'application/json'
  ) |>
  req_auth_bearer_token('my_token') |>
  req_body_json(list(name = 'Alice', role = 'admin')) |>
  req_url_query(notify = 'true')

# Show request details without sending
req_dry_run(req)
# POST /users?notify=true HTTP/1.1
# Host: api.example.com
# Authorization: Bearer my_token
# Content-Type: application/json
# ...

クイックチェック

httr2のリクエスト構築パターンについての理解を確認しましょう。

まとめ:httr2でHTTPリクエストを送信する

重要なポイント: httr2はパイプベースのビルダーを使用します:request(url) |> req_*() |> req_perform()。req_headers()でヘッダーを、req_url_query()でクエリパラメーターを、req_body_json()でJSONボディを追加します。req_auth_bearer_token()で認証します。必ずresp_check_status()でステータスを確認します。req_retry()で耐障害性を高め、req_throttle()でリクエストを制限します。req_dry_run()でデバッグします。

library(httr2)

# Complete httr2 request pattern:
# resp <- request('https://api.example.com/endpoint') |>
#   req_headers('Accept' = 'application/json') |>
#   req_url_query(param1 = 'value', page = 1) |>
#   req_auth_bearer_token(Sys.getenv('API_TOKEN')) |>
#   req_retry(max_tries = 3) |>
#   req_throttle(rate = 10/60) |>
#   req_perform() |>
#   resp_check_status()

# Extract data:
# data <- resp_body_json(resp, simplifyVector = TRUE)

cat('build -> authenticate -> perform -> check -> extract')

よくある質問

「httr2 で HTTP リクエストを送信する」レッスンは無料ですか?

はい。「httr2 で HTTP リクエストを送信する」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、R Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 R Academyコースには全4レッスンが含まれています。

「httr2 で HTTP リクエストを送信する」で何を学びますか?

GET リクエストと POST リクエストを送信し、ヘッダーを処理してレスポンスを扱います。 ブラウザで直接実行するハンズオンコードでR Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

R Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのR Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。

「httr2 で HTTP リクエストを送信する」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このR Academyレッスンでコードを書いて実行できますか?

はい。すべてのR Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. jsonlite で JSON をパースする
  2. httr2 で HTTP リクエストを送信する
  3. R で REST API を利用する
  4. ネストされた JSON 構造を扱う
← R Academyに戻る