Oil Price API Documentation - Quick Start in 5 Minutes | REST API
GitHub
GitHub

Google Sheets Integration

Import real-time oil prices and commodity data directly into Google Sheets for spreadsheet analysis, automated reports, and team collaboration.

Overview

Google Sheets is a versatile cloud-based spreadsheet platform ideal for tracking commodity prices, building financial models, and sharing energy market data across teams. By integrating OilPriceAPI with Google Sheets, you can create live oil price trackers, automated pricing spreadsheets, and collaborative energy analytics workbooks.

Key Benefits:

  • Real-time crude oil prices in familiar spreadsheet format
  • Automatic price updates with Apps Script triggers
  • Share live commodity data with team members
  • Build custom formulas combining price data with business logic
  • Free to use with Google Workspace or personal Google account

Prerequisites

Before you begin, ensure you have:

  1. Google Account with access to Google Sheets
  2. OilPriceAPI account with an active API key (Sign up)
  3. Basic familiarity with Google Sheets formulas

Quick Start: IMPORTDATA Function

The fastest way to get oil prices into Google Sheets is using CSV export:

Step 1: Get Your API Key

  1. Log in to your OilPriceAPI Dashboard
  2. Navigate to API Keys section
  3. Create a new key named "Google Sheets"
  4. Copy your API key

For detailed setup, see our Authentication Guide.

Step 2: Use IMPORTDATA with CSV Format

OilPriceAPI supports CSV format for easy spreadsheet import:

=IMPORTDATA("https://api.oilpriceapi.com/v1/prices/latest?by_code=WTI_USD&format=csv&api_key=YOUR_API_KEY")

Note: For the IMPORTDATA function, append your API key as a query parameter. This is the only method where query parameter authentication is supported.

[Screenshot: Google Sheets showing oil price data imported via IMPORTDATA]

Recommended Method: Google Apps Script

For more control and security, use Google Apps Script to fetch data:

Step 1: Open Apps Script Editor

  1. Open your Google Sheet
  2. Click Extensions > Apps Script
  3. Delete any existing code in the editor

Step 2: Add the OilPriceAPI Script

Copy and paste this script:

/**
 * OilPriceAPI Integration for Google Sheets
 * Fetches real-time oil and commodity prices
 */

// Store your API key in Script Properties for security
// Go to Project Settings > Script Properties > Add Property
// Key: OILPRICE_API_KEY, Value: your_api_key

const API_BASE_URL = 'https://api.oilpriceapi.com/v1';

/**
 * Get the latest price for a commodity
 * @param {string} commodityCode - Commodity code (e.g., "WTI_USD", "BRENT_CRUDE_USD")
 * @return {number} Current price
 * @customfunction
 */
function OILPRICE(commodityCode) {
  const apiKey = PropertiesService.getScriptProperties().getProperty('OILPRICE_API_KEY');

  if (!apiKey) {
    throw new Error('API key not configured. Set OILPRICE_API_KEY in Script Properties.');
  }

  const url = `${API_BASE_URL}/prices/latest?by_code=${encodeURIComponent(commodityCode)}`;

  const options = {
    method: 'get',
    headers: {
      'Authorization': `Token ${apiKey}`
    },
    muteHttpExceptions: true
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const data = JSON.parse(response.getContentText());

    if (data.status === 'success') {
      return data.data.price;
    } else {
      throw new Error(data.message || 'API error');
    }
  } catch (error) {
    return `Error: ${error.message}`;
  }
}

/**
 * Get formatted price with currency symbol
 * @param {string} commodityCode - Commodity code
 * @return {string} Formatted price (e.g., "$72.45")
 * @customfunction
 */
function OILPRICE_FORMATTED(commodityCode) {
  const apiKey = PropertiesService.getScriptProperties().getProperty('OILPRICE_API_KEY');

  const url = `${API_BASE_URL}/prices/latest?by_code=${encodeURIComponent(commodityCode)}`;

  const options = {
    method: 'get',
    headers: {
      'Authorization': `Token ${apiKey}`
    },
    muteHttpExceptions: true
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const data = JSON.parse(response.getContentText());

    if (data.status === 'success') {
      return data.data.formatted;
    } else {
      throw new Error(data.message || 'API error');
    }
  } catch (error) {
    return `Error: ${error.message}`;
  }
}

/**
 * Get multiple commodity prices at once
 * @param {string} commodityCodes - Comma-separated commodity codes
 * @return {Array} Array of [code, price, formatted, currency]
 * @customfunction
 */
function OILPRICES(commodityCodes) {
  const apiKey = PropertiesService.getScriptProperties().getProperty('OILPRICE_API_KEY');

  const url = `${API_BASE_URL}/prices/latest?by_code=${encodeURIComponent(commodityCodes)}`;

  const options = {
    method: 'get',
    headers: {
      'Authorization': `Token ${apiKey}`
    },
    muteHttpExceptions: true
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const data = JSON.parse(response.getContentText());

    if (data.status === 'success') {
      // Handle single or multiple commodities
      const prices = Array.isArray(data.data) ? data.data : [data.data];
      return prices.map(p => [p.code, p.price, p.formatted, p.currency]);
    } else {
      throw new Error(data.message || 'API error');
    }
  } catch (error) {
    return [[`Error: ${error.message}`]];
  }
}

/**
 * Fetch historical prices and write to a range
 * @param {string} commodityCode - Commodity code
 * @param {string} period - Time period (past_day, past_week, past_month, past_year)
 * @param {string} targetCell - Starting cell reference (e.g., "A1")
 */
function fetchHistoricalPrices(commodityCode, period, targetCell) {
  const apiKey = PropertiesService.getScriptProperties().getProperty('OILPRICE_API_KEY');

  const url = `${API_BASE_URL}/prices/${period}?by_code=${encodeURIComponent(commodityCode)}&interval=1d`;

  const options = {
    method: 'get',
    headers: {
      'Authorization': `Token ${apiKey}`
    },
    muteHttpExceptions: true
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const data = JSON.parse(response.getContentText());

    if (data.status !== 'success') {
      throw new Error(data.message || 'API error');
    }

    const prices = data.data.prices;
    const sheet = SpreadsheetApp.getActiveSheet();
    const range = sheet.getRange(targetCell);

    // Prepare data with headers
    const output = [['Date', 'Price', 'Currency', 'Type']];
    prices.forEach(p => {
      output.push([
        new Date(p.created_at),
        p.price,
        p.currency,
        p.type
      ]);
    });

    // Write to sheet
    const targetRange = sheet.getRange(
      range.getRow(),
      range.getColumn(),
      output.length,
      output[0].length
    );
    targetRange.setValues(output);

    SpreadsheetApp.getActiveSpreadsheet().toast(
      `Loaded ${prices.length} price records`,
      'OilPriceAPI'
    );

  } catch (error) {
    SpreadsheetApp.getActiveSpreadsheet().toast(
      `Error: ${error.message}`,
      'OilPriceAPI Error'
    );
  }
}

/**
 * Create a custom menu for OilPriceAPI functions
 */
function onOpen() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu('OilPriceAPI')
    .addItem('Refresh All Prices', 'refreshAllPrices')
    .addItem('Load WTI Historical (Past Month)', 'loadWTIHistory')
    .addItem('Load Brent Historical (Past Month)', 'loadBrentHistory')
    .addSeparator()
    .addItem('Configure API Key', 'showApiKeyDialog')
    .addToUi();
}

/**
 * Refresh all OILPRICE formulas in the sheet
 */
function refreshAllPrices() {
  // Force recalculation of custom functions
  const sheet = SpreadsheetApp.getActiveSheet();
  const range = sheet.getDataRange();

  // Touch the sheet to trigger recalculation
  SpreadsheetApp.flush();

  SpreadsheetApp.getActiveSpreadsheet().toast(
    'Prices refreshed',
    'OilPriceAPI'
  );
}

function loadWTIHistory() {
  fetchHistoricalPrices('WTI_USD', 'past_month', 'A1');
}

function loadBrentHistory() {
  fetchHistoricalPrices('BRENT_CRUDE_USD', 'past_month', 'A1');
}

function showApiKeyDialog() {
  const ui = SpreadsheetApp.getUi();
  const result = ui.prompt(
    'Configure API Key',
    'Enter your OilPriceAPI key:',
    ui.ButtonSet.OK_CANCEL
  );

  if (result.getSelectedButton() === ui.Button.OK) {
    PropertiesService.getScriptProperties().setProperty(
      'OILPRICE_API_KEY',
      result.getResponseText()
    );
    ui.alert('API key saved successfully!');
  }
}

Step 3: Configure Your API Key

  1. In Apps Script, click Project Settings (gear icon)
  2. Scroll to Script Properties
  3. Click Add script property
  4. Set Property: OILPRICE_API_KEY, Value: your_api_key
  5. Click Save

Step 4: Use Custom Functions

Return to your spreadsheet and use the custom functions:

=OILPRICE("WTI_USD")           // Returns: 72.45
=OILPRICE("BRENT_CRUDE_USD")   // Returns: 76.23
=OILPRICE_FORMATTED("WTI_USD") // Returns: $72.45
=OILPRICES("WTI_USD,BRENT_CRUDE_USD,NATURAL_GAS_USD")

[Screenshot: Google Sheets using OILPRICE custom functions with live data]

Setting Up Automatic Refresh

Time-Driven Triggers

Set up automatic price updates with Apps Script triggers:

  1. In Apps Script, click Triggers (clock icon)
  2. Click Add Trigger
  3. Configure:
    • Function: refreshAllPrices
    • Event source: Time-driven
    • Type: Hour timer or specific time
  4. Click Save

Recommended schedules based on your plan:

PlanRefresh FrequencyDaily Requests
FreeEvery 6 hours~4
HobbyEvery hour~24
ProfessionalEvery 15 minutes~96

On-Edit Trigger for Manual Refresh

Add a refresh button to your sheet:

function onEdit(e) {
  // Check if the edit was in the refresh button cell
  if (e.range.getA1Notation() === 'A1' && e.value === 'REFRESH') {
    refreshAllPrices();
    e.range.setValue('');  // Clear the cell
  }
}

Building a Complete Oil Price Tracker

Sample Spreadsheet Layout

ABCDE
CommodityCurrent Price24h ChangeChange %Last Updated
WTI Crude=OILPRICE("WTI_USD")=B2-B7=D2/B7*100=NOW()
Brent Crude=OILPRICE("BRENT_CRUDE_USD")=B3-B8=D3/B8*100=NOW()
Natural Gas=OILPRICE("NATURAL_GAS_USD")=B4-B9=D4/B9*100=NOW()

Conditional Formatting

Add visual indicators for price changes:

  1. Select the Change % column
  2. Click Format > Conditional formatting
  3. Add rules:
    • Green background for values > 0
    • Red background for values < 0

Price Alerts with Email

/**
 * Check prices and send email alerts
 * Set up as a time-driven trigger
 */
function checkPriceAlerts() {
  const apiKey = PropertiesService.getScriptProperties().getProperty('OILPRICE_API_KEY');
  const alertEmail = '[email protected]';

  // Define your alert thresholds
  const alerts = [
    { code: 'WTI_USD', above: 80, below: 60 },
    { code: 'BRENT_CRUDE_USD', above: 85, below: 65 }
  ];

  alerts.forEach(alert => {
    const price = OILPRICE(alert.code);

    if (price > alert.above) {
      MailApp.sendEmail(
        alertEmail,
        `Oil Price Alert: ${alert.code} above $${alert.above}`,
        `Current ${alert.code} price: $${price}\nThreshold: $${alert.above}`
      );
    }

    if (price < alert.below) {
      MailApp.sendEmail(
        alertEmail,
        `Oil Price Alert: ${alert.code} below $${alert.below}`,
        `Current ${alert.code} price: $${price}\nThreshold: $${alert.below}`
      );
    }
  });
}

Rate Limits and Best Practices

Optimizing API Usage:

  • Cache prices in cells rather than making repeated API calls
  • Use OILPRICES() to fetch multiple commodities in one request
  • Set appropriate refresh intervals based on your plan
  • Use historical endpoints with interval parameter for trend data

Security Best Practices:

  • Store API keys in Script Properties, not in cells
  • Don't share spreadsheets with API keys visible
  • Use separate API keys for different integrations
  • Monitor usage in your OilPriceAPI Dashboard

For detailed rate limit information, see our Rate Limiting Guide.

Troubleshooting

Custom Function Not Working

"Unknown function OILPRICE":

  • Ensure Apps Script is saved and deployed
  • Refresh the spreadsheet (Ctrl+R or Cmd+R)
  • Check for script errors in Apps Script execution log

"API key not configured":

  • Set the OILPRICE_API_KEY in Script Properties
  • Verify the key is saved correctly

Rate Limit Exceeded

"429 Too Many Requests":

  • Reduce refresh frequency
  • Cache results in cells instead of making repeated calls
  • Consider upgrading your plan

Slow Loading

  • Custom functions have execution time limits
  • Use OILPRICES() for bulk fetches
  • Consider using triggers instead of cell formulas for large datasets

FAQ

Can I use this with Google Sheets on mobile?

Yes, the spreadsheet with oil prices works on Google Sheets mobile apps. However, custom functions execute on Google's servers, so you'll see the results but can't edit the Apps Script from mobile.

How do I share a sheet with live oil prices?

When sharing, the API key stays in Script Properties (not visible to viewers). Viewers will see the price values but won't have access to your API key.

What's the difference between IMPORTDATA and Apps Script?

FeatureIMPORTDATAApps Script
Setup complexitySimpleMedium
API key securityExposed in URLHidden in properties
Custom logicNoneFull JavaScript
Error handlingLimitedComprehensive
Multiple commoditiesMultiple cellsSingle function

Can I use Google Sheets for historical price charts?

Yes, use fetchHistoricalPrices() to load data, then insert a chart. See our Historical Prices API for available time ranges.

Why do prices show as cached/stale?

Google Sheets caches custom function results. To force refresh:

  • Edit the cell and press Enter
  • Use the custom menu: OilPriceAPI > Refresh All Prices
  • Set up time-driven triggers for automatic refresh

Related Resources

  • Authentication Guide - API key setup and security
  • Historical Prices API - Time-series data endpoints
  • Commodities List - Available commodity codes
  • Rate Limiting Guide - Understanding request limits
  • Looker Studio Integration - Advanced Google ecosystem analytics
  • Power BI Integration - Microsoft BI tool integration
Last Updated: 12/28/25, 12:24 AM