Blog / How-to
How to load oil prices into BigQuery or Snowflake
There is no native OilPriceAPI connector for BigQuery or Snowflake. The way in is a scheduled REST load: a script calls the API, writes a CSV, and the warehouse loads the file into a staging table and merges it into your prices table. The script and the SQL are below.
The latest price from /v1/prices/latest works on every plan. Daily history from past_week and past_year needs an active 7-day trial or a paid plan; a Free plan key gets 402 UPGRADE_REQUIRED.
By OilPriceAPI · Published · Export script run against the live API on Nov 27, 2026
The workflow
Set OILPRICEAPI_KEY on the machine that runs the job
oil_to_csv.py writes oil_prices.csv
latest, daily or backfill
bq load, or PUT + COPY INTO, fills a staging table
MERGE staging into the prices table
Repeat on a schedule (cron or your orchestrator)
1. Check the request in a terminal
curl -s \
-H "Authorization: Token YOUR_API_KEY" \
"https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD"Always pass by_code. In the JSON response, data.price is the value and data.observed_at is the time the source published it. That source timestamp is what the script stores as price_time for latest rows.
2. Export to one CSV
Save this as oil_to_csv.py, set OILPRICEAPI_KEY in the environment, and run it with Python 3. It uses only the standard library. Edit CODES to change the series.
import csv
import io
import json
import os
import sys
import urllib.error
import urllib.request
API = "https://api.oilpriceapi.com/v1/prices"
KEY = os.environ["OILPRICEAPI_KEY"]
CODES = ["WTI_USD", "BRENT_CRUDE_USD"]
OUT = "oil_prices.csv"
COLUMNS = ["code", "price_time", "price", "currency", "unit", "kind"]
def get(path):
req = urllib.request.Request(API + path, headers={"Authorization": "Token " + KEY})
try:
with urllib.request.urlopen(req, timeout=30) as resp:
return resp.headers, resp.read().decode("utf-8")
except urllib.error.HTTPError as err:
body = json.loads(err.read() or b"{}")
detail = body.get("error") if isinstance(body.get("error"), dict) else body
name = detail.get("code") or detail.get("error_code", "")
message = detail.get("message") or body.get("error", "")
sys.exit(f"{path}: {err.code} {name} {message}")
def latest(code):
# Any plan. observed_at is when the source published the price.
_, text = get(f"/latest?by_code={code}")
d = json.loads(text)["data"]
return [[d["code"], d["observed_at"], d["price"], d["currency"], d["unit"], "latest"]]
def daily(code, window):
# Trial or paid plan. One row per UTC day; created_at is the day.
headers, text = get(f"/{window}?by_code={code}&interval=1d&format=csv")
if headers.get("X-Total-Pages", "1") != "1":
sys.exit(f"{code}: more than one page; use a shorter window")
return [
[r["code"], r["created_at"], r["price"], r["currency"], r["unit"], "daily"]
for r in csv.DictReader(io.StringIO(text))
]
mode = sys.argv[1] if len(sys.argv) > 1 else "latest"
rows = []
for code in CODES: # one code per request: one response shape, one page
if mode == "latest":
rows += latest(code)
elif mode == "daily":
rows += daily(code, "past_week")
elif mode == "backfill":
rows += daily(code, "past_year")
else:
sys.exit("usage: oil_to_csv.py [latest|daily|backfill]")
with open(OUT, "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(COLUMNS)
writer.writerows(rows)
print(f"Wrote {len(rows)} {mode} rows for {len(CODES)} codes to {OUT}")| Mode | Request | Plan | Rows |
|---|---|---|---|
latest | GET /v1/prices/latest | Any plan | One row per code; price_time is the source's observed_at |
daily | GET /v1/prices/past_week, interval=1d | Trial or paid | Last 5 trading days per code; re-loads overlap and are merged |
backfill | GET /v1/prices/past_year, interval=1d | Trial or paid | A year of daily rows per code; run once |
We ran all three modes against the live API on Nov 27, 2026: latest wrote 2 rows, daily 10 rows and backfill 522 rows, with no repeated code, time and kind. With a wrong key it stops with 401 UNAUTHORIZED and the API's message. A Free plan key in daily or backfill mode stops with 402 UPGRADE_REQUIRED instead of writing an empty file. Every file has the same six columns:
code,price_time,price,currency,unit,kind
WTI_USD,2026-11-26T00:00:00.000Z,<price>,USD,barrel,daily3a. Load into BigQuery
Create the dataset and the target table once, in the BigQuery console or with bq query --use_legacy_sql=false:
CREATE SCHEMA IF NOT EXISTS oil;
CREATE TABLE IF NOT EXISTS oil.prices (
code STRING, price_time TIMESTAMP, price NUMERIC,
currency STRING, unit STRING, kind STRING
);Then, after each export, load the file into a staging table that is replaced every run, and merge it into oil.prices:
bq load --source_format=CSV --skip_leading_rows=1 --replace \
oil.prices_staging ./oil_prices.csv \
code:STRING,price_time:TIMESTAMP,price:NUMERIC,currency:STRING,unit:STRING,kind:STRING
bq query --use_legacy_sql=false '
MERGE oil.prices t
USING oil.prices_staging s
ON t.code = s.code AND t.price_time = s.price_time AND t.kind = s.kind
WHEN MATCHED THEN UPDATE SET price = s.price
WHEN NOT MATCHED THEN INSERT ROW'3b. Load into Snowflake
Create both tables once:
CREATE TABLE IF NOT EXISTS oil_prices_staging (
code STRING, price_time TIMESTAMP_NTZ, price NUMBER(12, 4),
currency STRING, unit STRING, kind STRING
);
CREATE TABLE IF NOT EXISTS oil_prices LIKE oil_prices_staging;Then, after each export, upload the file to the staging table's stage, copy it in and merge. PUT uploads a local file and cannot run from a Snowsight worksheet, so run these with the Snowflake CLI (snow sql) or a driver. The script writes UTC times ending in Z; the explicit TIMESTAMP_FORMAT reads them, and TIMESTAMP_NTZ keeps them as UTC wall-clock time:
PUT file:///opt/oil/oil_prices.csv @%oil_prices_staging OVERWRITE = TRUE;
TRUNCATE TABLE oil_prices_staging;
COPY INTO oil_prices_staging
FROM @%oil_prices_staging
FILE_FORMAT = (
TYPE = CSV SKIP_HEADER = 1
TIMESTAMP_FORMAT = 'YYYY-MM-DD"T"HH24:MI:SS.FF3"Z"'
)
PURGE = TRUE;
MERGE INTO oil_prices t
USING oil_prices_staging s
ON t.code = s.code AND t.price_time = s.price_time AND t.kind = s.kind
WHEN MATCHED THEN UPDATE SET price = s.price
WHEN NOT MATCHED THEN INSERT (code, price_time, price, currency, unit, kind)
VALUES (s.code, s.price_time, s.price, s.currency, s.unit, s.kind);4. Run it on a schedule
Run backfill once, then daily once a day. Put the load commands for your warehouse in load.sh.
# 06:00 UTC daily: yesterday's daily rows, then the load
0 6 * * * cd /opt/oil && python3 oil_to_csv.py daily && ./load.shEach run costs one request per code. Two codes once a day is about 60 requests a month. daily re-reads the last week, so a missed run fills itself in the next day, and the MERGE updates a changed price instead of adding a second row. Timestamps are UTC. Keep the API key in the job's environment or your secret manager, never in a table or a committed file.
Related guides
- Historical oil price data API guide: custom date ranges, plan depth and the 402.
- Historical oil prices API: intervals and how far back each series goes.
- How to get oil prices in Tableau: the same CSV export, opened in Tableau.
Try 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
- Live calls to /v1/prices/latest, /v1/prices/past_week and /v1/prices/past_year, Nov 27, 2026, including a bad key.
- BigQuery docs (bq load, MERGE) and Snowflake docs (PUT, COPY INTO, MERGE), read Nov 27, 2026. The warehouse commands were not run for this post.