# JavaScript/Node.js SDK
Official JavaScript SDK for OilPriceAPI - works in Node.js and browsers.
# ๐ฆ Installation
# npm
npm install @oilpriceapi/sdk
# yarn
yarn add @oilpriceapi/sdk
# pnpm
pnpm add @oilpriceapi/sdk
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# ๐ Quick Start
# ES Modules (Recommended)
import { OilPriceAPI } from '@oilpriceapi/sdk';
const client = new OilPriceAPI({
apiKey: process.env.OILPRICE_API_KEY
});
// Get latest prices
const prices = await client.prices.getLatest();
console.log(`WTI: $${prices.data.WTI.price}`);
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# CommonJS
const { OilPriceAPI } = require('@oilpriceapi/sdk');
const client = new OilPriceAPI({
apiKey: process.env.OILPRICE_API_KEY
});
// With promises
client.prices.getLatest()
.then(prices => {
console.log(`WTI: $${prices.data.WTI.price}`);
})
.catch(error => {
console.error('Error:', error.message);
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# Browser (CDN)
<script src="https://unpkg.com/@oilpriceapi/sdk/dist/browser.js"></script>
<script>
const client = new OilPriceAPI.Client({
apiKey: 'YOUR_API_KEY'
});
client.prices.getLatest()
.then(prices => {
document.getElementById('wti-price').textContent = `$${prices.data.WTI.price}`;
});
</script>
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# ๐ง Configuration
# Client Options
const client = new OilPriceAPI({
apiKey: 'YOUR_API_KEY', // Required
baseURL: 'https://api.oilpriceapi.com', // Optional, default shown
timeout: 30000, // Optional, milliseconds
retries: 3, // Optional, automatic retry on failure
retryDelay: 1000, // Optional, milliseconds between retries
cache: true, // Optional, enable response caching
cacheTime: 300000, // Optional, cache duration in ms (5 min)
headers: { // Optional, additional headers
'X-Custom-Header': 'value'
}
});
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# Environment Variables
The SDK automatically reads from environment variables:
# .env file
OILPRICE_API_KEY=opa_live_a1b2c3d4e5f6
OILPRICE_API_URL=https://api.oilpriceapi.com
OILPRICE_API_TIMEOUT=30000
1
2
3
4
2
3
4
// No need to pass apiKey if env var is set
const client = new OilPriceAPI();
1
2
2
# ๐ API Methods
# Prices
# Get Latest Prices
// Get all commodities
const allPrices = await client.prices.getLatest();
// Get specific commodities
const oilPrices = await client.prices.getLatest({
commodities: ['WTI', 'BRENT']
});
// Get prices in different currency
const eurPrices = await client.prices.getLatest({
currency: 'EUR'
});
// Get specific fields only
const minimalData = await client.prices.getLatest({
commodities: ['WTI'],
fields: ['price', 'timestamp']
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Get Historical Prices
// Past 24 hours
const dailyPrices = await client.prices.getPastDay({
commodities: ['WTI', 'BRENT']
});
// Past week with specific interval
const weeklyPrices = await client.prices.getPastWeek({
commodities: ['NATURAL_GAS'],
interval: '1d' // Daily data points
});
// Past month
const monthlyPrices = await client.prices.getPastMonth();
// Past year
const yearlyPrices = await client.prices.getPastYear({
commodities: ['WTI'],
interval: '1w' // Weekly data points
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Commodities
// Get all available commodities
const commodities = await client.commodities.getAll();
// Get specific commodity details
const wtiDetails = await client.commodities.get('WTI');
// Get commodities by category
const categories = await client.commodities.getCategories();
const crudeoils = await client.commodities.getByCategory('crude_oil');
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# WebSocket Streaming (Reservoir Mastery)
// Connect to real-time price stream
const stream = client.stream.connect({
commodities: ['WTI', 'BRENT', 'NATURAL_GAS'],
onConnect: () => {
console.log('Connected to price stream');
},
onPrice: (update) => {
console.log(`${update.commodity}: $${update.price} (${update.change > 0 ? '+' : ''}${update.change})`);
},
onError: (error) => {
console.error('Stream error:', error);
},
onDisconnect: (reason) => {
console.log('Disconnected:', reason);
}
});
// Disconnect when done
stream.disconnect();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Price Alerts
// Create a price alert
const alert = await client.alerts.create({
commodity: 'WTI',
condition: 'above',
threshold: 80.00,
notification: {
email: true,
webhook: 'https://your-app.com/webhook'
}
});
// List active alerts
const myAlerts = await client.alerts.list();
// Delete an alert
await client.alerts.delete(alert.id);
// Test alert notification
await client.alerts.test(alert.id);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Account & Usage
// Get account info
const account = await client.account.get();
console.log(`Plan: ${account.plan}`);
console.log(`Requests remaining: ${account.requests_remaining}`);
// Get usage statistics
const usage = await client.account.getUsage({
period: 'current_month'
});
// Get API keys
const apiKeys = await client.account.getApiKeys();
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# ๐ฏ TypeScript Support
The SDK includes full TypeScript definitions:
import { OilPriceAPI, Price, Commodity, Alert } from '@oilpriceapi/sdk';
const client = new OilPriceAPI({
apiKey: process.env.OILPRICE_API_KEY!
});
// Type-safe responses
const prices: PriceResponse = await client.prices.getLatest();
const wti: Price = prices.data.WTI;
// Type-safe parameters
interface PriceOptions {
commodities?: string[];
currency?: string;
fields?: string[];
}
const options: PriceOptions = {
commodities: ['WTI', 'BRENT'],
currency: 'EUR'
};
const euroPrices = await client.prices.getLatest(options);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# ๐ก๏ธ Error Handling
The SDK provides detailed error information:
try {
const prices = await client.prices.getLatest();
} catch (error) {
if (error.code === 'RATE_LIMIT_EXCEEDED') {
console.log(`Rate limit hit. Reset at: ${error.resetAt}`);
console.log(`Retry after: ${error.retryAfter} seconds`);
} else if (error.code === 'INVALID_API_KEY') {
console.error('Check your API key');
} else if (error.code === 'NETWORK_ERROR') {
console.error('Network issue:', error.message);
} else {
console.error('Unexpected error:', error);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# Error Types
import {
OilPriceAPIError,
RateLimitError,
AuthenticationError,
ValidationError,
NetworkError
} from '@oilpriceapi/sdk';
// Specific error handling
try {
await client.prices.getLatest();
} catch (error) {
if (error instanceof RateLimitError) {
// Wait and retry
await sleep(error.retryAfter * 1000);
} else if (error instanceof AuthenticationError) {
// Invalid API key
} else if (error instanceof ValidationError) {
// Invalid parameters
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# ๐ก Advanced Usage
# Caching
// Enable caching globally
const client = new OilPriceAPI({
apiKey: 'YOUR_API_KEY',
cache: true,
cacheTime: 300000 // 5 minutes
});
// Or per-request
const prices = await client.prices.getLatest({
cache: false // Skip cache for this request
});
// Clear cache
client.cache.clear();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# Retry Logic
const client = new OilPriceAPI({
apiKey: 'YOUR_API_KEY',
retries: 3,
retryDelay: 1000,
retryCondition: (error) => {
// Retry on network errors and 5xx status codes
return error.code === 'NETWORK_ERROR' ||
(error.status >= 500 && error.status < 600);
}
});
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# Request Interceptors
// Add request logging
client.interceptors.request.use((config) => {
console.log(`API Request: ${config.method} ${config.url}`);
return config;
});
// Add response timing
client.interceptors.response.use((response) => {
console.log(`Response time: ${response.duration}ms`);
return response;
});
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# Batch Requests
// Fetch multiple data types efficiently
const [prices, commodities, alerts] = await Promise.all([
client.prices.getLatest(),
client.commodities.getAll(),
client.alerts.list()
]);
1
2
3
4
5
6
2
3
4
5
6
# ๐ React Integration
# Custom Hook
import { useState, useEffect } from 'react';
import { OilPriceAPI } from '@oilpriceapi/sdk';
const client = new OilPriceAPI();
export function useOilPrices(commodities = ['WTI', 'BRENT']) {
const [prices, setPrices] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let cancelled = false;
async function fetchPrices() {
try {
setLoading(true);
const response = await client.prices.getLatest({ commodities });
if (!cancelled) {
setPrices(response.data);
setError(null);
}
} catch (err) {
if (!cancelled) {
setError(err.message);
setPrices(null);
}
} finally {
if (!cancelled) {
setLoading(false);
}
}
}
fetchPrices();
// Refresh every 5 minutes
const interval = setInterval(fetchPrices, 5 * 60 * 1000);
return () => {
cancelled = true;
clearInterval(interval);
};
}, [commodities.join(',')]);
return { prices, loading, error, refetch: fetchPrices };
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Component Example
import React from 'react';
import { useOilPrices } from './hooks/useOilPrices';
function OilPriceWidget() {
const { prices, loading, error } = useOilPrices(['WTI', 'BRENT']);
if (loading) return <div>Loading prices...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div className="oil-prices">
{Object.entries(prices).map(([commodity, data]) => (
<div key={commodity} className="price-card">
<h3>{commodity}</h3>
<div className="price">${data.price.toFixed(2)}</div>
<div className={`change ${data.change_24h > 0 ? 'positive' : 'negative'}`}>
{data.change_24h > 0 ? '+' : ''}{data.change_percent_24h.toFixed(2)}%
</div>
</div>
))}
</div>
);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# ๐ Next.js Integration
# API Route Handler
// app/api/oil-prices/route.js
import { OilPriceAPI } from '@oilpriceapi/sdk';
import { NextResponse } from 'next/server';
const client = new OilPriceAPI({
apiKey: process.env.OILPRICE_API_KEY
});
export async function GET(request) {
try {
const { searchParams } = new URL(request.url);
const commodities = searchParams.get('commodities')?.split(',');
const prices = await client.prices.getLatest({ commodities });
return NextResponse.json(prices, {
headers: {
'Cache-Control': 'public, s-maxage=300, stale-while-revalidate=600'
}
});
} catch (error) {
return NextResponse.json(
{ error: error.message },
{ status: error.status || 500 }
);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Server Component
// app/components/OilPrices.jsx
import { OilPriceAPI } from '@oilpriceapi/sdk';
const client = new OilPriceAPI({
apiKey: process.env.OILPRICE_API_KEY
});
export default async function OilPrices() {
const prices = await client.prices.getLatest({
commodities: ['WTI', 'BRENT'],
cache: true
});
return (
<div>
{Object.entries(prices.data).map(([commodity, data]) => (
<div key={commodity}>
<h3>{commodity}: ${data.price}</h3>
</div>
))}
</div>
);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# ๐งช Testing
# Mock Client
import { OilPriceAPI, MockClient } from '@oilpriceapi/sdk';
// Use mock client in tests
const client = new MockClient({
prices: {
WTI: { price: 75.50, change_24h: 0.50 },
BRENT: { price: 80.25, change_24h: -0.25 }
}
});
// Test your code
const prices = await client.prices.getLatest();
expect(prices.data.WTI.price).toBe(75.50);
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# Jest Example
// __tests__/oil-prices.test.js
import { OilPriceAPI } from '@oilpriceapi/sdk';
jest.mock('@oilpriceapi/sdk');
describe('Oil Price Service', () => {
it('should fetch latest prices', async () => {
const mockPrices = {
data: {
WTI: { price: 75.50 }
}
};
OilPriceAPI.mockImplementation(() => ({
prices: {
getLatest: jest.fn().mockResolvedValue(mockPrices)
}
}));
const client = new OilPriceAPI();
const result = await client.prices.getLatest();
expect(result.data.WTI.price).toBe(75.50);
});
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# ๐ Examples
Find more examples in our GitHub repository (opens new window):
- Express.js API (opens new window)
- React Dashboard (opens new window)
- Next.js App (opens new window)
- Vue.js Widget (opens new window)
- CLI Tool (opens new window)
- Serverless Function (opens new window)
# ๐ Resources
- API Documentation (opens new window)
- npm Package (opens new window)
- GitHub Repository (opens new window)
- Support
Need help? Join our Discord (opens new window) or open an issue (opens new window)
โ Python SDK