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 Mistakes
Authentication Header Format
The documented and recommended scheme is Token:
Authorization: Token YOUR_API_KEY
Note:
Tokenis the recommended scheme and the one used throughout these docs.Authorization: Bearer YOUR_API_KEYis also currently accepted if you're coming from an OAuth2 background, but preferTokenfor consistency.
Endpoint Format
WRONG ❌
GET /v1/prices/WTI_USD
CORRECT ✅
GET /v1/prices/latest?by_code=WTI_USD
Note: Commodity codes go in the
by_codequery parameter, not in the URL path.
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, pass a date range to the historical endpoint:
# 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.OILPRICEAPI_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['OILPRICEAPI_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['OILPRICEAPI_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['OILPRICEAPI_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
Read the X-Total and X-Total-Pages response headers to page through large result sets.
Some endpoints also send an RFC 5988 Link header, but it is not sent on every response and is not sent at all by /v1/prices/historical. Page on X-Total-Pages and page=N, which are present on every paginated response.
Filtering Commodities
GET /v1/commodities returns the full catalog. Filter it client-side by the category field on each item — the endpoint does not currently apply category, search, or active query parameters (they are ignored and the full list is returned).
import requests
resp = requests.get(
"https://api.oilpriceapi.com/v1/commodities",
headers={"Authorization": "Token YOUR_API_KEY"},
).json()
crude = [c for c in resp["data"] if c["category"] == "crude_oil"]
Best Practices
1. Always Specify Commodity Codes
List exactly the commodities you need with by_code:
# Good - Specific request
GET /v1/prices/latest?by_code=WTI_USD,BRENT_CRUDE_USD
# Avoid - No by_code returns only a single default commodity (BRENT_CRUDE_USD)
GET /v1/prices/latest
Note: Calling
/v1/prices/latestwithoutby_codedoes not return all commodities - it returns a single default commodity. To get multiple prices, pass a comma-separated list:by_code=WTI_USD,BRENT_CRUDE_USD.
2. Cache Responses
Refresh cadence varies by source and dataset. Cache responses using the returned timestamps and freshness metadata:
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`);
}
}
Troubleshooting
404 Not Found Error
Common Cause: Using commodity code in URL path instead of query parameter
# ❌ Wrong - Returns 404
curl "https://api.oilpriceapi.com/v1/prices/WTI_USD"
# ✅ Correct
curl "https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD"
401 Unauthorized Error
Common Cause: A missing or invalid API key. Make sure the Authorization header is present and your key is correct.
# ❌ Wrong - no Authorization header, returns 401
curl "https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD"
# ✅ Correct
curl "https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD" \
-H "Authorization: Token YOUR_API_KEY"
A 401 response includes a JSON body with error.code set to UNAUTHORIZED and a request_id you can quote when contacting support.
Quick Verification Test
Test your setup with this command (replace YOUR_API_KEY):
curl "https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD" \
-H "Authorization: Token YOUR_API_KEY"
Expected Response:
- Status: 200 OK
- Body contains
"code": "WTI_USD"and current price data
Still having issues? Email support@oilpriceapi.com with your request_id from the error response.
Next Steps
Learn about handling responses and parsing the returned data.