ZetCode

R HTTP requests

last modified November 20, 2026

Many data sources are reached over HTTP: a JSON API, a CSV export, or a file behind a login. The httr2 package models a request as an object that is built step by step and then performed, and it models the reply as a response object with a status, headers, and a body. Building and sending are separate steps, so a request can be printed and inspected before anything leaves the machine. This article covers URLs and query parameters, headers, JSON bodies, reading responses, HTTP errors, retries, timeouts, and a complete API client. The examples use httr2 1.3.0, webfakes 1.5.0, and R 4.5.2.

The first examples talk to two free public services: timeapi.io returns the current time, and httpbin.org echoes back what it receives. The later examples start their own small web server written in R with the webfakes package, so they run offline and always give the same output. Install the packages once with install.packages(c("httr2", "webfakes", "callr")); webfakes uses callr to run the server in a background R process. The installing packages section of the introduction explains the details.

A first request

request creates a request from a URL, and req_perform sends it and returns a response. The time API answers a GET request with a JSON object describing the current time in the requested time zone. resp_status reads the numeric status code, and resp_body_json parses the body into an R list.

first-request.R
library(httr2)
url <- "https://timeapi.io/api/time/current/zone?timeZone=Europe/Bratislava"
resp <- request(url) |> req_perform()
cat("status:", resp_status(resp), "\n")
now <- resp_body_json(resp)
cat("time zone:", now$timeZone, "\n")
cat("date:", now$date, "\n")
cat("time:", now$time, "\n")
cat("weekday:", now$dayOfWeek, "\n")

The status 200 means the request succeeded. The parsed body is a named list, so its fields are read with $, like any other list element. The date and time in the output are those of the moment the script ran, so they will differ on each run.

$ Rscript first-request.R
status: 200 
time zone: Europe/Bratislava 
date: 11/20/2026 
time: 09:51 
weekday: Friday 

Building a request

Writing the whole URL as one string is fine for a single call, but it is error prone once parts of it change. The req_* functions each add one part and return a new request, which makes them easy to chain. req_url_path_append adds path segments, req_url_query appends query parameters, req_headers adds request headers, and req_user_agent identifies the client. Printing a request shows exactly what would be sent, without contacting the server.

build.R
library(httr2)
req <- request("https://timeapi.io/api") |>
  req_url_path_append("time", "current", "zone") |>
  req_url_query(timeZone = "Asia/Tokyo") |>
  req_headers(Accept = "application/json") |>
  req_user_agent("zetcode-tutorial/1.0")
print(req)
now <- req_perform(req) |> resp_body_json()
cat("Tokyo:", now$date, now$time, "\n")

The printout shows the method, the assembled URL, the Accept header, the empty body, and the user agent. The slash inside Asia/Tokyo is percent-encoded as %2F, so it cannot be mistaken for a path separator. Because the request is an ordinary R object, it can be stored, passed to a function, and extended before req_perform sends it.

$ Rscript build.R
<httr2_request>
GET https://timeapi.io/api/time/current/zone?timeZone=Asia%2FTokyo
Headers:
* Accept: "application/json"
Body: empty
Options:
* useragent: "zetcode-tutorial/1.0"
Tokyo: 11/20/2026 17:51 

Query parameters and headers

To see what a server actually receives, we can send the request to an echo service. The /get endpoint of httpbin.org replies with a JSON document that contains the URL, the query parameters, and the headers of the request. Here the values contain a space and an ampersand, two characters that have a special meaning in a URL.

echo.R
library(httr2)
resp <- request("https://httpbin.org/get") |>
  req_url_query(q = "R graphics", tags = "a&b", limit = 2) |>
  req_user_agent("zetcode-tutorial/1.0") |>
  req_perform()
echo <- resp_body_json(resp)
cat("url:", echo$url, "\n")
str(echo$args)
cat("user agent:", echo$headers$`User-Agent`, "\n")

The space is sent as %20 and the ampersand as %26, so the server decodes the original values correctly. Numbers become strings, because a query string carries only text. The User-Agent header that the server received is the one set with req_user_agent. The script prints only selected fields, as the full echo also contains the caller's IP address.

$ Rscript echo.R
url: https://httpbin.org/get?q=R%20graphics&tags=a%26b&limit=2 
List of 3
 $ limit: chr "2"
 $ q    : chr "R graphics"
 $ tags : chr "a&b"
user agent: zetcode-tutorial/1.0 

Sending a JSON body

A create or update call sends data instead of only reading it. req_body_json serialises an R list with jsonlite, sets the Content-Type header to application/json, and changes the method to POST. The /post endpoint of httpbin echoes the body back, so we can check what was sent.

post.R
library(httr2)
req <- request("https://httpbin.org/post") |>
  req_body_json(list(title = "R Graphics", price = 38))
print(req)
resp <- req_perform(req)
echo <- resp_body_json(resp)
cat("status:", resp_status(resp), "\n")
cat("content type sent:", echo$headers$`Content-Type`, "\n")
cat("body sent:", echo$data, "\n")
str(echo$json)

The request printout reports the method as POST and the body as JSON data. The echo confirms the content type and shows the body exactly as it travelled: a compact JSON object. httpbin also parses that body, and str displays the result. For a form submission, req_body_form sends application/x-www-form-urlencoded data instead, and req_body_raw sends a string unchanged.

$ Rscript post.R
<httr2_request>
POST https://httpbin.org/post
Body: JSON data
status: 200 
content type sent: application/json 
body sent: {"title":"R Graphics","price":38} 
List of 2
 $ price: int 38
 $ title: chr "R Graphics"

A local test server

Public services are handy, but their answers change and they may be down. For repeatable examples and for tests, webfakes runs a web server written in R. new_app creates an application, app$get registers a handler for a path, and res$send_json writes a JSON reply. new_app_process starts the application in a background R process on a free port and returns once the server is ready.

local-server.R
library(httr2)
library(webfakes)
app <- new_app()
app$get("/hello", function(req, res) {
  res$send_json(list(message = "Hello there!"), auto_unbox = TRUE)
})
srv <- new_app_process(app)
cat("server:", srv$url(), "\n")
resp <- request(srv$url("/hello")) |> req_perform()
cat("status:", resp_status(resp), "\n")
cat("type:", resp_content_type(resp), "\n")
print(resp_body_json(resp))
srv$stop()

srv$url builds the full address for a path, so the script does not need to know the port, which is chosen anew on every run. The httr2 code is the same as for a remote API; only the base URL differs. srv$stop shuts the background process down at the end.

$ Rscript local-server.R
server: http://127.0.0.1:39619/ 
status: 200 
type: application/json 
$message
[1] "Hello there!"

A books API

The remaining examples use a small books API. To avoid repeating it, the server lives in its own file, which the scripts load with source. The /books path returns all books, and /books/:id returns one book; the :id part matches any value and is available in req$params. An unknown identifier gets a 404 status with a JSON error message.

books-app.R
library(webfakes)

books_app <- function() {
  books <- data.frame(
    id = 1:4,
    title = c("R in Action", "The R Book", "R Graphics", "Advanced R"),
    price = c(45, 52, 38, 49)
  )
  app <- new_app()
  app$get("/books", function(req, res) {
    res$send_json(list(books = books), auto_unbox = TRUE)
  })
  app$get("/books/:id", function(req, res) {
    book <- books[books$id == as.integer(req$params$id), ]
    if (nrow(book) == 1) {
      res$send_json(as.list(book), auto_unbox = TRUE)
    } else {
      res$set_status(404)
      res$send_json(list(error = "no such book"), auto_unbox = TRUE)
    }
  })
  app
}

The data frame is created inside books_app rather than at the top of the file. The server runs in a separate R process, and the handlers take along the environment in which they were defined, but not the global environment of the calling script. as.list turns the single row into an object instead of an array with one element.

Reading the response

A response body can be read as a string, as parsed JSON, or as a data frame. resp_body_string returns the text exactly as it arrived, which is useful for logging and for formats that httr2 does not parse. resp_body_json has a simplifyVector argument; when it is TRUE, an array of objects with the same fields becomes a data frame, as in the JSON article. resp_header reads a single header by name.

fetch.R
library(httr2)
source("books-app.R")
srv <- new_app_process(books_app())
resp <- request(srv$url("/books")) |> req_perform()
cat("status:", resp_status(resp), "\n")
cat("length:", resp_header(resp, "content-length"), "\n")
text <- resp_body_string(resp)
cat("characters:", nchar(text), "\n")
data <- resp_body_json(resp)
cat("books:", length(data$books), "\n")
str(data$books[[1]])
books <- resp_body_json(resp, simplifyVector = TRUE)$books
print(books)
srv$stop()

The content-length header and nchar both report 176, because the body contains only ASCII characters and every byte is one character. Without simplification, the books are a list of four lists; with it, they form a data frame with the columns id, title, and price. Reading the same response twice is cheap: the body is already in memory, and only the parsing runs again.

$ Rscript fetch.R
status: 200 
length: 176 
characters: 176 
books: 4 
List of 3
 $ id   : int 1
 $ title: chr "R in Action"
 $ price: int 45
  id       title price
1  1 R in Action    45
2  2  The R Book    52
3  3  R Graphics    38
4  4  Advanced R    49

Handling HTTP errors

A response with a status of 400 or higher is an error, and req_perform raises an R error for it by default. That is the right behaviour in a script that cannot continue without the data. When the caller wants to inspect the failed response, req_error turns the automatic error off with a function that always returns FALSE.

errors.R
library(httr2)
source("books-app.R")
srv <- new_app_process(books_app())
req <- request(srv$url("/books/7")) |>
  req_error(is_error = function(resp) FALSE)
resp <- req_perform(req)
cat("status:", resp_status(resp), "\n")
cat("description:", resp_status_desc(resp), "\n")
cat("error:", resp_is_error(resp), "\n")
cat("message:", resp_body_json(resp)$error, "\n")
srv$stop()

Book 7 does not exist, so the server answers 404 Not Found, and resp_is_error confirms it. Because our server sends a JSON error message, the body can still be parsed; many servers send an HTML page instead, which is why the status should be checked before the body is parsed. resp_check_status turns such a response into an R error with the message HTTP 404 Not Found.

$ Rscript errors.R
status: 404 
description: Not Found 
error: TRUE 
message: no such book 

Retries

Networks and servers fail intermittently, and a client should retry the failures that are likely to pass on a later attempt. req_retry sets the maximum number of tries and a backoff function that returns the number of seconds to wait before the next try. This server answers the first two requests with 503 Service Unavailable and the third with a success; it counts the requests in app$locals, which persists between requests.

retry.R
library(httr2)
library(webfakes)
app <- new_app()
app$locals$hits <- 0
app$get("/busy", function(req, res) {
  app$locals$hits <- app$locals$hits + 1
  if (app$locals$hits < 3) {
    res$send_status(503)
  } else {
    res$send_json(list(attempt = app$locals$hits), auto_unbox = TRUE)
  }
})
srv <- new_app_process(app)
start <- Sys.time()
resp <- request(srv$url("/busy")) |>
  req_retry(max_tries = 3, backoff = function(i) 0.5) |>
  req_perform()
elapsed <- as.numeric(Sys.time() - start, units = "secs")
cat("status:", resp_status(resp), "\n")
cat("succeeded on attempt:", resp_body_json(resp)$attempt, "\n")
cat("seconds:", round(elapsed, 1), "\n")
srv$stop()

httr2 retried twice and the third attempt succeeded, so the script sees only the final 200 response. The run took a little over a second: two half-second waits plus the requests themselves. By default only transient failures, such as 429 Too Many Requests and 503, are retried, not a 404, because a missing resource will still be missing on the next try. A related policy, req_throttle, limits how many requests are sent to one host per minute.

$ Rscript retry.R
status: 200 
succeeded on attempt: 3 
seconds: 1.3 

Timeouts

A server that never answers would block the script forever. req_timeout limits a request to a number of seconds. The /slow handler sleeps for three seconds, while the client is willing to wait for only one.

timeout.R
library(httr2)
library(webfakes)
app <- new_app()
app$get("/slow", function(req, res) {
  Sys.sleep(3)
  res$send("finally")
})
srv <- new_app_process(app)
cat("waiting at most one second\n")
resp <- request(srv$url("/slow")) |>
  req_timeout(1) |>
  req_perform()
cat("not reached\n")

After one second curl gives up, and req_perform raises an error that stops the script, so the last line is never reached. The background server is stopped automatically when the script ends. The error handling article shows how to catch such an error with tryCatch and continue.

$ Rscript timeout.R
waiting at most one second
Error in `req_perform()`:
! Failed to perform HTTP request.
Caused by error in `curl::curl_fetch_memory()`:
! Timeout was reached [127.0.0.1]:
Operation timed out after 1000 milliseconds with 0 bytes received
Backtrace:
    ▆
 1. └─httr2::req_perform(req_timeout(request(srv$url("/slow")), 1))
 2.   └─httr2:::handle_resp(req, resp, error_call = error_call)
 3.     └─rlang::cnd_signal(resp)
Execution halted

A complete example

The final script builds one base request with the settings every call shares and derives the individual calls from it. It checks the status before using the body, converts the JSON into a data frame, selects the books above forty, and then fetches a single book by its identifier.

complete.R
library(httr2)
source("books-app.R")
srv <- new_app_process(books_app())
client <- request(srv$url()) |>
  req_user_agent("zetcode-tutorial/1.0") |>
  req_retry(max_tries = 3) |>
  req_timeout(5)
resp <- client |> req_url_path_append("books") |> req_perform()
resp_check_status(resp)
books <- resp_body_json(resp, simplifyVector = TRUE)$books
expensive <- books[books$price > 40, ]
print(expensive)
cat("count:", nrow(expensive), "\n")
cat("average:", mean(books$price), "\n")
book <- client |> req_url_path_append("books", 3) |> req_perform() |>
  resp_body_json()
cat("book 3:", book$title, "\n")
srv$stop()

The client object holds the base URL, the user agent, the retry policy, and the timeout; each call adds only its path. Three books cost more than forty, and the average price of all four is 46. The filtering works on columns because of simplifyVector = TRUE. Switching from the local server to a production API means changing only the base URL.

$ Rscript complete.R
  id       title price
1  1 R in Action    45
2  2  The R Book    52
4  4  Advanced R    49
count: 3 
average: 46 
book 3: R Graphics 

Source

httr2: perform HTTP requests and process the responses

webfakes: fake web apps for HTTP testing

httpbin.org: HTTP request and response service

RFC 9110: HTTP semantics

In this article we sent requests to a public time API and to an echo service, built URLs from paths and encoded query parameters, and posted a JSON body. We then started a local web server with webfakes, read the status, headers, and body of its responses, handled a 404 without stopping the script, retried a failing request, and limited a slow one with a timeout. The JSON article explains the simplification rules behind simplifyVector, and the web scraping article extracts data from HTML pages that do not offer an API. The series continues with R Markdown.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.