rguides

How to Make HTTP Requests in R with httr2

The httr2 package makes it simple to make HTTP requests in R with a modern, pipe-friendly interface that replaces the older httr package. It handles everything from basic GET calls to authenticated API workflows with retry logic and streaming responses.

library(httr2)
req <- request("https://httpbin.org/get")
resp <- req_perform(req)
resp_body_string(resp)

For POST requests with JSON bodies, add req_method() and req_body_json() before req_perform(). Query parameters use req_url_query(), and headers use req_headers(). Parse responses with resp_body_json() for JSON APIs or resp_body_string() for plain text. Always store API keys in environment variables, accessed with Sys.getenv(), rather than hardcoding credentials in scripts.

req <- request("https://httpbin.org/post") |>
  req_method("POST") |>
  req_body_json(list(user = "alice", active = TRUE))
resp <- req_perform(req)
resp_body_json(resp)

For authenticated APIs, req_auth_bearer_token() covers token-based authentication. Use req_throttle() for built-in rate limiting during sequential requests. When a request fails, req_retry() automatically retries with exponential backoff, and req_error() lets you inspect the response body on error rather than stopping immediately. Multipart form uploads are handled by req_body_multipart().

See also