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}")
# Output: Brent Crude: $71.45
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,
cache="memory",
cache_ttl=300
)
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}")
Historical Data with Pandas
# Get historical data as DataFrame
df = client.prices.to_dataframe(
commodity="BRENT_CRUDE_USD",
start="2024-01-01",
end="2024-12-31",
interval="daily"
)
print(f"Retrieved {len(df)} data points")
print(df.head())
# Calculate moving averages
df['SMA_20'] = df['price'].rolling(window=20).mean()
Diesel Prices
# Get state average diesel price (free tier)
ca_price = client.diesel.get_price("CA")
print(f"California diesel: ${ca_price.price:.2f}/gallon")
# Get nearby diesel stations (paid tiers)
result = client.diesel.get_stations(
lat=37.7749, # San Francisco
lng=-122.4194,
radius=8047 # 5 miles in meters
)
print(f"Regional average: ${result.regional_average.price:.2f}/gallon")
print(f"Found {len(result.stations)} stations")
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
from oilpriceapi.exceptions import (
OilPriceAPIError,
RateLimitError,
DataNotFoundError
)
try:
price = client.prices.get("INVALID_CODE")
except DataNotFoundError as e:
print(f"Commodity not found: {e}")
except RateLimitError as e:
print(f"Rate limited. Resets in {e.seconds_until_reset}s")
except OilPriceAPIError as e:
print(f"API error: {e}")
Available Commodities
Oil & Gas:
BRENT_CRUDE_USD- Brent Crude OilWTI_USD- West Texas IntermediateNATURAL_GAS_USD- Natural GasDIESEL_USD- DieselGASOLINE_USD- GasolineHEATING_OIL_USD- Heating Oil
Coal (8 Endpoints):
CAPP_COAL_USD- Central Appalachian CoalPRB_COAL_USD- Powder River Basin CoalNEWCASTLE_COAL_USD- Newcastle API6
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
- Smart Caching - Reduce API calls automatically
- Rate Limit Handling - Automatic retries with backoff
Links
Next Steps
- API Reference - All available endpoints
- Error Codes - Handle errors gracefully
- Rate Limiting - Understand usage limits