Python Oil Price API
Integrate real-time oil and commodity prices into your Python applications. Complete with async support, error handling, and production-ready examples.
Quick Start
1. Install Dependencies
pip install requests
pip install aiohttp # for async support
pip install flask # for web apps
2. Get Your API Key
- Sign up for free account
- Get instant API access
- 30,000 free requests/month
Basic Integration
import requests
import json
from datetime import datetime
import asyncio
import aiohttp
class OilPriceAPI:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://api.oilpriceapi.com"
self.headers = {
"Authorization": f"Token {api_key}",
"Content-Type": "application/json"
}
def get_brent_price(self):
"""Get current Brent crude oil price"""
response = requests.get(
f"{self.base_url}/prices",
headers=self.headers
)
if response.status_code == 200:
return response.json()
else:
response.raise_for_status()
def get_commodity_health(self):
"""Get all commodity prices from health endpoint"""
response = requests.get(
f"{self.base_url}/health",
headers=self.headers
)
if response.status_code == 200:
return response.json()
else:
response.raise_for_status()
def get_wti_price(self):
"""Get WTI crude oil price from health endpoint"""
health_data = self.get_commodity_health()
wti_data = health_data.get('metrics', {}).get('commodity_health', {}).get('WTI_USD')
if wti_data:
return {
'price': wti_data['latest_price'] / 100, # Convert from cents
'timestamp': wti_data['last_update'],
'currency': 'USD',
'unit': 'barrel'
}
return None
# Usage Examples
if __name__ == "__main__":
# Initialize API client
api = OilPriceAPI("YOUR_API_KEY_HERE")
try:
# Get Brent crude price
brent_data = api.get_brent_price()
print(f"Brent Crude: $" + str(brent_data['data']['price']) + "/barrel")
# Get WTI price
wti_data = api.get_wti_price()
if wti_data:
print(f"WTI Crude: $\{wti_data['price']:.2f\}/barrel")
# Get all commodity data
health_data = api.get_commodity_health()
commodities = health_data.get('metrics', {}).get('commodity_health', {})
for commodity, data in commodities.items():
if 'latest_price' in data:
price = data['latest_price'] / 100
print(f"{commodity}: $" + f"{price:.2f}")
except requests.exceptions.RequestException as e:
print(f"API Error: {e}")
Async/Await Support
For high-performance applications, use our async implementation:
import asyncio
import aiohttp
import json
class AsyncOilPriceAPI:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://api.oilpriceapi.com"
self.headers = {
"Authorization": f"Token {api_key}",
"Content-Type": "application/json"
}
async def _make_request(self, endpoint):
"""Make async HTTP request"""
async with aiohttp.ClientSession() as session:
async with session.get(
f"{self.base_url}/{endpoint}",
headers=self.headers
) as response:
if response.status == 200:
return await response.json()
else:
response.raise_for_status()
async def get_brent_price(self):
"""Async get Brent crude price"""
return await self._make_request("prices")
async def get_commodity_health(self):
"""Async get all commodity prices"""
return await self._make_request("health")
async def get_multiple_commodities(self):
"""Get multiple commodity prices concurrently"""
tasks = [
self.get_brent_price(),
self.get_commodity_health()
]
brent_data, health_data = await asyncio.gather(*tasks)
# Extract WTI from health data
wti_raw = health_data.get('metrics', {}).get('commodity_health', {}).get('WTI_USD', {})
wti_price = wti_raw.get('latest_price', 0) / 100 if wti_raw else 0
return {
'brent': brent_data['data']['price'],
'wti': wti_price,
'timestamp': brent_data['data']['timestamp']
}
# Async usage example
async def main():
api = AsyncOilPriceAPI("YOUR_API_KEY_HERE")
try:
prices = await api.get_multiple_commodities()
print(f"Brent: $" + str(prices['brent']))
print(f"WTI: $" + f"{prices['wti']:.2f}")
print(f"Updated: {prices['timestamp']}")
except Exception as e:
print(f"Error: {e}")
# Run async code
if __name__ == "__main__":
asyncio.run(main())
Flask Web App Integration
Build a web API with caching and background updates:
from flask import Flask, jsonify
import requests
import os
from datetime import datetime, timedelta
import threading
import time
app = Flask(__name__)
class PriceCache:
def __init__(self):
self.cache = {}
self.last_update = {}
self.cache_duration = 300 # 5 minutes
self.api_key = os.getenv('OIL_PRICE_API_KEY')
self.headers = {
"Authorization": f"Token {self.api_key}",
"Content-Type": "application/json"
}
# Start background update thread
self.start_background_updates()
def fetch_prices(self):
"""Fetch fresh price data from API"""
try:
# Get Brent from prices endpoint
brent_response = requests.get(
"https://api.oilpriceapi.com/prices",
headers=self.headers,
timeout=10
)
# Get other commodities from health endpoint
health_response = requests.get(
"https://api.oilpriceapi.com/health",
headers=self.headers,
timeout=10
)
prices = {}
if brent_response.status_code == 200:
brent_data = brent_response.json()
prices['brent'] = {
'price': brent_data['data']['price'],
'timestamp': brent_data['data']['timestamp']
}
if health_response.status_code == 200:
health_data = health_response.json()
commodities = health_data.get('metrics', {}).get('commodity_health', {})
# Extract WTI
if 'WTI_USD' in commodities:
wti_data = commodities['WTI_USD']
prices['wti'] = {
'price': wti_data['latest_price'] / 100,
'timestamp': wti_data['last_update']
}
# Extract Natural Gas
if 'NATURAL_GAS_USD' in commodities:
gas_data = commodities['NATURAL_GAS_USD']
prices['natural_gas'] = {
'price': gas_data['latest_price'] / 100,
'timestamp': gas_data['last_update']
}
self.cache = prices
self.last_update['timestamp'] = datetime.now()
return prices
except Exception as e:
print(f"Error fetching prices: {e}")
return self.cache # Return cached data on error
def get_prices(self):
"""Get prices (from cache if recent, otherwise fetch fresh)"""
now = datetime.now()
if (not self.last_update.get('timestamp') or
now - self.last_update['timestamp'] > timedelta(seconds=self.cache_duration)):
return self.fetch_prices()
return self.cache
def start_background_updates(self):
"""Start background thread to update prices periodically"""
def update_loop():
while True:
self.fetch_prices()
time.sleep(self.cache_duration)
thread = threading.Thread(target=update_loop, daemon=True)
thread.start()
# Initialize price cache
price_cache = PriceCache()
@app.route('/api/prices')
def get_all_prices():
"""API endpoint to get all cached prices"""
prices = price_cache.get_prices()
return jsonify({
'status': 'success',
'data': prices,
'cached_at': price_cache.last_update.get('timestamp', datetime.now()).isoformat()
})
@app.route('/api/prices/<commodity>')
def get_commodity_price(commodity):
"""API endpoint to get specific commodity price"""
prices = price_cache.get_prices()
if commodity in prices:
return jsonify({
'status': 'success',
'commodity': commodity,
'data': prices[commodity]
})
else:
return jsonify({
'status': 'error',
'message': f'Commodity {commodity} not found'
}), 404
@app.route('/health')
def health_check():
"""Health check endpoint"""
return jsonify({
'status': 'healthy',
'cache_age': (datetime.now() - price_cache.last_update.get('timestamp', datetime.now())).seconds,
'available_commodities': list(price_cache.cache.keys())
})
if __name__ == '__main__':
app.run(debug=True, port=5000)
Available Commodities
Brent Crude Oil
North Sea Brent crude oil, the global benchmark for oil pricing representing ~60% of internationally traded crude oil.
WTI Crude Oil
West Texas Intermediate crude oil, the primary benchmark for North American oil markets and NYMEX futures.
Dubai Crude Oil
Dubai crude oil benchmark for Middle Eastern crude oil pricing and Asian markets.
Natural Gas
NYMEX Henry Hub natural gas futures, the primary pricing benchmark for North American natural gas markets.
Natural Gas (UK)
UK natural gas pricing in British pence per therm.
Dutch TTF Gas
Dutch Title Transfer Facility (TTF) natural gas futures, the European gas pricing benchmark.
Gasoline RBOB
Reformulated Blendstock for Oxygenate Blending (RBOB) gasoline futures.
Heating Oil
No. 2 heating oil futures, a key refined petroleum product for heating and industrial use.
Coal
Coal futures pricing for thermal coal used in power generation.
Gold
Gold futures pricing, a key precious metal and safe-haven asset.
EUR/USD
Euro to US Dollar exchange rate, the most traded currency pair globally.
GBP/USD
British Pound to US Dollar exchange rate, also known as "Cable".
Best Practices
Error Handling
- Always use try/except blocks
- Implement retry logic with exponential backoff
- Log API errors for debugging
Performance
- Cache responses for 5+ minutes
- Use async for multiple requests
- Set appropriate request timeouts
Ready to Start Building?
Get your free API key and start integrating real-time commodity prices into your Python applications today.