Real-world code examples for using the Oil Price API Node.js SDK.
All examples use environment variables for API keys:
export OIL_PRICE_API_KEY="your_api_key_here"Or create a .env file in the examples directory (don't commit this!):
OIL_PRICE_API_KEY=your_api_key_here
Using tsx (recommended for TypeScript):
npx tsx examples/basic.tsOr compile and run:
npm run build
node dist/examples/basic.js1. basic.ts
Simple usage patterns
- Get latest commodity prices
- Filter by specific commodity
- Get historical price data
- Work with different time periods
npx tsx examples/basic.ts2. express.ts
Express.js API server integration
- RESTful API endpoints
- Error handling middleware
- Client connection reuse
- Query parameter handling
npm install express @types/express
npx tsx examples/express.tsThen visit:
http://localhost:3000/api/prices/latesthttp://localhost:3000/api/commodities
Next.js API route example
- API route handler (Pages Router)
- Response caching headers
- Error handling
- TypeScript types
Place in your Next.js project at: pages/api/oil-prices.ts
Comprehensive error handling
- Catch specific error types
- Graceful degradation
- Fallback strategies
- Custom retry configurations
npx tsx examples/error-handling.tsWorking with commodity metadata
- List all commodities
- Explore categories
- Get specific commodity details
- Validate commodity codes
- Build UI dropdowns
npx tsx examples/commodities.ts// lib/oilpriceapi.ts
import { OilPriceAPI } from 'oilpriceapi';
export const oilPriceClient = new OilPriceAPI({
apiKey: process.env.OIL_PRICE_API_KEY!,
retries: 3,
timeout: 10000
});Then import and use across your application:
import { oilPriceClient } from './lib/oilpriceapi';
const prices = await oilPriceClient.getLatestPrices();import { OilPriceAPIError, RateLimitError } from 'oilpriceapi';
try {
const prices = await client.getLatestPrices();
} catch (error) {
if (error instanceof RateLimitError) {
// Handle rate limit specifically
console.log('Rate limited, retry after:', error.statusCode);
} else if (error instanceof OilPriceAPIError) {
// Handle other API errors
console.error('API Error:', error.message);
}
}const cache = new Map();
async function getCachedPrices(commodity: string) {
const cacheKey = `prices:${commodity}`;
if (cache.has(cacheKey)) {
const { data, timestamp } = cache.get(cacheKey);
if (Date.now() - timestamp < 5 * 60 * 1000) { // 5 minutes
return data;
}
}
const prices = await client.getLatestPrices({ commodity });
cache.set(cacheKey, { data: prices, timestamp: Date.now() });
return prices;
}Sign up for a free API key at oilpriceapi.com