Blog / How-to
How to cache OilPriceAPI requests and stay inside your rate limits
Put every code you need in one call to GET /v1/prices/latest (up to 20 codes count as one request), keep the response for as long as the slowest-changing series takes to publish, and revalidate with the response's ETag. If nothing changed, the API returns 304 Not Modified, and a 304 does not count against your quota.
Two limits apply to every key: a request quota (per day on the Free plan, per month on paid plans) and a rate limit of 60 requests per fixed 60-second window, the same on every plan. A 429 means wait and retry; a 402 means the quota is spent and retrying will not help.
By OilPriceAPI · Published · Limits and headers as documented and served on Nov 26, 2026
1. Batch your codes
Three separate requests for Brent, WTI and natural gas cost three requests. One request with all three costs one:
curl -s -i "https://api.oilpriceapi.com/v1/prices/latest?by_code=BRENT_CRUDE_USD,WTI_USD,NATURAL_GAS_USD" \
-H "Authorization: Token $OILPRICEAPI_KEY"Two or more codes return data.prices[]; a single code returns a flat data object. More than 20 codes returns 400, and a request that includes a futures code (one containing _FUTURES_) is limited to 10. Each record carries observed_at, the time the source observed the price, so you can tell a fresh value from a repeated one. Always pass by_code: without it the endpoint returns Brent.
2. Revalidate with the ETag instead of re-downloading
Every response carries an ETag and a Last-Modified header. Send the ETag back as If-None-Match on the next call:
curl -s -i "https://api.oilpriceapi.com/v1/prices/latest?by_code=BRENT_CRUDE_USD,WTI_USD,NATURAL_GAS_USD" \
-H "Authorization: Token $OILPRICEAPI_KEY" \
-H 'If-None-Match: W/"<etag from the previous response>"'If no price in the batch changed, the answer is 304 Not Modified with an empty body. A 304 is not charged against your quota. A conditional request whose price did change returns a normal 200 with the new body, charged as usual. We checked this on Nov 26, 2026: eight conditional requests returned 304 without changing X-RateLimit-Used.
A 304 still uses one slot of the 60-per-60-second rate limit, so revalidation lets you poll more often within your quota, not faster than the rate limit. If-Modified-Since with the Last-Modified value is documented to work the same way. Details are in the conditional requests reference.
3. Cache for as long as the data takes to change
Polling faster than a series publishes cannot return a new value. These intervals are from the rate limiting guide:
| Series | New value | Cache for |
|---|---|---|
BRENT_CRUDE_USD | about every 2.5 minutes | 5 minutes |
WTI_USD, NATURAL_GAS_USD | about every 5 minutes | 5 minutes |
DIESEL_USD, GASOLINE_USD | about twice a day | 6 hours |
Weekly inventory and rig counts | weekly | once a day |
Monthly reports (OPEC, EIA STEO) | monthly | once a day |
Source: docs.oilpriceapi.com/guides/rate-limiting, “How often the data actually changes” and “Series that publish on a schedule”, read Nov 26, 2026.
A five-minute cache is already at the resolution of the fastest series we publish. A larger plan buys more codes and endpoints, not fresher prices. If one batch mixes fast and slow series, split it into two batches with their own cache times.
4. A cache client in Python
This uses only the standard library. It serves from memory for MAX_AGE seconds, revalidates with the stored ETag, waits once on a per-minute 429 (RATE_LIMIT_EXCEEDED), and keeps serving the last good prices on a quota block, whose Retry-After can be days away:
"""Cache OilPriceAPI latest prices: one batched call, ETag revalidation,
and the documented 429 and 402 handling. Standard library only."""
import json
import os
import time
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
API_URL = "https://api.oilpriceapi.com/v1/prices/latest"
KEY = os.environ["OILPRICEAPI_KEY"]
CODES = ["BRENT_CRUDE_USD", "WTI_USD", "NATURAL_GAS_USD"] # up to 20 per call
MAX_AGE = 300 # seconds; nothing on this list publishes faster than ~2.5 min
_cache = {"etag": None, "prices": None, "fetched_at": 0.0}
def latest_prices():
"""Return {code: price record}, calling the API at most once per MAX_AGE."""
if _cache["prices"] and time.time() - _cache["fetched_at"] < MAX_AGE:
return _cache["prices"]
headers = {"Authorization": "Token " + KEY}
if _cache["etag"]:
headers["If-None-Match"] = _cache["etag"] # a 304 is not charged
url = API_URL + "?" + urlencode({"by_code": ",".join(CODES)})
for attempt in range(2):
try:
with urlopen(Request(url, headers=headers), timeout=15) as resp:
body = json.load(resp)
remaining = resp.headers.get("X-RateLimit-Remaining")
data = body["data"]
records = data["prices"] if "prices" in data else [data]
_cache.update(
etag=resp.headers.get("ETag"),
prices={r["code"]: r for r in records},
fetched_at=time.time(),
)
print(f"200: refreshed, {remaining} requests left in this window")
return _cache["prices"]
except HTTPError as err:
if err.code == 304: # unchanged: keep the cached body
_cache["fetched_at"] = time.time()
print("304: unchanged, served from cache")
return _cache["prices"]
try:
code = json.load(err).get("error_code")
except ValueError:
code = None
if code == "RATE_LIMIT_EXCEEDED" and attempt == 0:
# Per-minute limit: Retry-After is seconds to the window reset.
wait = int(err.headers.get("Retry-After", "60"))
print(f"429: waiting {wait}s, then one retry")
time.sleep(wait)
continue
if err.code in (402, 429) and _cache["prices"]:
# Quota spent (402, or a trial's 429). Retry-After here can be
# days away, so do not wait on it; serve the last good value.
print(f"{err.code} {code}: serving cached prices")
return _cache["prices"]
raise # a second 429, or a quota block with nothing cached
if __name__ == "__main__":
for record in latest_prices().values():
print(record["code"], record["price"], record["observed_at"])We ran it against the live API on Nov 26, 2026. The first call returned 200, the second was served from memory with no request, and a forced revalidation returned 304. The 429 and 402 branches, including a trial 429 with a five-day Retry-After, were run against a local stub server. For several processes or servers, keep the same three fields (ETag, prices, fetch time) in a shared store such as Redis, so each process does not spend its own requests.
The workflow
Your app asks for prices
Cache younger than MAX_AGE
- Serve from memory
- No request sent
Cache expired
- GET /v1/prices/latest with If-None-Match
- 304: keep the cached body (not charged)
- 200: store the new body and ETag
429 RATE_LIMIT_EXCEEDED: wait Retry-After seconds, retry once
402, or a trial 429: serve the cached prices until the quota resets
5. Read the rate-limit headers
On a normal response, the X-RateLimit-* headers describe your quota, not the 60-second window:
| Header | Meaning |
|---|---|
X-RateLimit-Limit | Your request quota for the current window |
X-RateLimit-Remaining | Requests left in the current window |
X-RateLimit-Used | Requests used in the current window |
X-RateLimit-Reset | Unix timestamp when the quota window resets |
X-RateLimit-Window | Whether the quota is counted per day or per month |
ETag, Last-Modified | Validators to send back as If-None-Match |
X-Request-Id | Quote it when you contact support |
On a per-minute 429, X-RateLimit-Limit, Remaining and Reset switch to describing the 60-second window, and Retry-After and X-RateLimit-Reset are seconds until that window resets, not a timestamp. The window is fixed and aligned to the clock, so ten requests in the same second are fine.
429 or 402: which to retry
| Status | error_code | Cause | What to do |
|---|---|---|---|
| 429 | RATE_LIMIT_EXCEEDED | More than 60 requests in one 60-second window | Sleep Retry-After seconds, then retry once |
| 402 | PAYMENT_REQUIRED or MONTHLY_QUOTA_EXCEEDED | The daily (Free) or monthly (paid) quota is used up | Do not retry; serve the cached value until reset.date |
| 429 | TRIAL_LIMIT_EXCEEDED | An active trial has used its 10,000 requests | Do not retry; reset.date in the body is the trial end |
Branch on error_code, not on the status alone. A quota block also carries Retry-After, but it counts the seconds to the quota reset, which can be hours or days. Once a key is over quota, its rate limit drops to 5 requests per 60 seconds, so a client that keeps retrying a 402 starts collecting 429s too. Every lane and field is listed in the rate limiting guide.
Related guides
- Oil price webhooks vs polling: when a pushed update replaces the poll altogether.
- Python oil price API tutorial: the latest-price request and the official SDK.
- Download historical Brent and WTI data to CSV: history endpoints accept at most 5 codes per request.
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. All plans share the same 60-per-60-second rate limit.
Sources
- docs.oilpriceapi.com/guides/rate-limiting: limits, headers, error codes and publication cadence, read Nov 26, 2026.
- docs.oilpriceapi.com/api-reference/prices/latest, conditional requests section, read Nov 26, 2026.
- GET https://api.oilpriceapi.com/v1/meta/limits (60 requests per 60-second fixed window, every plan), fetched Nov 26, 2026.
- Live calls to /v1/prices/latest on Nov 26, 2026: response headers and eight 304 responses with X-RateLimit-Used unchanged.