Convert an example curl / httr request to a R function
Convert the provided curl / httr request example into a generic R function. The function should strictly adhere to the robust, explicit, and chainable design principles of the `httr2` package, prioritizing clarity, predictable behavior, and comprehensive error handling.
It must:
- **Core Packages:** Utilize `tidyverse`, `httr2`, and `cli` for all operations.
- **Piping Discipline:** Employ the `magrittr` pipe (`%>%`) exclusively for chaining operations,
reflecting `httr2`'s idiomatic, step-by-step request building.
- **Function Signature:** The primary input parameter for the function must be name `query`.
A second parameter, `path`, should be included to specify the endpoint path relative to the base URL.
- **Base URL Handling:**
- Retrieve the base API URL from the environment variable named `burl` using `Sys.getenv("burl", unset = NA)`.
- The initial `httr2::request()` call should use this `burl` as its base.
- The `path` parameter of the function should then be appended to this base URL using `httr2::req_url_path_append()`.
- **API Key Handling:**
- Apply the API key to the request using `httr2::req_headers("x-api-key" = ct_api_key())`. The key should never be hardcoded in. If one is present in the original request, use the ct_api_key() which pulls it from the Sys.getenv() for you instead. This is extremely important.
- **Environment Variable Controls:**
- **Debug Mode (`run_debug`):** Check for a boolean flag `run_debug` from `Sys.getenv("run_debug")`.
If `TRUE`, the function *must* use `httr2::req_dry_run()` instead of `req_perform()` for all requests.
In this mode, the function should return the `httr2_request` object(s) or dry-run output
instead of attempting to parse or process a live response. A `cli` message should inform the user that debug/dry-run mode is active.
- **Verbose Output (`run_verbose`):** Check for a boolean flag `run_verbose` from `Sys.getenv("run_verbose")`.
If `TRUE`, for multiple/sequential requests, print the current iteration number using a `cli` message
(e.g., `cli::cli_alert_info("Processing query {current_index} of {total_queries}: item_id = {current_item}")`).
- **Request Construction (httr2-idiomatic):**
- Construct the HTTP request using `httr2`'s expressive and chainable syntax
(e.g., `request() %>% req_url_path_append() %>% req_url_query() %>% ...`).
Each modification to the request (URL, query parameters, body, headers, etc.)
should be an explicit, separate step in the chain.
- Remove any unnecessary or default headers to keep requests concise and transparent.
- For GET requests involving multiple `query` items, process them sequentially
using `purrr::map` with a `cli` progress indicator.
- Include robust options like `req_timeout()` for network resilience.
- **Robust Error Handling & Information (httr2-aligned):**
- Wrap the core request execution (or `req_dry_run` if debug mode) using `purrr::safely` or `purrr::possibly`
to gracefully manage R-level errors (e.g., network issues, malformed JSON parsing)
without crashing the function.
- After `req_perform()`, explicitly check for HTTP errors (e.g., 4xx, 5xx status codes)
using `httr2::resp_is_error()`. Provide clear, user-friendly `cli` messages
for success, warnings, and errors based on the HTTP status.
- Output all user-facing messages (progress, success, warnings, errors, debugging info)
using `cli` functions (e.g., `cli::cli_alert_info`, `cli::cli_alert_success`,
`cli::cli_alert_warning`, `cli::cli_alert_danger`) instead of `print`, `message`, or `cat`.
- Display the following `cli` debugging information *before* initiating any HTTP requests:
" cli_rule(left = "<INSERT SEARCH PARAMETER HERE> payload options")
cli_dl(c("Number of compounds" = "{length(query)}"))
cli_rule()
cli_end() "
- **Response Processing:**
- Parse successful JSON responses using `httr2::resp_body_json()`. (This step is skipped if `RUN_DEBUG` is TRUE).
- Where appropriate and possible, transform the parsed response into a `tibble`
for structured data representation; otherwise, return a well-structured list.
- **Modularity and Readability:** Ensure clear separation of concerns between
request setup, execution, and response parsing, consistent with `httr2`'s design
philosophy for maintainable and understandable code.