JavaScript/Node.js SDK
Get started with the official OilPriceAPI Node.js SDK in under 2 minutes.
Installation
npm install oilpriceapi
Requirements: Node.js 18+ (uses native fetch)
Quick Start
import { OilPriceAPI } from 'oilpriceapi';
// Initialize the client
const client = new OilPriceAPI({
apiKey: 'your_api_key_here'
});
// Get latest prices
const prices = await client.getLatestPrices();
console.log(prices);
TypeScript Support
Full TypeScript support with detailed type definitions:
import { OilPriceAPI, Price, RateLimitError } from 'oilpriceapi';
const client = new OilPriceAPI({ apiKey: process.env.OILPRICEAPI_KEY! });
const prices: Price[] = await client.getLatestPrices();
Common Operations
Get Specific Commodity
// Get only WTI crude oil price
const wti = await client.getLatestPrices({ commodity: 'WTI_USD' });
console.log(`WTI: ${wti[0].formatted} per barrel`);
// Get only Brent crude price
const brent = await client.getLatestPrices({ commodity: 'BRENT_CRUDE_USD' });
console.log(`Brent: ${brent[0].formatted} per barrel`);
Historical Data
// Past week
const weekPrices = await client.getHistoricalPrices({
period: 'past_week',
commodity: 'WTI_USD'
});
// Custom date range with daily aggregation (fast!)
const yearlyPrices = await client.getHistoricalPrices({
startDate: '2024-01-01',
endDate: '2024-12-31',
commodity: 'BRENT_CRUDE_USD',
interval: 'daily' // Returns 365 points instead of 600k+
});
Diesel Prices
// Get state average (free tier)
const caPrice = await client.diesel.getPrice('CA');
console.log(`California diesel: $${caPrice.price}/gallon`);
// Get nearby stations (paid tiers)
const result = await client.diesel.getStations({
lat: 37.7749, // San Francisco
lng: -122.4194,
radius: 8047 // 5 miles in meters
});
console.log(`Found ${result.stations.length} stations`);
console.log(`Regional average: $${result.regional_average.price}/gallon`);
// Find cheapest station
const cheapest = result.stations.reduce((min, s) =>
s.diesel_price < min.diesel_price ? s : min
);
console.log(`Cheapest: ${cheapest.name} at ${cheapest.formatted_price}`);
Price Alerts
// Create an alert when Brent exceeds $85
const alert = await client.alerts.create({
name: 'Brent High Alert',
commodity_code: 'BRENT_CRUDE_USD',
condition_operator: 'greater_than',
condition_value: 85.00,
webhook_url: 'https://your-app.com/webhooks/price-alert',
enabled: true,
cooldown_minutes: 60
});
console.log(`Alert created: ${alert.name} (ID: ${alert.id})`);
// List all alerts
const alerts = await client.alerts.list();
alerts.forEach(alert => {
console.log(`${alert.name}: ${alert.trigger_count} triggers`);
});
// Update an alert
await client.alerts.update(alertId, { enabled: false });
// Delete an alert
await client.alerts.delete(alertId);
Advanced Configuration
const client = new OilPriceAPI({
apiKey: 'your_key',
// Retry configuration
retries: 3, // Max retry attempts (default: 3)
retryDelay: 1000, // Initial delay in ms (default: 1000)
retryStrategy: 'exponential', // 'exponential', 'linear', or 'fixed'
// Timeout configuration
timeout: 30000, // Request timeout in ms (default: 30000)
// Debug mode
debug: true // Enable debug logging (default: false)
});
Error Handling
import {
OilPriceAPI,
AuthenticationError,
RateLimitError,
NotFoundError,
TimeoutError,
ServerError
} from 'oilpriceapi';
try {
const prices = await client.getLatestPrices();
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid API key:', error.message);
} else if (error instanceof RateLimitError) {
console.error('Rate limit exceeded. Retry after:', error.retryAfter, 'seconds');
} else if (error instanceof TimeoutError) {
console.error('Request timed out:', error.message);
} else if (error instanceof NotFoundError) {
console.error('Commodity not found:', error.message);
} else if (error instanceof ServerError) {
console.error('Server error:', error.statusCode, error.message);
}
}
Framework Examples
Express.js
import express from 'express';
import { OilPriceAPI } from 'oilpriceapi';
const app = express();
const client = new OilPriceAPI({ apiKey: process.env.OILPRICEAPI_KEY! });
app.get('/api/prices', async (req, res) => {
try {
const prices = await client.getLatestPrices();
res.json(prices);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch prices' });
}
});
Next.js API Route
// app/api/prices/route.ts
import { NextResponse } from 'next/server';
import { OilPriceAPI } from 'oilpriceapi';
const client = new OilPriceAPI({ apiKey: process.env.OILPRICEAPI_KEY! });
export async function GET() {
const prices = await client.getLatestPrices();
return NextResponse.json(prices);
}
SDK Features
- Zero Dependencies - Uses native fetch (Node 18+)
- Type-Safe - Full TypeScript support with detailed types
- Automatic Retries - Exponential backoff on failures
- Request Timeouts - Configurable timeout handling
- Debug Mode - Built-in logging for troubleshooting
- Diesel Prices - State averages + station-level pricing
- Price Alerts - Webhook notifications when prices hit thresholds
Alert Operators
greater_than- Price exceeds thresholdless_than- Price falls below thresholdequals- Price matches exactlygreater_than_or_equal- Price meets or exceedsless_than_or_equal- Price at or below
Webhook Payload
When an alert triggers:
{
"event": "price_alert.triggered",
"alert_id": "550e8400-e29b-41d4-a716-446655440000",
"alert_name": "Brent High Alert",
"commodity_code": "BRENT_CRUDE_USD",
"condition_operator": "greater_than",
"condition_value": 85.00,
"current_price": 86.50,
"triggered_at": "2025-12-15T14:30:00Z"
}
Links
Next Steps
- API Reference - All available endpoints
- Error Codes - Handle errors gracefully
- Rate Limiting - Understand usage limits