Skip to contents

When constructing API calls programmatically, you may encounter situations where an upstream task should indicate which function to apply. For example, one endpoint might use a special security function that isn't used by other endpoints. This function exists to make coding such situations easier.

Usage

do_if_fn_defined(x, fn = NULL, ...)

Arguments

x

An object to potentially modify, such as a httr2::request() object.

fn

A function to apply to x. If fn is NULL, x is returned unchanged.

...

Additional arguments to pass to fn.

Value

The object, potentially modified.

Examples

build_api_req <- function(endpoint, security_fn = NULL, ...) {
  req <- httr2::request("https://example.com")
  req <- httr2::req_url_path_append(req, endpoint)
  do_if_fn_defined(req, security_fn, ...)
}

# Most endpoints of this API do not require authentication.
unsecure_req <- build_api_req("unsecure_endpoint")
unsecure_req$headers
#> list()

# But one endpoint requires
secure_req <- build_api_req(
  "secure_endpoint", httr2::req_auth_bearer_token, "secret-token"
)
secure_req$headers$Authorization
#> [1] "Bearer secret-token"