OilPriceAPI Docs
Quick Start
API Reference
  • SDKs and languages
  • Tutorials
  • Articles
  • Documentation directory
  • Quick reference
  • API explorer
  • FAQ
  • Changelog
  • Status
  • Dashboard
GitHub
Quick Start
API Reference
  • SDKs and languages
  • Tutorials
  • Articles
  • Documentation directory
  • Quick reference
  • API explorer
  • FAQ
  • Changelog
  • Status
  • Dashboard
GitHub
  • Getting Started

    • Quick Start Guide - OilPriceAPI
    • Making Requests
    • Handling Responses
  • SDK Quick Start

    • Python SDK
    • JavaScript/Node.js SDK

Python SDK

Get started with the official OilPriceAPI Python SDK in under 2 minutes.

Installation

pip install oilpriceapi

Requirements: Python 3.8+

Quick Start

from oilpriceapi import OilPriceAPI

# Initialize client (uses OILPRICEAPI_KEY env var by default)
client = OilPriceAPI()

# Get latest Brent Crude price
brent = client.prices.get("BRENT_CRUDE_USD")
print(f"Brent Crude: ${brent.value:.2f}/{brent.unit} at {brent.timestamp.isoformat()}")
# Output: Brent Crude: $104.32/barrel at 2026-09-13T14:51:34.609000+00:00

Values move, so the number above is whatever Brent last traded at, not a constant. Always read unit and timestamp with the value — the same call against GASOLINE_USD returns a price per gallon, not per barrel.

Authentication

# Method 1: Environment variable (recommended)
# export OILPRICEAPI_KEY="your_api_key"
client = OilPriceAPI()

# Method 2: Direct initialization
client = OilPriceAPI(api_key="your_api_key")

# Method 3: With configuration
client = OilPriceAPI(
    api_key="your_api_key",
    timeout=30,
    max_retries=3
)

Common Operations

Get Multiple Prices

prices = client.prices.get_multiple(["BRENT_CRUDE_USD", "WTI_USD", "NATURAL_GAS_USD"])
for price in prices:
    print(f"{price.commodity}: ${price.value:.2f}/{price.unit}")
# BRENT_CRUDE_USD: $104.32/barrel
# WTI_USD: $99.99/barrel
# NATURAL_GAS_USD: $2.83/mmbtu

Historical Data with Pandas

# Get historical data as DataFrame (requires: pip install "oilpriceapi[pandas]")
df = client.prices.to_dataframe(
    commodity="BRENT_CRUDE_USD",
    start="2026-01-01",
    end="2026-03-31",
    interval="daily"
)

print(f"Retrieved {len(df)} data points")
print(df.head())

# Calculate moving averages — the price column is `value`
df['SMA_20'] = df['value'].rolling(window=20).mean()

The frame is indexed by date and carries these columns:

COLUMNS: ['commodity', 'value', 'currency', 'unit', 'type_name']

                                 commodity  value currency    unit      type_name
date
2026-01-01 00:00:00+00:00  BRENT_CRUDE_USD  60.91      USD  barrel  daily_average
2026-01-02 00:00:00+00:00  BRENT_CRUDE_USD  60.77      USD  barrel  daily_average
2026-01-05 00:00:00+00:00  BRENT_CRUDE_USD  61.11      USD  barrel  daily_average

Keep currency and unit alongside the number. A Brent value is per barrel; a retail gasoline value is per gallon or per litre depending on the series.

Diesel Prices

client.diesel.* is broken in SDK v1.13.0

client.diesel.get_price() and client.diesel.get_stations() raise a pydantic ValidationError on v1.13.0. The API nests the record under data, and the SDK unpacks the envelope one level too high. Tracked in python-sdk#110; this page will switch back to the typed helpers once a release ships the fix.

Until then, call the endpoint through the client's own request() method, which returns the parsed JSON envelope unchanged.

import os

from oilpriceapi import OilPriceAPI

with OilPriceAPI(api_key=os.environ["OILPRICEAPI_KEY"]) as client:
    payload = client.request(
        "GET",
        "/v1/diesel-prices",
        params={"state": "CA"},
        timeout=30,
    )

average = payload["data"]["regional_average"]
print(
    f"{average['region']} diesel: "
    f"{average['price']} {average['currency']}/{average['unit']} "
    f"({average['source']}, {average['updated_at']})"
)
# california diesel: 8.136 USD/gallon (aaa, 2026-09-13T14:57:19Z)

data.sources in the same response breaks the average out by contributing source (aaa, eia, padd), each with its own updated_at. Station-level pricing is a separate paid endpoint — see the diesel API reference for its parameters.

Price Alerts

# Create a price alert with webhook notification
alert = client.alerts.create(
    name="Brent High Alert",
    commodity_code="BRENT_CRUDE_USD",
    condition_operator="greater_than",
    condition_value=85.00,
    webhook_url="https://your-server.com/webhook",
    enabled=True,
    cooldown_minutes=60
)

print(f"Alert created: {alert.id}")

# List all alerts
alerts = client.alerts.list()
for alert in alerts:
    print(f"{alert.name}: {alert.trigger_count} triggers")

Async Support

import asyncio
from oilpriceapi import AsyncOilPriceAPI

async def get_prices():
    async with AsyncOilPriceAPI() as client:
        prices = await asyncio.gather(
            client.prices.get("BRENT_CRUDE_USD"),
            client.prices.get("WTI_USD"),
            client.prices.get("NATURAL_GAS_USD")
        )
        return prices

prices = asyncio.run(get_prices())

Error Handling

An unrecognised commodity code is rejected by the API with HTTP 400, so the SDK raises BadRequestError — not DataNotFoundError. The error carries the catalog's own recovery values, so you can act on it instead of guessing:

from oilpriceapi.exceptions import (
    OilPriceAPIError,
    AuthenticationError,
    BadRequestError,
    RateLimitError,
)

try:
    price = client.prices.get("INVALID_CODE")
except BadRequestError as e:
    print(f"Bad request: {e}")
    print(f"Rejected codes: {e.invalid_codes}")
    print(f"Did you mean: {e.suggestions}")
except AuthenticationError:
    print("Replace the missing, expired, or revoked API key.")
except RateLimitError as e:
    print(f"Rate limited. Resets in {e.seconds_until_reset}s")
except OilPriceAPIError as e:
    print(f"API error: {e} (request_id={e.request_id})")

Running that against production prints:

Bad request: [400] Code 'INVALID_CODE' not found. Did you mean: 'US_CPI_CORE'? See /v1/commodities for all available codes.
Rejected codes: ['INVALID_CODE']
Did you mean: ['US_CPI_CORE']

DataNotFoundError is still raised where the API genuinely returns 404 — a valid code with no observation in the requested window, for example.

To find a code rather than guess at one, search the live catalog:

matches = client.commodities.search("brent crude", limit=5)
print([commodity["code"] for commodity in matches])
# ['BRENT_CRUDE_USD', 'BRENT_FUTURES', 'BRENT_FUTURES_CONTINUOUS', 'BRENT_SPOT_EUROPE_USD', 'BRENT_SPOT_USD']

Available Commodities

Oil & Gas:

  • BRENT_CRUDE_USD - Brent Crude Oil (USD/barrel)
  • WTI_USD - West Texas Intermediate (USD/barrel)
  • NATURAL_GAS_USD - US Natural Gas (USD/mmbtu)
  • DIESEL_USD - Diesel (USD/gallon)
  • GASOLINE_USD - Gasoline (USD/gallon)
  • HEATING_OIL_USD - Heating Oil (USD/gallon)

Coal:

  • CAPP_COAL_USD - Central Appalachian Coal (USD/short_ton)
  • PRB_COAL_USD - Powder River Basin Coal (USD/short_ton)
  • NEWCASTLE_COAL_USD - Newcastle API6 (USD/metric_ton)

View the available commodity catalog

SDK Features

  • Type Safe - Full type hints for IDE autocomplete
  • Pandas Integration - First-class DataFrame support
  • Price Alerts - Automated monitoring with webhook notifications
  • Diesel Prices - State averages + station-level pricing
  • Async Support - High-performance async client
  • Rate Limit Handling - Automatic retries with backoff

Links

  • PyPI Package
  • GitHub Repository
  • Full SDK Documentation

Next Steps

  • API Reference - All available endpoints
  • Error Codes - Handle errors gracefully
  • Rate Limiting - Understand usage limits
Last Updated: 9/13/26, 3:48 PM
Next
JavaScript/Node.js SDK