Making Requests
Learn how to make effective API requests to retrieve oil and energy price data.
Base URL
All API requests should be made to:
https://api.oilpriceapi.com/v1/
Request Format
HTTP Methods
OilPriceAPI primarily uses GET
requests for data retrieval:
GET
- Retrieve price data, commodity information, and lists
Required Headers
Every request must include:
Authorization: Token YOUR_API_KEY
Content-Type: application/json
Common Parameters
Commodity Selection
Use the by_code
parameter to specify commodities:
# Single commodity
GET /v1/prices/latest?by_code=WTI_USD
# Multiple commodities (comma-separated)
GET /v1/prices/latest?by_code=WTI_USD,BRENT_CRUDE_USD,NATURAL_GAS_USD
Date Ranges
For historical data, use date parameters:
# Specific date
GET /v1/prices/by_date?date=2025-01-01&by_code=WTI_USD
# Date range
GET /v1/prices/historical?start_date=2025-01-01&end_date=2025-01-10&by_code=WTI_USD
Date format: YYYY-MM-DD
Example Requests
Get Latest Prices
curl "https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD" \
-H "Authorization: Token YOUR_API_KEY"
Get Multiple Commodities
curl "https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD,BRENT_CRUDE_USD,NATURAL_GAS_USD" \
-H "Authorization: Token YOUR_API_KEY"
Get Historical Data
curl "https://api.oilpriceapi.com/v1/prices/historical?start_date=2025-01-01&end_date=2025-01-10&by_code=WTI_USD" \
-H "Authorization: Token YOUR_API_KEY"
Request Libraries
JavaScript (Axios)
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://api.oilpriceapi.com/v1',
headers: {
'Authorization': `Token ${process.env.OILPRICE_API_KEY}`,
'Content-Type': 'application/json'
}
});
// Get latest WTI price
const getLatestWTI = async () => {
try {
const response = await apiClient.get('/prices/latest', {
params: { by_code: 'WTI_USD' }
});
return response.data;
} catch (error) {
console.error('API Error:', error.response?.data || error.message);
}
};
Python (Requests)
import requests
import os
class OilPriceClient:
def __init__(self):
self.base_url = 'https://api.oilpriceapi.com/v1'
self.headers = {
'Authorization': f"Token {os.environ['OILPRICE_API_KEY']}",
'Content-Type': 'application/json'
}
def get_latest_prices(self, commodity_codes):
params = {'by_code': ','.join(commodity_codes)}
response = requests.get(
f'{self.base_url}/prices/latest',
headers=self.headers,
params=params
)
response.raise_for_status()
return response.json()
# Usage
client = OilPriceClient()
data = client.get_latest_prices(['WTI_USD', 'BRENT_CRUDE_USD'])
Ruby (Net::HTTP)
require 'net/http'
require 'json'
require 'uri'
class OilPriceClient
BASE_URL = 'https://api.oilpriceapi.com/v1'
def initialize(api_key)
@api_key = api_key
end
def get_latest_prices(commodity_codes)
uri = URI("#{BASE_URL}/prices/latest")
uri.query = URI.encode_www_form(by_code: commodity_codes.join(','))
request = Net::HTTP::Get.new(uri)
request['Authorization'] = "Token #{@api_key}"
request['Content-Type'] = 'application/json'
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
JSON.parse(response.body)
end
end
# Usage
client = OilPriceClient.new(ENV['OILPRICE_API_KEY'])
data = client.get_latest_prices(['WTI_USD', 'BRENT_CRUDE_USD'])
PHP (cURL)
<?php
class OilPriceClient {
private $baseUrl = 'https://api.oilpriceapi.com/v1';
private $apiKey;
public function __construct($apiKey) {
$this->apiKey = $apiKey;
}
public function getLatestPrices($commodityCodes) {
$url = $this->baseUrl . '/prices/latest?' . http_build_query([
'by_code' => implode(',', $commodityCodes)
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Token ' . $this->apiKey,
'Content-Type: application/json'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception('API request failed with code: ' . $httpCode);
}
return json_decode($response, true);
}
}
// Usage
$client = new OilPriceClient($_ENV['OILPRICE_API_KEY']);
$data = $client->getLatestPrices(['WTI_USD', 'BRENT_CRUDE_USD']);
?>
Pagination
For endpoints returning large datasets, use pagination parameters:
# Get page 2 with 50 results per page
GET /v1/prices/historical?page=2&per_page=50&by_code=WTI_USD
Default pagination:
page
: 1per_page
: 100- Maximum
per_page
: 1000
Filtering and Sorting
Filter by Category
# Get all crude oil commodities
GET /v1/commodities?category=crude_oil
# Get all natural gas commodities
GET /v1/commodities?category=natural_gas
Sort Results
# Sort historical prices by date (ascending)
GET /v1/prices/historical?by_code=WTI_USD&sort=date_asc
# Sort by price (descending)
GET /v1/prices/historical?by_code=WTI_USD&sort=price_desc
Best Practices
1. Use Specific Commodity Codes
Instead of requesting all commodities, specify only what you need:
# Good - Specific request
GET /v1/prices/latest?by_code=WTI_USD,BRENT_CRUDE_USD
# Avoid - Too broad
GET /v1/prices/latest
2. Cache Responses
Prices update every 5 minutes. Cache responses to reduce API calls:
const cache = new Map();
const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
async function getCachedPrice(commodity) {
const cached = cache.get(commodity);
if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
return cached.data;
}
const data = await fetchPriceFromAPI(commodity);
cache.set(commodity, { data, timestamp: Date.now() });
return data;
}
3. Handle Errors Gracefully
Always implement proper error handling:
import time
import requests
from requests.exceptions import RequestException
def get_price_with_retry(commodity_code, max_retries=3):
for attempt in range(max_retries):
try:
response = requests.get(
f'https://api.oilpriceapi.com/v1/prices/latest',
params={'by_code': commodity_code},
headers={'Authorization': f'Token {API_KEY}'},
timeout=10
)
response.raise_for_status()
return response.json()
except RequestException as e:
if attempt == max_retries - 1:
raise
time.sleep(2 ** attempt) # Exponential backoff
4. Monitor Rate Limits
Track your usage to avoid hitting limits:
function checkRateLimit(response) {
const remaining = response.headers['x-ratelimit-remaining'];
const limit = response.headers['x-ratelimit-limit'];
if (remaining < limit * 0.1) {
console.warn(`Low API quota: ${remaining}/${limit} requests remaining`);
}
}
Next Steps
Learn about handling responses and parsing the returned data.