OilPriceAPI Docs
Quick Start
API Reference
  • SDKs and languages
  • Tutorials
  • Articles
  • Documentation directory
  • Quick reference
  • API explorer
  • FAQ
  • Changelog
  • Status
  • Dashboard
GitHub
Quick Start
API Reference
  • SDKs and languages
  • Tutorials
  • Articles
  • Documentation directory
  • Quick reference
  • API explorer
  • FAQ
  • Changelog
  • Status
  • Dashboard
GitHub

Quick Start

Get your first price from OilPriceAPI in under 2 minutes.

Overview

This guide will help you:

  1. Try the no-key demo endpoint
  2. Get your API key
  3. Make your first authenticated API request
  4. Understand the response format
  5. Explore next steps

Step 0: Try the Demo Endpoint

Start with the live demo endpoint. It requires no API key and returns the same data.prices array container used by multi-code latest-price responses. Individual demo records use updated_at; authenticated records use created_at and may include additional freshness fields. Read the current demo limit from data.meta.rate_limit. This illustrative response is not a live quote:

curl -X GET "https://api.oilpriceapi.com/v1/demo/prices"

Example response:

{
  "status": "success",
  "data": {
    "prices": [
      {
        "code": "WTI_USD",
        "name": "WTI Crude Oil",
        "price": 73.64,
        "currency": "USD",
        "updated_at": "2026-07-08T18:21:13Z",
        "change_24h": 4.54,
        "source": "OilPriceAPI"
      }
    ],
    "meta": {
      "demo_mode": true,
      "rate_limit": "25 requests per day, per IP",
      "note": "This is the free demo API."
    }
  }
}

Step 1: Get Your API Key

Sign Up

  1. Visit oilpriceapi.com/signup
  2. Create your account (free tier available)
  3. Confirm your email address. Your key works for its first 100 requests before you confirm, so you can make your first call straight away.

The Free plan includes 50 requests per day. New accounts start with a 7-day free trial of 10,000 requests; paid plans carry quotas from 10,000 / month (Developer) to 1,000,000 / month (Scale).

Copy Your API Key

Your first API key is created automatically when you sign up and shown on the page that follows. You don't need to create one.

To copy it again later:

  1. Log into your dashboard
  2. Open API Keys
  3. Use the eye icon to show the key, or the copy icon to copy it
**Tip**: For separate development and production keys, use **Create New Key** on the same page, then store each key in your environment or secret manager.
Keep your API key in your server environment.

Set OILPRICEAPI_KEY in your terminal or secret manager. Run authenticated examples on your server. Use the keyless demo for browser experiments.

API key setup and security

Step 2: Make Your First Request

Let's fetch the latest oil prices:

cURL
curl "https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD,BRENT_CRUDE_USD" \
  -H "Authorization: Token YOUR_API_KEY"
JavaScript
const response = await fetch(
  "https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD,BRENT_CRUDE_USD",
  {
    headers: {
      Authorization: "Token YOUR_API_KEY",
    },
  },
);

const data = await response.json();
// data.data.prices is an array - find each commodity by its code
const wti = data.data.prices.find((p) => p.code === "WTI_USD");
const brent = data.data.prices.find((p) => p.code === "BRENT_CRUDE_USD");
console.log(`WTI: $${wti.price}`);
console.log(`Brent: $${brent.price}`);
Python
import requests

response = requests.get(
    'https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD,BRENT_CRUDE_USD',
    headers={'Authorization': 'Token YOUR_API_KEY'}
)

data = response.json()
# data['data']['prices'] is a list - build a dict keyed by code
prices = {p['code']: p for p in data['data']['prices']}
print(f"WTI: ${prices['WTI_USD']['price']}")
print(f"Brent: ${prices['BRENT_CRUDE_USD']['price']}")
Node.js
const https = require("https");

const options = {
  hostname: "api.oilpriceapi.com",
  path: "/v1/prices/latest?by_code=WTI_USD,BRENT_CRUDE_USD",
  headers: {
    Authorization: "Token YOUR_API_KEY",
  },
};

https.get(options, (res) => {
  let data = "";

  res.on("data", (chunk) => {
    data += chunk;
  });

  res.on("end", () => {
    const parsed = JSON.parse(data);
    const wti = parsed.data.prices.find((p) => p.code === "WTI_USD");
    console.log(`WTI: $${wti.price}`);
  });
});

Step 3: Understanding the Response

Here's what you'll receive when requesting multiple commodities:

{
  "status": "success",
  "data": {
    "prices": [
      {
        "price": 68.58,
        "formatted": "$68.58",
        "currency": "USD",
        "code": "WTI_USD",
        "created_at": "2026-07-03T13:43:01.099Z",
        "type": "spot_price",
        "source": "market_reporting"
      },
      {
        "price": 71.98,
        "formatted": "$71.98",
        "currency": "USD",
        "code": "BRENT_CRUDE_USD",
        "created_at": "2026-07-03T13:43:01.099Z",
        "type": "spot_price",
        "source": "market_reporting"
      }
    ],
    "metadata": {
      "request_id": "6390b34903a8d3f0",
      "timestamp": "2026-07-03T13:47:37Z",
      "version": "v1"
    }
  }
}

The data.prices field is an array, so find each commodity by its code rather than indexing by name.

Key Fields Explained

FieldDescriptionExample
priceCurrent spot price74.52
formattedPrice with currency symbol$74.52
currencyPrice currency codeUSD
codeCommodity identifierWTI_USD
created_atPrice timestamp (ISO 8601)2025-12-29T15:30:00.000Z
typePrice typespot_price
sourceData source identifiermarket_reporting

Step 4: Common Use Cases

Get Specific Commodities

# Only get WTI and Natural Gas prices
curl "https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD,NATURAL_GAS_USD" \
  -H "Authorization: Token YOUR_API_KEY"

Get Multiple Commodity Prices

# Get WTI and Brent prices together
curl "https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD,BRENT_CRUDE_USD" \
  -H "Authorization: Token YOUR_API_KEY"

Get Historical Data

# Get past 24 hours of WTI data
curl "https://api.oilpriceapi.com/v1/prices/past_day?by_code=WTI_USD" \
  -H "Authorization: Token YOUR_API_KEY"

Step 5: Best Practices

1. Store API Keys Securely

Never hardcode API keys:

// ❌ Bad
const apiKey = "YOUR_API_KEY";

// ✅ Good
const apiKey = process.env.OILPRICEAPI_KEY;

2. Handle Errors Gracefully

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

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

  const data = await response.json();
  return data;
} catch (error) {
  console.error("Failed to fetch prices:", error);
  // Implement fallback logic
}

3. Implement Caching

Cache responses according to your application's tolerance and the returned freshness metadata:

import time
from functools import lru_cache

@lru_cache(maxsize=1)
def get_cached_prices(cache_key):
    response = requests.get(
        'https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD,BRENT_CRUDE_USD',
        headers={'Authorization': f'Token {API_KEY}'}
    )
    return response.json()

# Generate new cache key every 5 minutes
cache_key = int(time.time() // 300)
prices = get_cached_prices(cache_key)

Step 6: Direct API Integration

The API is simple to integrate directly into your application without any additional libraries:

JavaScript/Node.js
// Using fetch (Node.js 18+ or browser)
const API_KEY = process.env.OILPRICEAPI_KEY;
const BASE_URL = "https://api.oilpriceapi.com/v1";

async function getLatestPrices(commodities) {
  const response = await fetch(
    `${BASE_URL}/prices/latest?by_code=${commodities.join(",")}`,
    {
      headers: {
        Authorization: `Token ${API_KEY}`,
      },
    },
  );

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

  return response.json();
}

// Usage
const prices = await getLatestPrices(["WTI_USD", "BRENT_CRUDE_USD"]);
const wti = prices.data.prices.find((p) => p.code === "WTI_USD");
console.log(wti.price);
Python
import requests
import os

API_KEY = os.environ['OILPRICEAPI_KEY']
BASE_URL = 'https://api.oilpriceapi.com/v1'

def get_latest_prices(commodities):
    response = requests.get(
        f"{BASE_URL}/prices/latest",
        params={'by_code': ','.join(commodities)},
        headers={'Authorization': f'Token {API_KEY}'}
    )
    response.raise_for_status()
    return response.json()

# Usage
prices = get_latest_prices(['WTI_USD', 'BRENT_CRUDE_USD'])
by_code = {p['code']: p for p in prices['data']['prices']}
print(f"WTI: ${by_code['WTI_USD']['price']}")
Ruby
require 'net/http'
require 'json'

API_KEY = ENV['OILPRICEAPI_KEY']
BASE_URL = 'https://api.oilpriceapi.com/v1'

def get_latest_prices(commodities)
  uri = URI("#{BASE_URL}/prices/latest?by_code=#{commodities.join(',')}")

  request = Net::HTTP::Get.new(uri)
  request['Authorization'] = "Token #{API_KEY}"

  response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
    http.request(request)
  end

  JSON.parse(response.body)
end

# Usage
prices = get_latest_prices(['WTI_USD', 'BRENT_CRUDE_USD'])
wti = prices['data']['prices'].find { |p| p['code'] == 'WTI_USD' }
puts "WTI: $#{wti['price']}"

Quick Examples

Price Alert System

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

  const data = await response.json();
  // Single commodity requests return a flat data object
  const wtiPrice = data.data.price;

  if (wtiPrice > 80) {
    sendAlert(`WTI above $80: Currently $${wtiPrice}`);
  }
}

// Check every 5 minutes
setInterval(checkPriceThreshold, 5 * 60 * 1000);

Simple Dashboard

<!DOCTYPE html>
<html>
  <head>
    <title>Oil Prices</title>
  </head>
  <body>
    <h1>Live Oil Prices</h1>
    <div id="prices">Loading...</div>

    <script>
      async function updatePrices() {
        // Note: In production, proxy through your backend
        const response = await fetch("/api/prices");
        const data = await response.json();

        // data.data.prices is an array - find each commodity by its code
        const wti = data.data.prices.find((p) => p.code === "WTI_USD");
        const brent = data.data.prices.find(
          (p) => p.code === "BRENT_CRUDE_USD",
        );

        document.getElementById("prices").innerHTML = `
        <p>WTI: $${wti.price}</p>
        <p>Brent: $${brent.price}</p>
        <p>Last Updated: ${new Date(wti.created_at).toLocaleString()}</p>
      `;
      }

      updatePrices();
      // 30 minutes fits the free plan (48 requests/day). Developer and
      // above: 5 * 60 * 1000. See /guides/rate-limiting#how-often-to-poll
      setInterval(updatePrices, 30 * 60 * 1000);
    </script>
  </body>
</html>

What's Next?

Now that you've made your first request, explore:

  • API Reference - All available endpoints
  • Authentication Guide - Security best practices
  • Making Requests - Request patterns and examples
  • Handling Responses - Response parsing and error handling
  • Premium Features - Advanced endpoints and features

Need Help?

  • Email: support@oilpriceapi.com
  • Chat: Available in dashboard
  • FAQ - Common questions answered
  • Status Page - API health
Last Updated: 10/17/26, 10:04 PM