### Package Installation Failure Error Source: https://github.com/r-lib/httr2/blob/main/revdep/failures.md Indicates a general failure during package installation. Check the installation log for specific details. ```text Installation failed. See ‘/tmp/workdir/arcgisplaces/new/arcgisplaces.Rcheck/00install.out’ for details. ``` -------------------------------- ### R Package Installation Success Source: https://github.com/r-lib/httr2/blob/main/revdep/failures.md This output indicates a successful installation of an R package, including steps like unpacking, checking MD5 sums, staged installation, byte-compilation, and index building. ```R * installing *source* package ‘dataRetrieval’ ... ** package ‘dataRetrieval’ successfully unpacked and MD5 sums checked ** using staged installation ** R ** inst ** byte-compile and prepare package for lazy loading ** help *** installing help indices *** copying figures ** building package indices ** installing vignettes ** testing if installed package can be loaded from temporary location ** testing if installed package can be loaded from final location ** testing if installed package keeps a record of temporary installation path * DONE (dataRetrieval) ``` ```R * installing *source* package ‘eudata’ ... ** package ‘eudata’ successfully unpacked and MD5 sums checked ** using staged installation ** R ** inst ** byte-compile and prepare package for lazy loading ** help *** installing help indices ** building package indices ** installing vignettes ** testing if installed package can be loaded from temporary location ** testing if installed package can be loaded from final location ** testing if installed package keeps a record of temporary installation path * DONE (eudata) ``` -------------------------------- ### Install httr2 Source: https://github.com/r-lib/httr2/blob/main/README.md Install the httr2 package from CRAN. ```r install.packages("httr2") ``` -------------------------------- ### R Installation Success in dataRetrieval (CRAN) Source: https://github.com/r-lib/httr2/blob/main/revdep/problems.md Shows a successful installation process for the 'dataRetrieval' package from CRAN, indicating that the package can be installed and loaded correctly. ```R * installing *source* package ‘dataRetrieval’ ... ** package ‘dataRetrieval’ successfully unpacked and MD5 sums checked ** using staged installation ** R ** inst ** byte-compile and prepare package for lazy loading ** help *** installing help indices *** copying figures ** building package indices ** installing vignettes ** testing if installed package can be loaded from temporary location ** testing if installed package can be loaded from final location ** testing if installed package keeps a record of temporary installation path * DONE (dataRetrieval) ``` -------------------------------- ### Create a basic request Source: https://github.com/r-lib/httr2/blob/main/README.md Start by creating a request object with the base URL. The request object can then be modified using the `req_` family of functions. ```r library(httr2) req <- request("https://r-project.org") req #> #> GET https://r-project.org #> Body: empty ``` -------------------------------- ### openeo package installation warning Source: https://github.com/r-lib/httr2/blob/main/revdep/problems.md A warning during the installation of the 'openeo' package, noting an unused argument in an 'oauth_flow_auth_code' function call, possibly related to httr2 integration. ```R Found the following significant warnings: Note: possible error in 'oauth_flow_auth_code(client = private$oauth_client, ': unused argument (port = 1410) See ‘/tmp/workdir/openeo/new/openeo.Rcheck/00install.out’ for details. Information on the location(s) of code generating the ‘Note’s can be obtained by re-running with environment variable R_KEEP_PKG_SOURCE set to ‘yes’. ``` -------------------------------- ### OAuth Auth Code Flow with Localhost Redirect Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/oauth-flow-auth-code.md Demonstrates initiating the OAuth authentication code flow. This example will error if run in a hosted environment due to the use of 'localhost' as a redirect URI. ```r oauth_flow_auth_code(client, "http://localhost") ``` -------------------------------- ### Input Validation for iterate_with_offset start Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-perform-iterative-helpers.md Ensures `start` is a whole number. Use when `start` is not a whole number. ```R iterate_with_offset("x", "x") ``` -------------------------------- ### R Installation Error in dataRetrieval (Devel) Source: https://github.com/r-lib/httr2/blob/main/revdep/problems.md Details an installation error for the 'dataRetrieval' package during development, where loading the package fails due to an HTTP 404 error during a request performed by httr2. ```R * installing *source* package ‘dataRetrieval’ ... ** package ‘dataRetrieval’ successfully unpacked and MD5 sums checked ** using staged installation ** R ** inst ** byte-compile and prepare package for lazy loading ** help *** installing help indices *** copying figures ** building package indices ... ** installing vignettes ** testing if installed package can be loaded from temporary location Error: package or namespace load failed for ‘dataRetrieval’: .onLoad failed in loadNamespace() for 'dataRetrieval', details: call: httr2::req_perform(check_endpoints_req) error: HTTP 404 Not Found. Error: loading failed Execution halted ERROR: loading failed * removing ‘/tmp/workdir/dataRetrieval/new/dataRetrieval.Rcheck/dataRetrieval’ ``` -------------------------------- ### R Package Installation Error Source: https://github.com/r-lib/httr2/blob/main/revdep/failures.md This output indicates that an R package installation failed, with a specific error message pointing to details in an '.Rcheck/00install.out' file. ```R Installation failed. See ‘/tmp/workdir/eudata/new/eudata.Rcheck/00install.out’ for details. ``` -------------------------------- ### AWS v4 Signature Calculation Example Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-auth-aws.md This snippet demonstrates the output of the `aws_v4_signature` function, showing the canonical request, string to sign, signing key, and the final authorization header. ```R signature ``` -------------------------------- ### Perform a request and get a response Source: https://github.com/r-lib/httr2/blob/main/README.md Perform the request using `req_perform()` and retrieve the response object. This replaces functions like `httr::GET()`. ```r resp <- req_perform(req) resp #> #> GET https://www.r-project.org/ #> Status: 200 OK #> Content-Type: text/html #> Body: In memory (6238 bytes) ``` -------------------------------- ### Debugging osmapiR Example Failures Source: https://github.com/r-lib/httr2/blob/main/revdep/problems.md This snippet shows the error traceback from a failed example in the osmapiR package. It indicates a failure within httr2's resp_failure_cnd function, suggesting an issue with handling HTTP responses or errors. ```R Running examples in ‘osmapiR-Ex.R’ failed The error most likely occurred in: > ### Name: osm_get_changesets > ### Title: Get changesets > ### Aliases: osm_get_changesets > > ### ** Examples > > chaset <- osm_get_changesets(changeset_id = 137595351, include_discussion = TRUE) ... 5. └─httr2:::resp_failure_cnd(req, resp, error_call = error_call) 6. ├─rlang::catch_cnd(...) 7. │ ├─rlang::eval_bare(...) 8. │ ├─base::tryCatch(...) 9. │ │ └─base (local) tryCatchList(expr, classes, parentenv, handlers) 10. │ │ └─base (local) tryCatchOne(expr, names, parentenv, handlers[[1L]]) 11. │ │ └─base (local) doTryCatch(return(expr), name, parentenv, handler) 12. │ └─base::force(expr) 13. └─rlang::abort(...) Execution halted ``` -------------------------------- ### Validate callback arguments with as_callback Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-policy.md Use as_callback to check if a function has the expected number of arguments. This example shows an error when the callback has too few arguments. ```R as_callback(function(x) 2, 2, "foo") ``` -------------------------------- ### OAuth 2.0 Authorization Code Flow with httr2 Source: https://context7.com/r-lib/httr2/llms.txt Implement the OAuth 2.0 authorization code flow for interactive applications. This example uses GitHub as the OAuth provider and caches tokens on disk for persistence. ```r # --- Authorization Code Flow (interactive, opens browser) --- github_client <- oauth_client( id = Sys.getenv("GITHUB_CLIENT_ID"), secret = Sys.getenv("GITHUB_CLIENT_SECRET"), token_url = "https://github.com/login/oauth/access_token", name = "my-github-app" ) req_github <- function(req) { req_oauth_auth_code( req, client = github_client, auth_url = "https://github.com/login/oauth/authorize", scope = "repo", cache_disk = TRUE # persist token across sessions ) } repos <- request("https://api.github.com/user/repos") | req_github() | req_perform() | resp_body_json() ``` -------------------------------- ### Translate basic curl command Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/curl.md Translates a simple curl command to an httr2 request. Ensures the command starts with 'curl'. ```R curl_translate("echo foo") ``` -------------------------------- ### HTTP-Level Disk Caching Source: https://context7.com/r-lib/httr2/llms.txt Configure disk caching for GET responses using req_cache(). This respects standard HTTP cache-control headers and uses conditional requests for efficiency. Specify the cache directory and optional parameters like max_n and max_size. ```r cache_dir <- file.path(tempdir(), "httr2-cache") req <- request("https://raw.githubusercontent.com/allisonhorst/palmerpenguins/master/inst/extdata/penguins.csv") |> req_cache(cache_dir, debug = TRUE, max_n = 100, max_size = 50 * 1024^2) ``` -------------------------------- ### Simple Request Retry Source: https://context7.com/r-lib/httr2/llms.txt Configure automatic retries for failed requests using req_retry(). This example retries up to 3 times on transient network errors or server issues. ```r request("https://api.example.com/data") |> req_retry(max_tries = 3) |> req_perform() ``` -------------------------------- ### Configure automatic retries for a request Source: https://github.com/r-lib/httr2/blob/main/README.md Configure automatic retries for a request using `req_retry()`. This example sets the maximum number of retries to 5. ```r req |> req_retry(max_tries = 5) #> #> GET https://r-project.org #> Body: empty #> Policies: #> * retry_max_tries : 5 #> * retry_on_failure : FALSE #> * retry_failure_threshold: Inf #> * retry_failure_timeout : 30 #> * retry_realm : "r-project.org" ``` -------------------------------- ### HTTP-Level Disk Caching Source: https://context7.com/r-lib/httr2/llms.txt Caches GET responses to disk using standard HTTP cache-control semantics. ```APIDOC ## `req_cache()` — HTTP-level disk caching Caches GET responses to disk using standard HTTP cache-control semantics (`Expires`, `ETag`, `Last-Modified`, `Cache-Control: max-age`). On subsequent requests, serves fresh responses from cache or issues conditional requests (`If-None-Match` / `If-Modified-Since`). ```r cache_dir <- file.path(tempdir(), "httr2-cache") req <- request("https://raw.githubusercontent.com/allisonhorst/palmerpenguins/master/inst/extdata/penguins.csv") |> req_cache(cache_dir, debug = TRUE, max_n = 100, max_size = 50 * 1024^2) ``` ``` -------------------------------- ### Get the status description of a response Source: https://github.com/r-lib/httr2/blob/main/README.md Extract the status description (e.g., 'OK', 'Not Found') from a response object using `resp_status_desc()`. ```r resp |> resp_status_desc() #> [1] "OK" ``` -------------------------------- ### Generate and Manage Encryption Keys with httr2 Source: https://context7.com/r-lib/httr2/llms.txt Use `secret_make_key()` to generate a new AES-CTR encryption key. This key should be stored securely, for example, in an environment variable, for use with encryption and decryption functions. ```r # 1. Generate a key once and add to .Renviron: MY_PKG_KEY= key <- secret_make_key() cat("MY_PKG_KEY=", key, "\n", sep = "") ``` -------------------------------- ### Rust Compilation Error: Rustc Version Mismatch Source: https://github.com/r-lib/httr2/blob/main/revdep/failures.md Occurs when a Rust package dependency requires a newer version of rustc than is currently installed. Suggests updating rustc or pinning the dependency version. ```text error: package `zerofrom v0.1.6` cannot be built because it requires rustc 1.81 or newer, while the currently active rustc version is 1.75.0 Either upgrade to rustc 1.81 or newer, or use cargo update zerofrom@0.1.6 --precise ver where `ver` is the latest version of `zerofrom` supporting rustc 1.75.0 make: *** [Makevars:28: rust/target/release/libarcgisplaces.a] Error 101 ERROR: compilation failed for package ‘arcgisplaces’ ``` -------------------------------- ### Prepare Request with req_perform_promise Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-promise.md Demonstrates how `req_perform_promise` correctly prepares an HTTP request when provided with valid arguments, showing the request and response details. ```R . <- extract_promise(req_perform_promise(req, verbosity = 1)) ``` -------------------------------- ### Create Basic Response Object Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/resp.md Use `response()` to create a basic mock HTTP response object. This is useful for testing functions that expect a response object. ```r response(200) ``` -------------------------------- ### Print OAuth Client Details (Basic) Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/oauth-client.md Display the basic details of an OAuth client, including its name, ID, and token URL. The secret is not shown by default. ```R oauth_client("x", url) ``` -------------------------------- ### Control Space Handling in Query Parameters Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-url.md Demonstrates how to control space encoding in query parameters using the `.space` argument. An error is raised if an invalid value is provided for `.space`. ```r req_url_query(req, a = " ", .space = "bar") ``` -------------------------------- ### Get the content type of a response Source: https://github.com/r-lib/httr2/blob/main/README.md Extract the Content-Type header from a response object using `resp_content_type()`. ```r resp |> resp_content_type() #> [1] "text/html" ``` -------------------------------- ### Create OAuth Client with Header Authentication Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/oauth-client.md Create an OAuth client specifying 'header' authentication. This requires a client secret to be provided. ```R oauth_client("abc", "http://x.com", auth = "header") ``` -------------------------------- ### Get the HTML body of a response Source: https://github.com/r-lib/httr2/blob/main/README.md Parse and retrieve the HTML body of a response object using `resp_body_html()`. ```r resp |> resp_body_html() #> {html_document} #> #> [1] #> #>
#> ... ``` -------------------------------- ### Create Response with File Body Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/resp.md Assign a file path to the `body` argument using `new_path()`. The response will indicate the file content and size. ```r response(200, body = new_path("path-content")) ``` -------------------------------- ### Handle Multi-Value Query Parameters Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-url.md Illustrates the default behavior when attempting to add multiple values to a single query parameter without specifying a strategy. An error occurs, and the user is prompted to use `.multi`. ```r req_url_query_multi("error") ``` -------------------------------- ### Create OAuth Client with JWT Signature Authentication Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/oauth-client.md Create an OAuth client for JWT signature authentication. This requires a key and a claim specification in `auth_params`. ```R oauth_client("abc", "http://x.com", auth = "jwt_sig") ``` ```R oauth_client("abc", "http://x.com", key = "abc", auth = "jwt_sig") ``` -------------------------------- ### Get JSON request Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/last.md Use `last_request_json()` to retrieve the JSON body of the last request. The `pretty` argument controls the formatting of the output. ```R last_request_json() ``` ```R last_request_json(pretty = FALSE) ``` -------------------------------- ### Print Request with Formatted Headers Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req.md Shows how to print a request with headers that include curly braces, demonstrating proper formatting. ```r req_headers(request("http://test"), x = "{z}", `{z}` = "x") ``` -------------------------------- ### Get JSON response Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/last.md Use `last_response_json()` to retrieve the JSON body of the last response. The `pretty` argument controls the formatting of the output. ```R last_response_json() ``` ```R last_response_json(pretty = FALSE) ``` -------------------------------- ### HTTP Basic Authentication Source: https://context7.com/r-lib/httr2/llms.txt Use req_auth_basic() to add Basic Authentication headers. If the password is omitted, it will be prompted for interactively. Ensure the server supports Basic Auth. ```r request("https://api.example.com/protected") |> req_auth_basic("alice", Sys.getenv("API_PASS")) |> req_dry_run(redact_headers = FALSE) ``` -------------------------------- ### Create Response with Headers Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/resp.md Add headers to a mock response object by providing a character vector of header strings to the `headers` argument. ```r response(200, headers = "Content-Type: text/html") ``` -------------------------------- ### Create Response with Empty File Body Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/resp.md Specify an empty file path for the response body using `new_path()`. The response will indicate no body content. ```r response(200, body = new_path("path-empty")) ``` -------------------------------- ### Simplify headers with curl_simplify_headers Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/curl.md Demonstrates how `curl_simplify_headers` can be used to simplify or retain common headers based on the `simplify_headers` argument. ```R print(curl_simplify_headers(headers, simplify_headers = TRUE)) ``` ```R print(curl_simplify_headers(headers, simplify_headers = FALSE)) ``` -------------------------------- ### httr2::req_stream not exported error Source: https://github.com/r-lib/httr2/blob/main/revdep/problems.md This error indicates that the function 'req_stream' is not exported by the httr2 namespace, causing installation or compilation failures in dependent packages. ```R * installing *source* package ‘eudata’ ... ** package ‘eudata’ successfully unpacked and MD5 sums checked ** using staged installation ** R ** inst ** byte-compile and prepare package for lazy loading Error: object ‘req_stream’ is not exported by 'namespace:httr2' Execution halted ERROR: lazy loading failed for package ‘eudata’ * removing ‘/tmp/workdir/eudata/new/eudata.Rcheck/eudata’ ``` -------------------------------- ### Unparseable template in req_template Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-template.md The template string must follow a parsable format, like 'GET /a/b/c' or 'a/b/c/'. Use this to validate template syntax. ```R req_template(req, "A B C") ``` -------------------------------- ### Print OAuth Client Details (with Function Auth) Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/oauth-client.md Display OAuth client details when the authentication method is a function. The function itself is indicated as '' in the output. ```R oauth_client("x", url, auth = function(...) { xxx }) ``` -------------------------------- ### Print OAuth Client Details (with Secret) Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/oauth-client.md Display OAuth client details when a secret is provided. The secret is redacted in the output for security. ```R oauth_client("x", url, secret = "SECRET") ``` -------------------------------- ### Streaming responses with `req_perform_connection()` / `resp_stream_*()` Source: https://context7.com/r-lib/httr2/llms.txt `req_perform_connection()` returns a response whose body is a live connection, enabling line-by-line or chunk-by-chunk processing without buffering the entire body. Use `resp_stream_raw()`, `resp_stream_lines()`, or `resp_stream_sse()` to read data incrementally. Always call `close(resp)` when done. ```APIDOC ## `req_perform_connection()` / `resp_stream_*()` — Streaming responses `req_perform_connection()` returns a response whose body is a live connection, enabling line-by-line or chunk-by-chunk processing without buffering the entire body. Use `resp_stream_raw()`, `resp_stream_lines()`, or `resp_stream_sse()` to read data incrementally. Always call `close(resp)` when done. ```r # Stream raw bytes in 16 KB chunks req <- request("https://httpbin.org/stream-bytes/65536") resp <- req_perform_connection(req) repeat { chunk <- resp_stream_raw(resp, kb = 16) if (length(chunk) == 0) break cat(sprintf("Received %d bytes\n", length(chunk))) } close(resp) # Stream newline-delimited JSON (e.g., ndjson APIs) resp <- request("https://httpbin.org/stream/5") |> req_perform_connection() while (!resp_stream_is_complete(resp)) { line <- resp_stream_lines(resp, 1) if (length(line)) cat("LINE:", line, "\n") } close(resp) # Server-Sent Events (SSE) resp <- request("https://api.example.com/events/stream") |> req_auth_bearer_token(Sys.getenv("TOKEN")) |> req_perform_connection() for (i in 1:10) { event <- resp_stream_sse(resp) if (!is.null(event)) { cat("Event:", event$event, "Data:", event$data, "\n") } } close(resp) ``` ``` -------------------------------- ### R Package Lazy Loading Error Source: https://github.com/r-lib/httr2/blob/main/revdep/failures.md This output shows an error during the lazy loading phase of an R package installation, specifically mentioning an object 'req_stream' not being exported by the 'httr2' namespace. ```R Error: object ‘req_stream’ is not exported by 'namespace:httr2' Execution halted ERROR: lazy loading failed for package ‘eudata’ * removing ‘/tmp/workdir/eudata/new/eudata.Rcheck/eudata’ ``` -------------------------------- ### Show raw SSE events with verbosity = 3 Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/resp-stream.md Set `verbosity = 3` to visualize raw Server-Sent Events (SSE) as they are parsed. This includes buffer contents, matched data, and remaining buffer. ```R . <- resp_stream_sse(resp) ``` -------------------------------- ### Read from clipboard for curl translation Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/curl.md Demonstrates using `clipr::read_clip()` to provide input for `curl_translate`, simulating reading headers from the clipboard. ```R curl_translate() ``` ```R writeLines(clipr::read_clip()) ``` -------------------------------- ### Failing Callback with Useful Body in httr2 Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-error.md Illustrates how a failing callback in `req_error()` can still generate a useful error body. This example shows how to extract specific error details from a JSON response. ```r req <- request_test("/status/404") req <- req_error(req, body = function(resp) resp_body_json(resp)$error) req_perform(req) ``` -------------------------------- ### Create Response with Raw Body Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/resp.md Include a raw vector as the response body using the `body` argument. This is suitable for binary data. ```r response(200, body = charToRaw("abcdef")) ``` -------------------------------- ### Coerce to Key from Raw Vector or Base64URL String Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/secret.md Use `as_key()` to convert a raw vector or a base64url encoded string into a key. The function expects specific input types for successful coercion. ```r as_key(1) ``` -------------------------------- ### Cache Interaction Debugging Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-cache.md Demonstrates cache interaction during request fetching, showing messages for pruning, saving, and finding responses in the cache. Use these to understand cache behavior. ```R invisible(cache_pre_fetch(req)) ``` ```R invisible(cache_post_fetch(req, resp)) ``` ```R invisible(cache_pre_fetch(req)) ``` ```R invisible(cache_pre_fetch(req)) ``` ```R invisible(cache_post_fetch(req, response(304))) ``` ```R invisible(cache_post_fetch(req, error_cnd())) ``` -------------------------------- ### Mock HTTP Responses with `with_mocked_responses()` Source: https://context7.com/r-lib/httr2/llms.txt Replace real HTTP responses with user-supplied values during testing. Accepts a function, a list of responses, or a formula. When the list is exhausted, returns HTTP 503. Compatible with all `req_perform*` variants. ```r library(httr2) # A function under test fetch_user <- function(id) { request("https://api.example.com/users") |> req_url_path_append(id) |> req_perform() |> resp_body_json() } # Mock with a fixed response mock_fn <- function(req) { response(200, headers = "Content-Type: application/json", body = charToRaw('{"id":1,"name":"Alice"}') ) } result <- with_mocked_responses(mock_fn, fetch_user(1)) result$name # "Alice" # Mock with a sequence of responses (useful for pagination tests) local_mocked_responses( list( response(200, body = charToRaw('{"page":1,"data":[1,2]}')), response(200, body = charToRaw('{"page":2,"data":[]}')) ) ) # Mock based on request content smart_mock <- function(req) { if (grepl("/users/42", req$url)) { response(200, body = charToRaw('{"id":42,"name":"Bob"}')) } else { response(404) } } ``` -------------------------------- ### Create and Inspect httr2 Token Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/oauth-token.md Demonstrates the creation of an httr2 token object and shows its computed expiration time. The output indicates that sensitive token details are redacted upon printing. ```R token <- new_token(type = "bearer", access_token = "secret", expires_in = 3600) token ``` -------------------------------- ### Modify List with Named Arguments Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/utils.md Demonstrates how to add, remove, or override elements in a list using named arguments. Ensure all additional arguments are named. ```R modify_list(x, a = 1, 2) ``` -------------------------------- ### Create a new HTTP request with httr2 Source: https://context7.com/r-lib/httr2/llms.txt Use `request()` to create the root `httr2_request` object. Subsequent `req_*` functions modify this object. Inspect the URL without sending the request using `req_get_url()`. ```r library(httr2) req <- request("https://api.github.com") req #> #> GET https://api.github.com #> Body: empty # Inspect the URL at any time without sending the request req |> req_url_path("/repos/r-lib/httr2") |> req_url_query(state = "open") |> req_get_url() #> [1] "https://api.github.com/repos/r-lib/httr2?state=open" ``` -------------------------------- ### OAuth 2.0 Device Flow with httr2 Source: https://context7.com/r-lib/httr2/llms.txt Implement the device flow for OAuth 2.0, which is useful in headless or command-line interface (CLI) environments where a browser is not available for user authentication. ```r # --- Device Flow (headless / CLI environments) --- request("https://api.example.com/resource") | req_oauth_device( client = service_client, auth_url = "https://auth.example.com/device/code" ) | req_perform() ``` -------------------------------- ### Print httr2 Request Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req.md Demonstrates the default print method for httr2 request objects, showing the HTTP method and URL. ```r req <- request("https://example.com") req ``` -------------------------------- ### Streaming responses with req_perform_connection() and resp_stream_*() Source: https://context7.com/r-lib/httr2/llms.txt Process response bodies incrementally without buffering the entire content. `req_perform_connection()` provides a live connection. Use `resp_stream_raw()`, `resp_stream_lines()`, or `resp_stream_sse()` for reading. Remember to `close(resp)` when finished. ```R # Stream raw bytes in 16 KB chunks req <- request("https://httpbin.org/stream-bytes/65536") resp <- req_perform_connection(req) repeat { chunk <- resp_stream_raw(resp, kb = 16) if (length(chunk) == 0) break cat(sprintf("Received %d bytes\n", length(chunk))) } close(resp) ``` ```R # Stream newline-delimited JSON (e.g., ndjson APIs) resp <- request("https://httpbin.org/stream/5") |> req_perform_connection() while (!resp_stream_is_complete(resp)) { line <- resp_stream_lines(resp, 1) if (length(line)) cat("LINE:", line, "\n") } close(resp) ``` ```R # Server-Sent Events (SSE) resp <- request("https://api.example.com/events/stream") |> req_auth_bearer_token(Sys.getenv("TOKEN")) |> req_perform_connection() for (i in 1:10) { event <- resp_stream_sse(resp) if (!is.null(event)) { cat("Event:", event$event, "Data:", event$data, "\n") } } close(resp) ``` -------------------------------- ### Parse URL Details Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/url.md Parses a URL string and displays its components, including scheme, hostname, credentials, port, path, query parameters, and fragment. Note that special characters in the query are automatically escaped. ```R url_parse("http://user:pass@example.com:81/path?a=1&b=2&c={1{2}3}#frag") ``` -------------------------------- ### Require named headers Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-headers.md All header arguments must be named. Unnamed arguments will cause an error. ```R req_headers(req, 1) ``` -------------------------------- ### Execute an HTTP request and handle responses with httr2 Source: https://context7.com/r-lib/httr2/llms.txt Use `req_perform()` to send a request. It returns an `httr2_response` on success and automatically converts 4xx/5xx status codes into R errors. Responses can be saved directly to disk using the `path` argument. Errors can be handled gracefully using `tryCatch`. ```r # Basic GET resp <- request("https://httpbin.org/get") |> req_url_query(foo = "bar") |> req_perform() resp_status(resp) # 200 resp_content_type(resp) # "application/json" resp_body_json(resp)$args # list(foo = "bar") # Save large responses directly to disk request("https://httpbin.org/bytes/1048576") |> req_perform(path = tempfile()) # Handle errors gracefully tryCatch( request("https://httpbin.org/status/404") |> req_perform(), httr2_http_404 = function(cnd) { message("Resource not found: ", conditionMessage(cnd)) NULL } ) ``` -------------------------------- ### request() — Create a new HTTP request Source: https://context7.com/r-lib/httr2/llms.txt Creates the root httr2_request object that all req_* functions modify. The base_url becomes the initial URL; subsequent calls to req_url_* functions can refine it. ```APIDOC ## request() — Create a new HTTP request Creates the root `httr2_request` object that all `req_*` functions modify. The `base_url` becomes the initial URL; subsequent calls to `req_url_*` functions can refine it. ```r library(httr2) req <- request("https://api.github.com") req #> #> GET https://api.github.com #> Body: empty # Inspect the URL at any time without sending the request req |> req_url_path("/repos/r-lib/httr2") |> req_url_query(state = "open") | req_get_url() #> [1] "https://api.github.com/repos/r-lib/httr2?state=open" ``` ``` -------------------------------- ### Handle Empty Response Body with resp_body_raw Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/resp-body.md Demonstrates the error generated when attempting to retrieve an empty response body using resp_body_raw. ```R resp_body_raw(resp1) ``` ```R resp_body_raw(resp2) ``` -------------------------------- ### Print Request with Repeated Headers Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req.md Illustrates how repeated headers are printed, showing comma-separated values for numeric vectors. ```r req_headers(request("https://example.com"), A = 1:3) ``` -------------------------------- ### as_headers Print Method Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/headers.md as_headers creates a httr2_headers object with a custom print method for displaying headers. ```R as_headers(c("X:1", "Y: 2", "Z:")) ``` ```R as_headers(list()) ``` -------------------------------- ### Mock HTTP for testing Source: https://context7.com/r-lib/httr2/llms.txt Replaces real HTTP responses with user-supplied values during testing. Accepts a function, a list of responses, or a formula. When the list is exhausted, returns HTTP 503. Compatible with all `req_perform*` variants. ```APIDOC ## `with_mocked_responses()` / `local_mocked_responses()` Replaces real HTTP responses with user-supplied values during testing. Accepts a function, a list of responses (returned in sequence), or a formula. When the list is exhausted, returns HTTP 503. Compatible with all `req_perform*` variants. ```r library(httr2) # A function under test fetch_user <- function(id) { request("https://api.example.com/users") |> req_url_path_append(id) |> req_perform() |> resp_body_json() } # Mock with a fixed response mock_fn <- function(req) { response(200, headers = "Content-Type: application/json", body = charToRaw('{"id":1,"name":"Alice"}') ) } result <- with_mocked_responses(mock_fn, fetch_user(1)) result$name # "Alice" # Mock with a sequence of responses (useful for pagination tests) local_mocked_responses( list( response(200, body = charToRaw('{"page":1,"data":[1,2]}')), response(200, body = charToRaw('{"page":2,"data":[]}')) ) ) # Mock based on request content smart_mock <- function(req) { if (grepl("/users/42", req$url)) { response(200, body = charToRaw('{"id":42,"name":"Bob"}')) } else { response(404) } } ``` ``` -------------------------------- ### Inspect Request with `req_dry_run()` Source: https://context7.com/r-lib/httr2/llms.txt Prints the exact HTTP message that would be sent to the server, including all headers and the body. Invaluable for debugging and for documentation of API wrappers. JSON bodies are pretty-printed by default. ```r request("https://api.example.com/submit") |> req_auth_bearer_token("secret-token") |> req_body_json(list(action = "create", name = "test", value = 42)) |> req_dry_run() #> POST /submit HTTP/1.1 #> accept: */* #> accept-encoding: deflate, gzip #> authorization: #> content-length: 43 #> content-type: application/json #> host: api.example.com #> user-agent: httr2/1.2.2 r-curl/... #> #> { #> "action": "create", #> "name": "test", #> "value": 42 #> } ``` -------------------------------- ### Check paths input length for req_perform_sequential Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-perform-sequential.md Validates that if `paths` are supplied, they match the length of `reqs`. Otherwise, an error is raised. ```r req_perform_sequential(list(req), letters) ``` -------------------------------- ### Show buffer info with verbosity = 3 Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/resp-stream.md Set `verbosity = 3` to display detailed buffer information during streaming. This helps in understanding how data chunks are processed and parsed. ```R while (!resp_stream_is_complete(con)) { resp_stream_lines(con, 1) } ``` -------------------------------- ### Paginate through multi-page APIs with req_perform_iterative() Source: https://context7.com/r-lib/httr2/llms.txt Repeatedly calls `next_req()` to fetch subsequent pages until `next_req` returns `NULL` or `max_reqs` is reached. Supports offset, cursor, and link-header based pagination via helper functions like `iterate_with_offset()`, `iterate_with_cursor()`, and `iterate_with_link_url()`. ```R # Offset-based pagination (?page_index=1, ?page_index=2, ...) req <- request("https://api.example.com/items") |> req_url_query(limit = 50) |> req_throttle(capacity = 60, fill_time_s = 60) resps <- req_perform_iterative( req, next_req = iterate_with_offset( "page_index", resp_complete = \(resp) length(resp_body_json(resp)$data) == 0 ), max_reqs = Inf ) ``` ```R # Cursor-based pagination resps <- req_perform_iterative( request("https://api.example.com/events") |> req_url_query(per_page = 100), next_req = iterate_with_cursor( "cursor", resp_param_value = \(resp) resp_body_json(resp)$meta$next_cursor ) ) ``` ```R # GitHub-style Link header pagination resps <- req_perform_iterative( request("https://api.github.com/repos/r-lib/httr2/issues") |> req_url_query(per_page = 30, state = "closed") |> req_auth_bearer_token(Sys.getenv("GITHUB_PAT")), next_req = iterate_with_link_url("next"), max_reqs = 5 ) ``` ```R # Collect all results into a data frame all_issues <- resps_data(resps, \(resp) { purrr::map(resp_body_json(resp), \(x) data.frame(number = x$number, title = x$title)) }) ``` -------------------------------- ### Perform many requests with `req_perform_sequential()` / `req_perform_parallel()` Source: https://context7.com/r-lib/httr2/llms.txt `req_perform_sequential()` performs a list of requests one at a time; `req_perform_parallel()` performs them concurrently using a curl multi-handle pool. Both accept `on_error = "stop" | "return" | "continue"` and return a list of responses and/or error objects. ```APIDOC ## `req_perform_sequential()` / `req_perform_parallel()` — Perform many requests `req_perform_sequential()` performs a list of requests one at a time; `req_perform_parallel()` performs them concurrently using a curl multi-handle pool. Both accept `on_error = "stop" | "return" | "continue"` and return a list of responses and/or error objects. ```r # Build 5 requests reqs <- lapply(1:5, \(i) request("https://httpbin.org/get") |> req_url_query(page = i) |> req_throttle(capacity = 20, fill_time_s = 60) ) # Sequential (safe, unlimited feature set) resps_seq <- req_perform_sequential(reqs, on_error = "continue") # Parallel (faster; requires req_throttle to be polite) resps_par <- req_perform_parallel(reqs, max_active = 5, on_error = "continue") # Filter and extract data from the successful ones successes <- resps_successes(resps_par) failures <- resps_failures(resps_par) data <- resps_data(successes, \(resp) resp_body_json(resp)$args) str(data) ``` ``` -------------------------------- ### Rate-Limit Requests with Token Bucket Source: https://context7.com/r-lib/httr2/llms.txt Use req_throttle() to enforce a maximum request rate to a specific host using a token bucket algorithm. This allows for bursts while maintaining a long-run average rate. ```r # Max 30 requests per minute to this host req <- request("https://api.example.com") |> req_throttle(capacity = 30, fill_time_s = 60) for (i in 1:5) { resp <- req |> req_url_path(paste0("/items/", i)) |> req_perform() cat(i, resp_status(resp), "\n") } # Inspect current token levels throttle_status() #> realm tokens to_wait #> 1 api.example.com 25 0 ``` -------------------------------- ### Case-insensitive header access Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-headers.md Demonstrates that header names are treated case-insensitively when accessing request details. ```R req ``` -------------------------------- ### Forward Errors for Escaped Query Parameter Types Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-url.md Demonstrates error handling for escaped query parameters when the value is not a single string. This prevents unexpected type coercions. ```r req_url_query(req, a = I(1)) ``` -------------------------------- ### URL Manipulation Utilities Source: https://context7.com/r-lib/httr2/llms.txt Standalone URL manipulation functions for building, inspecting, or transforming URLs programmatically. Includes parsing, building, modifying, and query string handling. ```r # Parse a URL into its component parts parsed <- url_parse("https://user:pw@api.example.com:8080/v2/items?q=foo&page=2#top") parsed$scheme # "https" parsed$hostname # "api.example.com" parsed$port # "8080" parsed$path # "/v2/items" parsed$query # list(q = "foo", page = "2") # Build a URL string from components url_build(parsed) #> [1] "https://user:pw@api.example.com:8080/v2/items?q=foo&page=2#top" # Surgically modify URL parts url_modify("https://api.example.com/v1/data", path = "/v2/data", scheme = "http") #> [1] "http://api.example.com/v2/data" url_modify_query("https://api.example.com?a=1&b=2", b = NULL, c = 3) #> [1] "https://api.example.com?a=1&c=3" # Parse and build query strings url_query_parse("a=hello%20world&b=42") #> list(a = "hello world", b = "42") url_query_build(list(search = "r language", page = 1, tags = c("statistics", "data")), .multi = "explode") #> [1] "search=r%20language&page=1&tags=statistics&tags=data" ``` -------------------------------- ### Perform many requests sequentially or in parallel Source: https://context7.com/r-lib/httr2/llms.txt Use `req_perform_sequential()` for one-by-one execution or `req_perform_parallel()` for concurrent requests using a curl multi-handle pool. Both accept `on_error` to control error handling and return lists of responses or errors. Use `req_throttle()` to be polite when performing parallel requests. ```R # Build 5 requests reqs <- lapply(1:5, \(i) request("https://httpbin.org/get") |> req_url_query(page = i) |> req_throttle(capacity = 20, fill_time_s = 60) ) # Sequential (safe, unlimited feature set) resps_seq <- req_perform_sequential(reqs, on_error = "continue") # Parallel (faster; requires req_throttle to be polite) resps_par <- req_perform_parallel(reqs, max_active = 5, on_error = "continue") # Filter and extract data from the successful ones successes <- resps_successes(resps_par) failures <- resps_failures(resps_par) data <- resps_data(successes, \(resp) resp_body_json(resp)$args) str(data) ``` -------------------------------- ### Default Loop Usage in req_perform_promise Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-promise.md Illustrates that `req_perform_promise` uses the default loop. If a pool is not explicitly supplied, an error will occur, prompting the user to provide one. ```R p4 <- req_perform_promise(request_test("/get")) ``` -------------------------------- ### Coerce to Key from Environment Variable Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/secret.md Convert an environment variable name into a key using `as_key()`. This function will error if the environment variable does not exist. ```r as_key("ENVVAR_THAT_DOESNT_EXIST") ``` -------------------------------- ### Print httr2 OAuth Client Source: https://context7.com/r-lib/httr2/llms.txt This snippet shows how to print an httr2 OAuth client object, which will redact sensitive information like secrets in its console output. ```r print(client) ``` -------------------------------- ### Handling Invalid Paths in req_body_file Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-body.md Illustrates error handling for `req_body_file()` when the provided path is invalid, not a file, or a directory. Ensure the path points to a valid file. ```r req_body_file(request_test(), 1) ``` ```r req_body_file(request_test(), "doesntexist") ``` ```r req_body_file(request_test(), ".") ``` -------------------------------- ### Package Loading Failure: httr2 HTTP 404 Error Source: https://github.com/r-lib/httr2/blob/main/revdep/failures.md This error occurs when the 'dataRetrieval' package attempts to perform an HTTP request using httr2, but the endpoint returns a 404 Not Found error. This suggests an issue with the API endpoint or network configuration. ```text Error: package or namespace load failed for ‘dataRetrieval’: .onLoad failed in loadNamespace() for 'dataRetrieval', details: call: httr2::req_perform(check_endpoints_req) error: HTTP 404 Not Found. Error: loading failed Execution halted ``` -------------------------------- ### Iterative Request with User Termination Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-perform-iterative.md Demonstrates how req_perform_iterative returns a single response when iteration is terminated by the user. This is useful for stopping long-running requests early. ```r resps <- req_perform_iterative(req, next_req = next_req) ``` -------------------------------- ### Debugging Test Failures in R Packages Source: https://github.com/r-lib/httr2/blob/main/revdep/problems.md This snippet displays the output from a failed test suite in an R package. It highlights the testthat framework and indicates that specific tests have failed, leading to an execution halt. ```R Running ‘testthat.R’ Running the tests in ‘tests/testthat.R’ failed. Complete output: > # This file is part of the standard setup for testthat. > # It is recommended that you do not modify it. > # > # Where should you do additional test configuration? > # Learn more about the roles of various files in: > # * https://r-pkgs.org/tests.html > # * https://testthat.r-lib.org/reference/test_package.html#special-files ... 19. │ ├─base::tryCatch(...) 20. │ │ └─base (local) tryCatchList(expr, classes, parentenv, handlers) 21. │ │ └─base (local) tryCatchOne(expr, names, parentenv, handlers[[1L]]) 22. │ │ └─base (local) doTryCatch(return(expr), name, parentenv, handler) 23. │ └─base::force(expr) 24. └─rlang::abort(...) [ FAIL 3 | WARN 0 | SKIP 13 | PASS 1821 ] Error: Test failures Execution halted ``` -------------------------------- ### Check unnamed arguments in multi_dots Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/utils-multi.md Ensure all components passed to `...` are named. Unnamed arguments will result in an error. ```R multi_dots(1) ``` -------------------------------- ### Forward Errors for Vector Elements in Query Parameters Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-url.md Illustrates that `req_url_query` raises an error if a vector with multiple elements is provided for a query parameter without a specified multi-value strategy. The user is advised to use `.multi`. ```r req_url_query(req, a = 1:2) ``` -------------------------------- ### Deprecation of req_perform_stream Source: https://github.com/r-lib/httr2/blob/main/tests/testthat/_snaps/req-perform-stream.md Shows the deprecation warning for `req_perform_stream()` and suggests using `req_perform_connection()` instead. ```R . <- req_perform_stream(req, function(x) NULL) ```