Node.js Oil Price API
Production-Ready SDK with TypeScript, Retries & Zero Dependencies
Official Node.js SDK for real-time oil and commodity prices. Built for production with automatic retries, timeout handling, and full TypeScript support.
npm install oilpriceapi
import { OilPriceAPI } from 'oilpriceapi';
const client = new OilPriceAPI({
apiKey: "your_free_key",
retries: 3,
timeout: 30000
});
const prices = await client.getLatestPrices();
console.log(`WTI: $${prices[0].price}/barrel`);
// Output:
// WTI: $63.53/barrelInstallation & Setup
1. Install via npm
npm install oilpriceapiRequirements: Node.js 14+ | Zero runtime dependencies | Full TypeScript support
3. Make Your First Call
import { OilPriceAPI } from 'oilpriceapi';
// Initialize client with configuration
const client = new OilPriceAPI({
apiKey: "YOUR_API_KEY",
retries: 3, // Automatic retry attempts
timeout: 30000, // 30 second timeout
retryStrategy: 'exponential'
});
// Get latest prices
const latest = await client.getLatestPrices();
// Get historical data
const historical = await client.getHistoricalPrices({
period: 'past_week',
commodity: 'WTI_USD'
});
// Get commodity metadata
const commodities = await client.getCommodities();Code Examples
Express.js API Route
import express from 'express';
import { OilPriceAPI } from 'oilpriceapi';
const app = express();
const client = new OilPriceAPI({
apiKey: process.env.API_KEY
});
app.get('/api/prices', async (req, res) => {
try {
const prices = await client.getLatestPrices();
res.json({ success: true, data: prices });
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
app.listen(3000);TypeScript with Error Handling
import {
OilPriceAPI,
AuthenticationError,
RateLimitError,
NotFoundError
} from 'oilpriceapi';
const client = new OilPriceAPI({
apiKey: process.env.API_KEY!
});
try {
const prices = await client.getLatestPrices({
commodity: 'WTI_USD'
});
console.log(`Price: $${prices[0].price}`);
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid API key');
} else if (error instanceof RateLimitError) {
console.error('Rate limit exceeded');
}
}Historical Price Analysis
const client = new OilPriceAPI({
apiKey: process.env.API_KEY,
timeout: 90000 // Historical queries can be slow
});
// Get past week of WTI prices
const history = await client.getHistoricalPrices({
period: 'past_week',
commodity: 'WTI_USD'
});
// Calculate average price
const avgPrice = history.reduce(
(sum, p) => sum + p.price, 0
) / history.length;
console.log(`Avg WTI: $${avgPrice.toFixed(2)}`);
// Find highest price
const highest = Math.max(...history.map(p => p.price));
console.log(`Peak: $${highest}`);React Hook
import { useState, useEffect } from 'react';
import { OilPriceAPI } from 'oilpriceapi';
function useOilPrices() {
const [prices, setPrices] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const client = new OilPriceAPI({
apiKey: process.env.NEXT_PUBLIC_API_KEY
});
client.getLatestPrices()
.then(setPrices)
.finally(() => setLoading(false));
}, []);
return { prices, loading };
}
function PriceDisplay() {
const { prices, loading } = useOilPrices();
if (loading) return <div>Loading...</div\>;
return (
<div>
\{prices?.map(p => (
<div key=\{p.code\}>
\{p.name\}: $\{p.price\}
</div>
))\}
</div>
);
}Why Use the Official SDK?
Full TypeScript Support
Complete type definitions included. Get autocomplete and type safety out of the box.
Automatic Retries
Configurable retry strategies: exponential, linear, or fixed backoff. Never miss data due to network blips.
Zero Dependencies
No bloat. 9.6 KB package with zero runtime dependencies. Minimal attack surface.
Timeout Handling
Configurable request timeouts (default: 90s). Gracefully handle slow historical queries.
Smart Error Classes
5 custom error types: AuthenticationError, RateLimitError, TimeoutError, NotFoundError, ServerError.
Production Ready
100% test pass rate. v0.3.1 stable. Used in production by companies worldwide.
Configuration Options
import { OilPriceAPI } from 'oilpriceapi';
const client = new OilPriceAPI({
apiKey: process.env.API_KEY, // Required: Your API key
retries: 3, // Optional: Max retry attempts (default: 3)
retryDelay: 1000, // Optional: Initial retry delay in ms (default: 1000)
retryStrategy: 'exponential', // Optional: 'exponential', 'linear', or 'fixed'
timeout: 90000, // Optional: Request timeout in ms (default: 90000)
debug: false // Optional: Enable debug logging (default: false)
});
// Available methods:
await client.getLatestPrices(options); // Get current prices
await client.getHistoricalPrices(options); // Get historical data
await client.getCommodities(); // Get commodity metadata
await client.getCommodityCategories(); // Get categories
await client.getCommodity(code); // Get specific commodity detailsBefore & After
❌ Before (Raw fetch)
const response = await fetch(
'https://api.oilpriceapi.com/v1/prices/latest',
{
headers: {
'Authorization': `Bearer ${API_KEY}`
}
}
);
if (!response.ok) {
throw new Error('Request failed');
}
const data = await response.json();
// Hope nothing goes wrong...
// No retries, no timeout, manual error handling✅ After (SDK)
import { OilPriceAPI } from 'oilpriceapi';
const client = new OilPriceAPI({
apiKey: API_KEY
});
const prices = await client.getLatestPrices();
// Automatic retries ✨
// Timeout handling ✨
// Smart error classes ✨
// TypeScript types ✨Frequently Asked Questions
How do I install the Node.js Oil Price API package?
Install via npm with: npm install oilpriceapi. The package requires Node.js 14+ and has zero runtime dependencies for maximum security.
Does it work with TypeScript?
Yes! Full TypeScript support with complete type definitions included. Get autocomplete, type checking, and inline documentation in your IDE out of the box.
Can I use this in Next.js/React?
Yes! Works perfectly in Next.js API routes, React hooks, and server components. Check our documentation for React integration examples and best practices.
Is it compatible with Express/Fastify?
Yes! The SDK works with any Node.js framework including Express, Fastify, Koa, Hapi, and NestJS. Universal compatibility across all JavaScript backends.
Does it support promises and async/await?
Yes! All methods are promise-based and work seamlessly with async/await. Modern async patterns with automatic error handling and timeout management.
How do I handle API errors in Node.js?
The SDK provides 5 custom error classes: AuthenticationError, RateLimitError, TimeoutError, NotFoundError, and ServerError for precise error handling.
Can I use this in serverless functions?
Yes! Optimized for serverless environments including AWS Lambda, Vercel Functions, Netlify Functions, and Cloudflare Workers. Fast cold starts with zero dependencies.
Where are the Node.js code examples?
Find comprehensive examples on our GitHub repository covering Express, TypeScript, React, error handling, and production patterns.
Ready to Start Building?
Get your free API key and start integrating real-time commodity prices into your Node.js applications today.