Authentication
Secure API access using Token authentication with your API key.
Quick Start
All requests require your API key in the Authorization header:
curl "https://api.oilpriceapi.com/v1/prices/latest" \
-H "Authorization: Token YOUR_API_KEY"
Authentication Format
Include your API key in the Authorization header with the Token prefix. The Bearer scheme (Authorization: Bearer YOUR_API_KEY) is also accepted, but Token is the documented and recommended form:
# cURL
curl "https://api.oilpriceapi.com/v1/prices/latest" \
-H "Authorization: Token opa_live_a1b2c3d4e5f6"
# JavaScript
const response = await fetch('https://api.oilpriceapi.com/v1/prices/latest', {
headers: { 'Authorization': 'Token opa_live_a1b2c3d4e5f6' }
});
# Python
import requests
response = requests.get(
'https://api.oilpriceapi.com/v1/prices/latest',
headers={'Authorization': 'Token opa_live_a1b2c3d4e5f6'}
)
Getting Your API Key
- Sign up at oilpriceapi.com/signup
- Go to Dashboard → API Keys
- Create new key with descriptive name
- Copy immediately (shown only once)
Environment Variables
Never hardcode API keys. Use environment variables:
# .env file
OILPRICE_API_KEY=opa_live_a1b2c3d4e5f6
// Node.js
const response = await fetch("https://api.oilpriceapi.com/v1/prices/latest", {
headers: { Authorization: `Token ${process.env.OILPRICE_API_KEY}` },
});
# Python
import os
api_key = os.environ.get('OILPRICE_API_KEY')
headers = {'Authorization': f'Token {api_key}'}
Security Best Practices
Never Expose Keys Client-Side
❌ Bad:
// NEVER do this in browser JavaScript
const apiKey = "opa_live_a1b2c3d4e5f6"; // Exposed to users
✅ Good:
// Create server endpoint instead
app.get("/api/prices", async (req, res) => {
const response = await fetch("https://api.oilpriceapi.com/v1/prices/latest", {
headers: { Authorization: `Token ${process.env.OILPRICE_API_KEY}` },
});
res.json(await response.json());
});
Key Rotation
Rotate API keys regularly:
class APIKeyManager {
constructor() {
this.primaryKey = process.env.OILPRICE_API_KEY_PRIMARY;
this.secondaryKey = process.env.OILPRICE_API_KEY_SECONDARY;
this.useSecondary = false;
}
getCurrentKey() {
return this.useSecondary ? this.secondaryKey : this.primaryKey;
}
}
Monitor Usage
Track API usage for anomalies:
import logging
def log_request(endpoint, api_key_suffix, requests_count, threshold=1000):
if requests_count > threshold:
logging.warning(f"High usage: {requests_count} requests for key ...{api_key_suffix[-4:]}")
Error Handling
Handle authentication failures:
async function makeRequest(endpoint) {
const response = await fetch(`https://api.oilpriceapi.com${endpoint}`, {
headers: { Authorization: `Token ${process.env.OILPRICE_API_KEY}` },
});
if (response.status === 401) {
throw new Error("Invalid API key");
}
if (response.status === 403) {
throw new Error("Access forbidden - check permissions");
}
return response.json();
}
Common Issues
| Status | Error | Solution |
|---|---|---|
| 401 | Invalid API key | Verify key is correct and active |
| 401 | Missing header | Check Authorization header format |
| 403 | Access forbidden | Verify IP/domain restrictions |
| 429 | Rate limit exceeded | Implement backoff or upgrade plan |
Testing
Verify your setup:
curl -i "https://api.oilpriceapi.com/v1/account" \
-H "Authorization: Token YOUR_API_KEY"
Expected response:
{
"account": {
"email": "user@example.com",
"tier": "developer",
"request_limit": 10000,
"usage_this_month": 67,
"trial_active": false,
"trial_ends_at": null
},
"api_keys": [
{
"id": "…",
"name": "…",
"token_hint": "19305b9d",
"active": true,
"created_at": "…",
"revoked_at": null
}
],
"docs": "https://docs.oilpriceapi.com"
}
Account details live under the top-level account object (tier, request_limit, usage_this_month, trial_active, trial_ends_at), and your keys are listed under api_keys.
Multi-Environment Setup
// There is no separate test/sandbox key type — every key is a live key.
// Use a second, separately-named key (ideally on a free-tier account) for
// development so you can rotate it without touching production.
const config = {
development: {
apiKey: process.env.OILPRICE_API_KEY_DEV,
},
production: {
apiKey: process.env.OILPRICE_API_KEY_PROD,
},
};
const env = process.env.NODE_ENV || "development";
const apiKey = config[env].apiKey;
Client Helper Examples
JavaScript Client
class OilPriceAPIClient {
constructor(apiKey = process.env.OILPRICE_API_KEY) {
this.apiKey = apiKey;
this.baseUrl = "https://api.oilpriceapi.com/v1";
}
async request(endpoint, params = {}) {
const url = new URL(`${this.baseUrl}${endpoint}`);
Object.entries(params).forEach(([key, value]) =>
url.searchParams.append(key, value),
);
const response = await fetch(url, {
headers: { Authorization: `Token ${this.apiKey}` },
});
if (!response.ok) throw new Error(`API error: ${response.status}`);
return response.json();
}
async getLatestPrices(commodities) {
return this.request("/prices/latest", { by_code: commodities.join(",") });
}
}
Python Client
import os
import requests
class OilPriceAPIClient:
def __init__(self, api_key=None):
self.api_key = api_key or os.environ.get('OILPRICE_API_KEY')
self.base_url = 'https://api.oilpriceapi.com/v1'
self.session = requests.Session()
self.session.headers.update({'Authorization': f'Token {self.api_key}'})
def request(self, endpoint, params=None):
response = self.session.get(f'{self.base_url}{endpoint}', params=params)
response.raise_for_status()
return response.json()
def get_latest_prices(self, commodities):
return self.request('/prices/latest', {'by_code': ','.join(commodities)})