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

Tableau Integration

Build interactive crude oil dashboards and energy market visualizations by connecting OilPriceAPI to Tableau Desktop and Tableau Server.

Overview

Tableau is the industry-leading data visualization platform trusted by energy companies, financial institutions, and analysts worldwide. By integrating OilPriceAPI with Tableau, you can create stunning oil price dashboards, perform sophisticated trend analysis, and share real-time commodity insights with stakeholders.

Key Benefits:

  • Interactive oil price visualizations with drill-down capabilities
  • Real-time Brent and WTI crude price tracking
  • Historical trend analysis with powerful analytics
  • Automated data refresh and alerting
  • Enterprise-grade sharing via Tableau Server or Tableau Cloud

Prerequisites

Before you begin, ensure you have:

  1. Tableau Desktop (2019.2 or later recommended for Web Data Connector support)
  2. OilPriceAPI account with an active API key (Sign up)
  3. Basic familiarity with Tableau data connections

Integration Methods

Tableau offers multiple ways to connect to REST APIs like OilPriceAPI:

MethodBest ForComplexity
Web Data ConnectorInteractive dashboardsMedium
Prep BuilderETL workflowsLow
Python/TabPyAdvanced analyticsHigh
Flat file importQuick analysisLow

Method 1: Web Data Connector (Recommended)

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 "Tableau Integration"
  4. Copy your API key securely

For detailed setup, see our Authentication Guide.

Step 2: Create a Web Data Connector

Create an HTML file to serve as your Tableau WDC:

<!DOCTYPE html>
<html>
<head>
    <title>OilPriceAPI Connector for Tableau</title>
    <script src="https://connectors.tableau.com/libs/tableauwdc-2.3.latest.js"></script>
</head>
<body>
    <h1>OilPriceAPI Data Connector</h1>
    <div>
        <label>API Key: <input type="password" id="apiKey" /></label>
    </div>
    <div>
        <label>Commodities (comma-separated):</label>
        <input type="text" id="commodities" value="WTI_USD,BRENT_CRUDE_USD" />
    </div>
    <div>
        <label>Data Range:</label>
        <select id="dataRange">
            <option value="latest">Latest Prices</option>
            <option value="past_day">Past 24 Hours</option>
            <option value="past_week">Past Week</option>
            <option value="past_month">Past Month</option>
            <option value="past_year">Past Year</option>
        </select>
    </div>
    <button id="submitButton">Connect to OilPriceAPI</button>

    <script>
        (function() {
            var myConnector = tableau.makeConnector();

            myConnector.getSchema = function(schemaCallback) {
                var cols = [
                    { id: "price", dataType: tableau.dataTypeEnum.float },
                    { id: "formatted", dataType: tableau.dataTypeEnum.string },
                    { id: "currency", dataType: tableau.dataTypeEnum.string },
                    { id: "code", dataType: tableau.dataTypeEnum.string },
                    { id: "created_at", dataType: tableau.dataTypeEnum.datetime },
                    { id: "type", dataType: tableau.dataTypeEnum.string }
                ];

                var tableSchema = {
                    id: "oilPrices",
                    alias: "Oil Price Data from OilPriceAPI",
                    columns: cols
                };

                schemaCallback([tableSchema]);
            };

            myConnector.getData = function(table, doneCallback) {
                var connectionData = JSON.parse(tableau.connectionData);
                var apiKey = tableau.password;
                var endpoint = connectionData.dataRange === 'latest'
                    ? '/v1/prices/latest'
                    : '/v1/prices/' + connectionData.dataRange;

                var url = 'https://api.oilpriceapi.com' + endpoint +
                          '?by_code=' + encodeURIComponent(connectionData.commodities);

                if (connectionData.dataRange !== 'latest') {
                    url += '&interval=1d';
                }

                fetch(url, {
                    headers: { 'Authorization': 'Token ' + apiKey }
                })
                .then(response => response.json())
                .then(data => {
                    var tableData = [];
                    var prices = connectionData.dataRange === 'latest'
                        ? [data.data]
                        : data.data.prices;

                    prices.forEach(function(price) {
                        tableData.push({
                            price: price.price,
                            formatted: price.formatted,
                            currency: price.currency,
                            code: price.code,
                            created_at: price.created_at,
                            type: price.type
                        });
                    });

                    table.appendRows(tableData);
                    doneCallback();
                });
            };

            tableau.registerConnector(myConnector);

            document.getElementById('submitButton').addEventListener('click', function() {
                tableau.connectionData = JSON.stringify({
                    commodities: document.getElementById('commodities').value,
                    dataRange: document.getElementById('dataRange').value
                });
                tableau.password = document.getElementById('apiKey').value;
                tableau.connectionName = "OilPriceAPI Data";
                tableau.submit();
            });
        })();
    </script>
</body>
</html>

Step 3: Host the Connector

Host the HTML file on a web server (localhost for development, or a secure internal server for production).

Step 4: Connect from Tableau

  1. Open Tableau Desktop
  2. Select Web Data Connector under Connect
  3. Enter your connector URL
  4. Fill in your API key and select commodities
  5. Click Connect to OilPriceAPI

[Screenshot: Tableau Web Data Connector with OilPriceAPI configuration]

Method 2: Tableau Prep Builder

For ETL workflows, use Tableau Prep with a script step:

Python Script for Prep Builder

import pandas as pd
import requests

def get_oil_prices(api_key, commodities, endpoint='latest'):
    """Fetch oil prices from OilPriceAPI for Tableau Prep"""

    base_url = 'https://api.oilpriceapi.com/v1/prices'
    headers = {'Authorization': f'Token {api_key}'}
    params = {'by_code': ','.join(commodities)}

    if endpoint == 'latest':
        url = f'{base_url}/latest'
    else:
        url = f'{base_url}/{endpoint}'
        params['interval'] = '1d'

    response = requests.get(url, headers=headers, params=params)
    data = response.json()

    if endpoint == 'latest':
        prices = [data['data']]
    else:
        prices = data['data']['prices']

    df = pd.DataFrame(prices)
    df['created_at'] = pd.to_datetime(df['created_at'])

    return df

# Example usage in Tableau Prep
def get_output_schema():
    return pd.DataFrame({
        'price': pd.Series(dtype='float'),
        'formatted': pd.Series(dtype='str'),
        'currency': pd.Series(dtype='str'),
        'code': pd.Series(dtype='str'),
        'created_at': pd.Series(dtype='datetime64[ns]'),
        'type': pd.Series(dtype='str')
    })

def main():
    # Replace with your credentials
    API_KEY = 'YOUR_API_KEY'
    COMMODITIES = ['WTI_USD', 'BRENT_CRUDE_USD', 'NATURAL_GAS_USD']

    return get_oil_prices(API_KEY, COMMODITIES, 'past_month')

Method 3: CSV/JSON File Import

For quick analysis, export data to a file and import into Tableau:

import requests
import pandas as pd
from datetime import datetime

def export_for_tableau(api_key, commodities, output_file='oil_prices.csv'):
    """Export oil price data to CSV for Tableau import"""

    headers = {'Authorization': f'Token {api_key}'}
    all_data = []

    for commodity in commodities:
        # Get historical data
        response = requests.get(
            'https://api.oilpriceapi.com/v1/prices/past_year',
            headers=headers,
            params={'by_code': commodity, 'interval': '1d'}
        )

        data = response.json()
        for price in data['data']['prices']:
            all_data.append(price)

    df = pd.DataFrame(all_data)
    df['created_at'] = pd.to_datetime(df['created_at'])
    df.to_csv(output_file, index=False)

    print(f"Exported {len(df)} records to {output_file}")
    return df

# Usage
export_for_tableau(
    'YOUR_API_KEY',
    ['WTI_USD', 'BRENT_CRUDE_USD', 'NATURAL_GAS_USD', 'HEATING_OIL_USD']
)

Then in Tableau:

  1. Click Connect > Text file
  2. Select your exported CSV
  3. Tableau will automatically detect column types

Building Effective Oil Price Dashboards

Recommended Visualizations

Chart TypeUse CaseConfiguration
Line ChartPrice trends over timeDate on X-axis, Price on Y-axis, Color by Commodity
Dual-Axis ChartCompare WTI vs Brent spreadTwo price measures with calculated spread
Heat MapPrice changes by month/dayCalendar heat map of daily price changes
Bullet ChartCurrent price vs. targetsCurrent price vs. 52-week high/low

Calculated Fields

Create useful calculated fields for oil price analysis:

// Daily Price Change
[Price] - LOOKUP([Price], -1)

// Percentage Change
([Price] - LOOKUP([Price], -1)) / LOOKUP([Price], -1) * 100

// WTI-Brent Spread (when both commodities in data)
IF [Code] = "WTI_USD" THEN [Price] END -
LOOKUP(IF [Code] = "BRENT_CRUDE_USD" THEN [Price] END, 0)

// 7-Day Moving Average
WINDOW_AVG([Price], -6, 0)

// 52-Week High
WINDOW_MAX([Price], -364, 0)

[Screenshot: Example Tableau dashboard showing crude oil price trends, spreads, and analytics]

Tableau Server/Cloud Deployment

Publishing Workbooks

  1. Complete your dashboard in Tableau Desktop
  2. Click Server > Publish Workbook
  3. Select your Tableau Server or Tableau Cloud site
  4. Configure Data Source to use stored credentials
  5. Set refresh schedule (match your API plan limits)

Configuring Automatic Refresh

PlanRecommended ScheduleMonthly Requests
HobbyOnce daily~900
ProfessionalEvery 4 hours~2,700
EnterpriseHourly~21,600

Rate Limits and Best Practices

Performance Optimization:

  • Use the interval parameter for historical data to reduce row count
  • Cache frequently-accessed data with Tableau extracts
  • Limit commodity codes to only those needed
  • Schedule refreshes during off-peak hours

Security Best Practices:

  • Never embed API keys directly in workbooks
  • Use Tableau Server/Cloud credential management
  • Rotate API keys periodically
  • Monitor usage in your OilPriceAPI Dashboard

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

Troubleshooting

Connection Errors

401 Unauthorized:

  • Verify API key is correct and active
  • Check Authorization header format: Token YOUR_API_KEY
  • Confirm key has not exceeded rate limits

CORS Errors in WDC:

  • Host your Web Data Connector on HTTPS
  • Ensure the connector URL is accessible from Tableau

Data Quality Issues

Missing Data Points:

  • OilPriceAPI provides data during market hours only
  • Use interval parameter for consistent time buckets

Timezone Discrepancies:

  • All OilPriceAPI timestamps are UTC
  • Convert to local timezone in Tableau calculated fields

FAQ

Can I use Tableau Public with OilPriceAPI?

Tableau Public has limited data connector support. We recommend using Tableau Desktop with a data extract, then publishing a static version to Tableau Public. Note that data won't auto-refresh in Tableau Public.

What's the best way to visualize oil price volatility?

Use calculated fields for standard deviation and Bollinger Bands. Combine with heat maps showing price change intensity by time period.

How do I create a WTI-Brent spread chart?

  1. Filter data to include both WTI_USD and BRENT_CRUDE_USD
  2. Create a calculated field for the spread
  3. Use a dual-axis line chart with the spread as a bar chart

Can I blend OilPriceAPI data with other data sources?

Yes, Tableau excels at data blending. Use the date field as your linking dimension to combine oil prices with production data, inventory levels, or financial metrics.

What's the historical data availability?

Historical data availability varies by commodity:

  • WTI Crude: Available from 2000
  • Brent Crude: Available from 1988
  • Natural Gas: Available from 1990

See Commodities List for complete details.

Related Resources

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