Learn R Programming

httr2

httr2 (pronounced hitter2) is a ground-up rewrite of httr that provides a pipeable API with an explicit request object that solves more problems felt by packages that wrap APIs (e.g. built-in rate-limiting, retries, OAuth, secure secrets, and more).

Installation

You can install httr2 from CRAN with:

install.packages("httr2")

Usage

To use httr2, start by creating a request:

library(httr2)

req <- request("https://r-project.org")
req
#> <httr2_request>
#> GET https://r-project.org
#> Body: empty

You can tailor this request with the req_ family of functions:

# Add custom headers
req |> req_headers("Accept" = "application/json")
#> <httr2_request>
#> GET https://r-project.org
#> Headers:
#> • Accept: 'application/json'
#> Body: empty

# Add a body, turning it into a POST
req |> req_body_json(list(x = 1, y = 2))
#> <httr2_request>
#> POST https://r-project.org
#> Body: json encoded data

# Modify the path in the url
req |> req_url_path(path = "path/to/my/file")
#> <httr2_request>
#> GET https://r-project.org/path/to/my/file
#> Body: empty

# Automatically retry if the request fails
req |> req_retry(max_tries = 5)
#> <httr2_request>
#> GET https://r-project.org
#> Body: empty
#> Policies:
#> • retry_max_tries: 5
#> • retry_on_failure: FALSE

# Change the HTTP method
req |> req_method("PATCH")
#> <httr2_request>
#> PATCH https://r-project.org
#> Body: empty

And see exactly what httr2 will send to the server with req_dry_run():

req |> req_dry_run()
#> GET / HTTP/1.1
#> Host: r-project.org
#> User-Agent: httr2/1.0.3.9000 r-curl/5.2.2 libcurl/8.6.0
#> Accept: */*
#> Accept-Encoding: deflate, gzip

Use req_perform() to perform the request, retrieving a response:

resp <- req_perform(req)
resp
#> <httr2_response>
#> GET https://www.r-project.org/
#> Status: 200 OK
#> Content-Type: text/html
#> Body: In memory (6951 bytes)

The resp_ functions help you extract various useful components of the response:

resp |> resp_content_type()
#> [1] "text/html"
resp |> resp_status_desc()
#> [1] "OK"
resp |> resp_body_html()
#> {html_document}
#> <html lang="en">
#> [1] <head>\n<meta http-equiv="Content-Type" content="text/html; charset=UTF-8 ...
#> [2] <body>\n    <div class="container page">\n      <div class="row">\n       ...

Major differences to httr

  • You can now create and modify a request without performing it. This means that there’s now a single function to perform the request and fetch the result: req_perform(). req_perform() replaces httr::GET(), httr::POST(), httr::DELETE(), and more.

  • HTTP errors are automatically converted into R errors. Use req_error() to override the defaults (which turn all 4xx and 5xx responses into errors) or to add additional details to the error message.

  • You can automatically retry if the request fails or encounters a transient HTTP error (e.g. a 429 rate limit request). req_retry() defines the maximum number of retries, which errors are transient, and how long to wait between tries.

  • OAuth support has been totally overhauled to directly support many more flows and to make it much easier to both customise the built-in flows and to create your own.

  • You can manage secrets (often needed for testing) with secret_encrypt() and friends. You can obfuscate mildly confidential data with obfuscate(), preventing it from being scraped from published code.

  • You can automatically cache all cacheable results with req_cache(). Relatively few API responses are cacheable, but when they are it typically makes a big difference.

Acknowledgements

httr2 wouldn’t be possible without curl, openssl, jsonlite, and jose, which are all maintained by Jeroen Ooms. A big thanks also go to Jenny Bryan and Craig Citro who have given me much useful feedback on both the design of the internals and the user facing API.

Copy Link

Version

Install

install.packages('httr2')

Monthly Downloads

365,637

Version

1.0.5

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Hadley Wickham

Last Published

September 26th, 2024

Functions in httr2 (1.0.5)

progress_bars

Progress bars in httr2
req_auth_basic

Authenticate request with HTTP basic authentication
example_url

Code for examples
req_cache

Automatically cache requests
req_cookie_preserve

Set and preserve cookies
obfuscate

Obfuscate mildly secret information
%>%

Pipe operator
req_auth_bearer_token

Authenticate request with bearer token
req_body

Send data in request body
req_headers

Modify request headers
req_method

Set HTTP method in request
req_perform

Perform a request to get a response
req_options

Set arbitrary curl options in request
req_oauth_refresh

OAuth with a refresh token
req_timeout

Set time limit for a request
oauth_flow_auth_code_url

OAuth authorization code components
oauth_redirect_uri

Default redirect url for OAuth
req_url

Modify request URL
req_dry_run

Perform a dry run
oauth_cache_path

httr2 OAuth cache location
req_perform_connection

Perform a request and return a streaming connection
req_error

Control handling of HTTP errors
request

Create a new HTTP request
oauth_token

Create an OAuth token
oauth_token_cached

Retrieve an OAuth token using the cache
req_template

Set request method/path from a template
resp_body_raw

Extract body from response
req_oauth

OAuth authentication
req_oauth_auth_code

OAuth with authorization code
resp_retry_after

Extract wait time from a response
req_perform_promise

Perform request asynchronously using the promises package
resp_status

Extract HTTP status from response
req_perform_iterative

Perform requests iteratively, generating new requests from previous responses
req_perform_sequential

Perform multiple requests in sequence
with_mocked_responses

Temporarily mock requests
req_perform_parallel

Perform a list of requests in parallel
jwt_claim

Create and encode a JWT
last_response

Retrieve most recent request/response
req_throttle

Rate limit a request by automatically adding a delay
req_oauth_bearer_jwt

OAuth with a bearer JWT (JSON web token)
resps_successes

Tools for working with lists of responses
response

Create a new HTTP response
with_verbosity

Temporarily set verbosity for all requests
resp_date

Extract request date from response
req_oauth_client_credentials

OAuth with client credentials
req_oauth_device

OAuth with device flow
resp_headers

Extract headers from a response
req_perform_stream

Perform a request and handle data as it streams back
req_oauth_password

OAuth with username and password
resp_stream_raw

Read a streaming body a chunk at a time
req_progress

Add a progress bar to long downloads or uploads
req_proxy

Use a proxy for a request
req_retry

Control when a request will retry, and how long it will wait between tries
req_user_agent

Set user-agent for a request
resp_url

Get URL/components from the response
req_verbose

Show extra output when request is performed
resp_check_content_type

Check the content type of a response
resp_content_type

Extract response content type and encoding
url_parse

Parse and build URLs
throttle_status

Display internal throttle status
resp_raw

Show the raw response
resp_link_url

Parse link URL from a response
secrets

Secret management
signal_total_pages

Signal total number pages
oauth_client

Create an OAuth client
curl_translate

Translate curl syntax to httr2
oauth_client_req_auth

OAuth client authentication
httr2-package

httr2: Perform HTTP Requests and Process the Responses
multi_req_perform

Perform a list of requests in parallel
iterate_with_offset

Iteration helpers