Tableau Integration
Build interactive crude oil dashboards and energy market visualizations by connecting OilPriceAPI to Tableau Desktop and Tableau Server. Ideal for commodities trading analysis, aviation fuel cost tracking, and maritime shipping bunker price analytics.
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:
- Tableau Desktop (2019.2 or later recommended for Web Data Connector support)
- OilPriceAPI account with an active API key (Sign up)
- Basic familiarity with Tableau data connections
Integration Methods
Tableau offers multiple ways to connect to REST APIs like OilPriceAPI:
| Method | Best For | Complexity |
|---|---|---|
| Web Data Connector | Interactive dashboards | Medium |
| Prep Builder | ETL workflows | Low |
| Python/TabPy | Advanced analytics | High |
| Flat file import | Quick analysis | Low |
Method 1: Web Data Connector (Recommended)
Step 1: Get Your API Key
- Log in to your OilPriceAPI Dashboard
- Navigate to API Keys section
- Create a new key named "Tableau Integration"
- 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
- Open Tableau Desktop
- Select Web Data Connector under Connect
- Enter your connector URL
- Fill in your API key and select commodities
- Click Connect to OilPriceAPI
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:
- Click Connect > Text file
- Select your exported CSV
- Tableau will automatically detect column types
Building Effective Oil Price Dashboards
Recommended Visualizations
| Chart Type | Use Case | Configuration |
|---|---|---|
| Line Chart | Price trends over time | Date on X-axis, Price on Y-axis, Color by Commodity |
| Dual-Axis Chart | Compare WTI vs Brent spread | Two price measures with calculated spread |
| Heat Map | Price changes by month/day | Calendar heat map of daily price changes |
| Bullet Chart | Current price vs. targets | Current 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)
Tableau Server/Cloud Deployment
Publishing Workbooks
- Complete your dashboard in Tableau Desktop
- Click Server > Publish Workbook
- Select your Tableau Server or Tableau Cloud site
- Configure Data Source to use stored credentials
- Set refresh schedule (match your API plan limits)
Configuring Automatic Refresh
| Plan | Recommended Schedule | Monthly Requests |
|---|---|---|
| Hobby | Once daily | ~900 |
| Professional | Every 4 hours | ~2,700 |
| Enterprise | Hourly | ~21,600 |
Rate Limits and Best Practices
Performance Optimization:
- Use the
intervalparameter 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
intervalparameter for consistent time buckets
Timezone Discrepancies:
- All OilPriceAPI timestamps are UTC
- Convert to local timezone in Tableau calculated fields
Frequently Asked Questions
How do I authenticate OilPriceAPI in Tableau?
Authentication in Tableau depends on your integration method:
Web Data Connector (WDC):
- Store the API key using
tableau.passwordin your connector code - Pass it in the Authorization header as
Token YOUR_API_KEY
Tableau Prep/Python:
- Store credentials in environment variables or a config file
- Pass the Authorization header with each request
For Tableau Server/Cloud:
- Publish your workbook with embedded credentials
- Or configure data source credentials in Tableau Server settings
- Use Tableau's credential management for secure storage
See the Authentication Guide for detailed instructions.
What's the rate limit when using Tableau with OilPriceAPI?
OilPriceAPI limits depend on your plan: Free (1,000/month), Hobby (10,000/month), Starter (50,000/month), Professional (100,000/month). Configure Tableau refresh schedules to stay within your limits:
| Plan | Recommended Refresh | Requests/Month Used |
|---|---|---|
| Free | Once daily | ~30 |
| Hobby | 4x daily | ~120 |
| Professional | Hourly | ~720 |
Use Tableau extracts to cache data locally and reduce API calls.
Can I automate price updates in Tableau?
Yes, Tableau offers several automation options:
Tableau Desktop:
- Use the Extract Refresh feature manually or via command line
- Schedule with Windows Task Scheduler or cron
Tableau Server/Cloud:
- Publish your workbook to Tableau Server
- Go to the data source settings
- Configure Refresh Schedules (hourly, daily, weekly)
- Set up alerts for refresh failures
Tableau Prep:
- Schedule flows to run automatically
- Chain data preparation with refresh
What happens if the API call fails in Tableau?
When API calls fail in Tableau:
Web Data Connector:
- Add error handling in your JavaScript code
- Display user-friendly error messages
- Log errors for debugging
Tableau Prep/Desktop:
- Tableau shows connection errors in the data source pane
- Check the Tableau log files for details
- Previous extract data remains available if refresh fails
Tableau Server:
- Failed refreshes trigger email notifications
- Check the Background Tasks admin view
- Data shows last successful refresh timestamp
Best practice: Configure Tableau to retain the last successful extract so dashboards remain functional during API issues.
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?
- Filter data to include both WTI_USD and BRENT_CRUDE_USD
- Create a calculated field for the spread
- 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
- Power BI Integration - Microsoft BI tool integration
- Looker Studio Integration - Google ecosystem integration
- Google Sheets Integration - Spreadsheet data source
- Commodities Trading API - Trading and analytics data
- Aviation Fuel API - Jet fuel price tracking
- Maritime Bunker API - Marine fuel analytics
- Logistics Fuel API - Supply chain cost analysis
- Python Developer Guide - Custom code integration
- R Developer Guide - Statistical analysis integration
- Authentication Guide - API key setup and security
- Historical Prices API - Time-series data endpoints