Oil Price API Documentation - Quick Start in 5 Minutes | REST API
GitHub
GitHub
  • Guides

    • Authentication
    • Security & Compliance
    • API Versioning
    • Coal Price Data - Complete Guide
    • Testing & Development
    • Error Codes Reference
    • Webhook Signature Verification
    • Production Deployment Checklist
    • Service Level Agreement (SLA)
    • Rate Limiting & Response Headers
    • Data Quality and Validation
    • Troubleshooting Guide
    • Incident Response Guide
    • Video Tutorials | OilPriceAPI

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 Token prefix:

# 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'}
)

Optional Telemetry Headers

In addition to authentication, you can include optional headers to help us understand API usage and unlock a 10% bonus to your monthly request limit.

Available Headers

HeaderRequiredDescriptionBonus
X-App-URLNoYour application's URL (e.g., https://myapp.com)+10%
X-App-NameNoYour application's name-
X-SDK-NameAutoSDK identifier (set automatically by official SDKs)-
X-SDK-VersionAutoSDK version (set automatically by official SDKs)-

10% Request Limit Bonus

Share where you're using our API by adding the X-App-URL header, and get a 10% bonus to your monthly request limit. For example:

  • Starter plan: 50,000 → 55,000 requests/month
  • Professional plan: 100,000 → 110,000 requests/month
  • Business plan: 200,000 → 220,000 requests/month

Example with Telemetry Headers

# cURL with optional headers
curl "https://api.oilpriceapi.com/v1/prices/latest" \
  -H "Authorization: Token opa_live_a1b2c3d4e5f6" \
  -H "X-App-URL: https://myapp.com" \
  -H "X-App-Name: MyFuelTracker"
// JavaScript with optional headers
const response = await fetch('https://api.oilpriceapi.com/v1/prices/latest', {
  headers: {
    'Authorization': 'Token opa_live_a1b2c3d4e5f6',
    'X-App-URL': 'https://myapp.com',
    'X-App-Name': 'MyFuelTracker'
  }
});
# Python with optional headers
import requests
response = requests.get(
    'https://api.oilpriceapi.com/v1/prices/latest',
    headers={
        'Authorization': 'Token opa_live_a1b2c3d4e5f6',
        'X-App-URL': 'https://myapp.com',
        'X-App-Name': 'MyFuelTracker'
    }
)

Using Official SDKs

Our official SDKs automatically send telemetry headers and make it easy to claim your bonus:

Node.js SDK:

const client = new OilPriceAPI({
  apiKey: 'opa_live_xxx',
  appUrl: 'https://myapp.com',     // +10% bonus!
  appName: 'MyFuelTracker'
});

Python SDK:

from oilpriceapi import OilPriceAPI

client = OilPriceAPI(
    api_key='opa_live_xxx',
    app_url='https://myapp.com',   # +10% bonus!
    app_name='MyFuelTracker'
)

You can also set your website URL in Dashboard Settings to apply the bonus to all requests.

API Key Types

TypeFormatUsageRate Limits
Liveopa_live_*ProductionPer your plan
Testopa_test_*Development100/day

Getting Your API Key

  1. Sign up at oilpriceapi.com/signup
  2. Go to Dashboard → API Keys
  3. Create new key with descriptive name
  4. 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

StatusErrorSolution
401Invalid API keyVerify key is correct and active
401Missing headerCheck Authorization header format
403Access forbiddenVerify IP/domain restrictions
429Rate limit exceededImplement backoff or upgrade plan

Testing

Verify your setup:

curl -i "https://api.oilpriceapi.com/v1/account" \
  -H "Authorization: Token YOUR_API_KEY"

Expected response:

{
  "status": "success",
  "data": {
    "email": "[email protected]",
    "plan": "professional",
    "requests_remaining": 95420
  }
}

Multi-Environment Setup

const config = {
  development: {
    apiKey: process.env.OILPRICE_API_KEY_DEV || 'opa_test_xxx'
  },
  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)})
Last Updated: 12/27/25, 7:06 PM
Next
Security & Compliance