OilPriceAPI Docs
GitHub
GitHub
  • SDKs & Languages

    • SDKs & Language Guides
    • TypeScript Response Types
  • Language Guides

    • Java Oil Price API Integration | OilPriceAPI
    • Go Oil Price API Integration | OilPriceAPI
    • Rust Oil Price API Integration | OilPriceAPI
    • PHP Oil Price API Integration | OilPriceAPI
    • Ruby Oil Price API Integration | OilPriceAPI
    • C# .NET Oil Price API Integration | OilPriceAPI
    • R Language Oil Price API Integration | OilPriceAPI

JavaScript / Node.js Integration Guide

Integrate OilPriceAPI into your JavaScript and Node.js applications for real-time crude oil prices, Brent oil data, natural gas pricing, and energy commodity market information. Build solutions for commodities trading platforms, logistics applications, and fleet management systems.

There are two ways to call the API from JavaScript:

  • The official oilpriceapi npm package (recommended) — typed, with retries and timeouts built in.
  • Raw HTTP with fetch — no dependencies on Node 18+ or in the browser.

For the complete SDK reference (TypeScript types, alerts, framework examples) see the JavaScript SDK Quick Start.

Requirements

  • Node.js 18 or higher (for native fetch), or any modern browser
  • npm for installing the SDK

Installation

Install the official SDK:

npm install oilpriceapi

The raw fetch examples below need no dependencies on Node 18+.

Quick Start

Using the official SDK

import { OilPriceAPI } from "oilpriceapi";

const client = new OilPriceAPI({ apiKey: process.env.OILPRICEAPI_KEY });

// Get the latest WTI price
const [wti] = await client.getLatestPrices({ commodity: "WTI_USD" });
console.log(`WTI: ${wti.formatted}`);

Using fetch (no SDK)

A single-commodity request returns a flat object at data:

const apiKey = process.env.OILPRICE_API_KEY;

const response = await fetch(
  "https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD",
  { headers: { Authorization: `Token ${apiKey}` } },
);

if (!response.ok) {
  throw new Error(`API error: HTTP ${response.status}`);
}

const data = await response.json();
console.log(`WTI: ${data.data.formatted}`); // e.g. "$68.58"
console.log(`Price: ${data.data.price}`); // e.g. 68.58

Complete API Client

class OilPriceAPIError extends Error {}
class AuthenticationError extends OilPriceAPIError {}
class RateLimitError extends OilPriceAPIError {}

class OilPriceClient {
  constructor(apiKey = process.env.OILPRICE_API_KEY, { timeout = 30000 } = {}) {
    if (!apiKey) {
      throw new Error("API key is required");
    }
    this.apiKey = apiKey;
    this.baseUrl = "https://api.oilpriceapi.com/v1";
    this.timeout = timeout;
  }

  async request(endpoint, params = {}) {
    const url = new URL(`${this.baseUrl}${endpoint}`);
    for (const [key, value] of Object.entries(params)) {
      url.searchParams.set(key, value);
    }

    const response = await fetch(url, {
      headers: {
        Authorization: `Token ${this.apiKey}`,
        Accept: "application/json",
      },
      signal: AbortSignal.timeout(this.timeout),
    });

    if (response.status === 401) {
      throw new AuthenticationError("Invalid or missing API key");
    }
    if (response.status === 429) {
      throw new RateLimitError("Rate limit exceeded");
    }
    if (!response.ok) {
      throw new OilPriceAPIError(`API error: HTTP ${response.status}`);
    }

    return response.json();
  }

  // Single commodity -> flat `data` object
  latestPrice(code) {
    return this.request("/prices/latest", { by_code: code });
  }

  // Multiple commodities -> `data.prices` array
  latestPrices(codes) {
    return this.request("/prices/latest", { by_code: codes.join(",") });
  }

  // period: past_day | past_week | past_month | historical
  historicalPrices(code, period = "past_week") {
    return this.request(`/prices/${period}`, { by_code: code });
  }

  commodities() {
    return this.request("/commodities");
  }
}

Usage Examples

Fetch a Single Price

const client = new OilPriceClient();

const { data } = await client.latestPrice("WTI_USD");
console.log(`${data.code}: ${data.formatted} (${data.currency})`);

Fetch Multiple Commodities

A multi-code request returns an array under data.prices. Use find to pick one out:

const client = new OilPriceClient();

const response = await client.latestPrices([
  "WTI_USD",
  "BRENT_CRUDE_USD",
  "NATURAL_GAS_USD",
]);

for (const price of response.data.prices) {
  console.log(`${price.code}: ${price.formatted}`);
}

const wti = response.data.prices.find((p) => p.code === "WTI_USD");
console.log(`WTI only: ${wti.formatted}`);

Historical Price Analysis

Historical endpoints return an array of points under data.prices:

const client = new OilPriceClient();

const history = await client.historicalPrices("WTI_USD", "past_week");
const points = history.data.prices;

const values = points.map((p) => p.price);
const avg = values.reduce((a, b) => a + b, 0) / values.length;

console.log(`Points: ${values.length}`);
console.log(`Average: $${avg.toFixed(2)}`);
console.log(`Range: $${Math.min(...values)} - $${Math.max(...values)}`);

Express.js Integration

import express from "express";

const app = express();
const client = new OilPriceClient(process.env.OILPRICE_API_KEY);

app.get("/api/prices/:code", async (req, res) => {
  try {
    const { data } = await client.latestPrice(req.params.code);
    res.json(data);
  } catch (err) {
    res.status(500).json({ error: "Failed to fetch price" });
  }
});

app.listen(3000);

Next.js API Route

// app/api/prices/route.js
import { NextResponse } from "next/server";

const client = new OilPriceClient(process.env.OILPRICE_API_KEY);

export async function GET() {
  const response = await client.latestPrices(["WTI_USD", "BRENT_CRUDE_USD"]);
  return NextResponse.json(response.data.prices);
}

Error Handling

The API returns different error shapes by status code:

  • 401 — a top-level error object with code: "UNAUTHORIZED".
  • 400 — status: "fail" with details under data.
async function fetchWithRetry(client, code, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await client.latestPrice(code);
    } catch (err) {
      if (err instanceof RateLimitError && attempt < maxRetries) {
        const backoff = 2 ** attempt * 1000;
        console.log(
          `Rate limited, waiting ${backoff}ms ` +
            `(attempt ${attempt}/${maxRetries})`,
        );
        await new Promise((r) => setTimeout(r, backoff));
        continue;
      }
      throw err;
    }
  }
}

// Inspecting the raw error body
const response = await fetch(
  "https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD",
  { headers: { Authorization: "Token bad_key" } },
);

if (response.status === 401) {
  const body = await response.json();
  console.log(body.error.code); // "UNAUTHORIZED"
  console.log(body.error.message);
}

Common Commodity Codes

CodeDescription
WTI_USDWest Texas Intermediate Crude Oil
BRENT_CRUDE_USDBrent Crude Oil
NATURAL_GAS_USDNatural Gas (Henry Hub)
HEATING_OIL_USDHeating Oil No. 2
DIESEL_USDUltra Low Sulfur Diesel

View all 460+ commodity codes

Frequently Asked Questions

Is there an official SDK for JavaScript?

Yes. Install it with npm install oilpriceapi and see the JavaScript SDK Quick Start for the full reference, including TypeScript types, price alerts, and framework examples. The raw fetch examples above are provided for teams that prefer zero dependencies.

How do I authenticate?

Send an Authorization: Token YOUR_API_KEY header on every request. The SDK takes the key via new OilPriceAPI({ apiKey }).

How do I handle rate limiting?

Implement exponential backoff when you receive a 429 response, as shown in the fetchWithRetry helper above. The official SDK retries automatically.

Related Resources

  • JavaScript SDK Quick Start - Full official SDK reference
  • Python Developer Guide - Alternative language guide
  • Ruby Developer Guide - Alternative language guide
  • Go Developer Guide - High-performance alternative
  • Authentication Guide - API key management
  • API Reference - Complete endpoint documentation
  • Rate Limiting - Usage limits and best practices
Last Updated: 7/3/26, 2:48 PM