Blog / How-to

R

How to get oil prices in R with httr2 and jsonlite

There is no OilPriceAPI package for R, and you do not need one. Send a GET to https://api.oilpriceapi.com/v1/prices/latest with by_code=WTI_USD and an Authorization: Token <your key> header, using httr2, and parse the JSON into a data frame. The script below does that for several codes at once, adds a week of daily history, and handles rate limits.

It is the same request as the R integration guide in our docs, which also shows the older httr package. Both send the same header, so either works.

By OilPriceAPI · Published · Sample run against the live API on Nov 27, 2026 with R 4.4 and httr2 1.3.0

1. Install httr2 and set your key

install.packages(c("httr2", "jsonlite"))

# Keep the key out of your scripts: add this line to ~/.Renviron,
# then restart R.
# OILPRICEAPI_KEY=your_key_here

The native pipe |> in the script needs R 4.1 or later. httr2 uses jsonlite to parse responses, so resp_body_json() returns ordinary R lists.

2. Fetch the latest prices into a data frame

# Latest oil prices from OilPriceAPI into a data frame, with httr2 + jsonlite.
library(httr2)

api_key <- Sys.getenv("OILPRICEAPI_KEY")
if (api_key == "") stop("Set OILPRICEAPI_KEY in your environment or ~/.Renviron")

opa_request <- function(path) {
  request("https://api.oilpriceapi.com/v1") |>
    req_url_path_append(path) |>
    req_headers(Authorization = paste("Token", api_key)) |>
    req_user_agent("my-r-script") |>
    req_timeout(30) |>
    # Put the API's error code and message into R's error text.
    req_error(body = function(resp) {
      b <- tryCatch(resp_body_json(resp), error = function(e) list())
      if (is.list(b$error)) b <- b$error else if (is.list(b$data)) b <- b$data
      fields <- c("error_code", "code", "error", "message")
      as.character(unlist(b[intersect(fields, names(b))]))
    }) |>
    # Retry only the per-minute limit; a quota block (402) is not retried.
    req_retry(
      max_tries = 2,
      is_transient = function(resp) resp_status(resp) == 429 &&
        identical(resp_body_json(resp)$error_code, "RATE_LIMIT_EXCEEDED")
    )
}

# Read one field from every record; a missing field becomes NA.
chr <- function(items, name) vapply(items, function(x)
  if (is.null(x[[name]])) NA_character_ else as.character(x[[name]]), "")
num <- function(items, name) vapply(items, function(x)
  if (is.null(x[[name]])) NA_real_ else as.numeric(x[[name]]), 0)

latest_prices <- function(codes) {
  body <- opa_request("prices/latest") |>
    req_url_query(by_code = paste(codes, collapse = ",")) |>
    req_perform() |>
    resp_body_json()
  # One code returns a flat object at data; two or more return data$prices.
  items <- if (!is.null(body$data$prices)) body$data$prices else list(body$data)
  data.frame(
    code        = chr(items, "code"),
    price       = num(items, "price"),
    currency    = chr(items, "currency"),
    observed_at = as.POSIXct(chr(items, "observed_at"),
                             format = "%Y-%m-%dT%H:%M:%OS", tz = "UTC")
  )
}

daily_history <- function(code) {
  body <- opa_request("prices/past_week") |>
    req_url_query(by_code = code, interval = "1d") |>
    req_perform() |>
    resp_body_json()
  items <- body$data$prices
  data.frame(
    date  = as.Date(substr(chr(items, "created_at"), 1, 10)),
    price = num(items, "price")
  )
}

prices <- latest_prices(c("WTI_USD", "BRENT_CRUDE_USD"))
print(prices)

wti_week <- daily_history("WTI_USD")
print(wti_week)

latest_prices() returns one row per code with the columns code, price, currency and observed_at, the time the source observed the price (in UTC). Put up to 20 codes in one call; they count as one request. Two or more codes come back as data$prices, and a single code comes back as a flat data object, which is why the function checks for both. Always pass by_code: without it the endpoint returns Brent.

We ran the script verbatim against the live API on Nov 27, 2026. latest_prices() returned two rows, and daily_history() returned five daily rows for Nov 20 to 26. Weekend days have no row. A single code parsed to one row.

3. Daily history, not raw ticks

/v1/prices/past_week on its own returns raw intraday points, capped at 100 per page. On Nov 27 that covered only the last 2 of the 8 requested days, and the response said so in data$metadata$truncation. Adding interval = "1d", as daily_history() does, returns one averaged point per day instead. The date comes from created_at, because a daily average has no single observed_at.

For a longer daily series, use /v1/prices/historical with start_date and end_date; it accepts at most 5 codes per request. The historical data guide covers it in Python, and the request is the same from R.

4. What happens on an error

req_error() copies the API's error code and message into the R error, so a failed call tells you what to fix. req_retry() retries only the per-minute rate limit:

StatusCodeCauseWhat the script does
429RATE_LIMIT_EXCEEDEDMore than 60 requests in one 60-second windowreq_retry() waits Retry-After seconds and tries once more
402PAYMENT_REQUIRED or MONTHLY_QUOTA_EXCEEDEDThe daily (Free) or monthly (paid) quota is used upStops with the code; retrying will not help until the quota resets
429TRIAL_LIMIT_EXCEEDEDAn active trial has used its requestsStops at once; its Retry-After can be days away
401UNAUTHORIZEDMissing or wrong keyStops with the API's message; check OILPRICEAPI_KEY
400invalid_codeA code in by_code does not existStops with the API's suggested codes

We checked the 401 and 400 rows against the live API, and the 429 and 402 rows against a local stub server, including a trial 429 with a five-day Retry-After, which the script reports at once instead of sleeping. Every limit and error code is listed in the rate limiting guide.

5. Do not poll faster than the data

Brent updates about every 2.5 minutes and WTI about every 5, so a loop that calls latest_prices() every few seconds gets the same rows back and spends requests. Cache the data frame for five minutes, or see how to cache OilPriceAPI requests for ETag revalidation, which returns an uncharged 304 when nothing changed.

Related guides

Run it with your own key

New accounts get a 7-day trial with 10,000 requests and no credit card. After that, the Free plan is 50 requests/day. The Developer plan is $19/month for 10,000 requests/month.

Sources

  • docs.oilpriceapi.com/developers/r: packages, header and endpoints, read Nov 27, 2026.
  • docs.oilpriceapi.com/guides/rate-limiting: limits, error codes and publication cadence, read Nov 26, 2026.
  • Live calls to /v1/prices/latest and /v1/prices/past_week from the script above, Nov 27, 2026, R 4.4 and httr2 1.3.0.