Power Outage Data in Tableau

To get power outage data into Tableau, run a short Python job that calls the PowerOutage.us v2 REST API, writes county outage counts into a .hyper extract with the Tableau Hyper API, and publishes it to Tableau Cloud or Tableau Server with Tableau Server Client and a personal access token. Tableau has no built-in connector that sends an API key in an Authorization header, and a published .hyper file has no source Tableau could refresh it from, so the job itself is the refresh: cron or Task Scheduler runs it every 15 minutes and overwrites the data source. If you already load the data into Snowflake, BigQuery or Databricks with our other guides, you can connect Tableau to that table instead.

What you'll have

  • A published data source with customers out, customers tracked, FIPS code and last update time for every county in the states you choose.
  • Counties on a filled map: the five-digit FIPS code is stored as text, ready for the County geographic role.
  • Calculated fields for percent of customers out and minutes since each county was last reported.
  • The data source overwritten every 15 minutes in place, so workbooks built on it show the latest counts without republishing.

What you need

An API key (request one with the form below) and these endpoints. Full details are in the API reference.

EndpointMethodUsed forPackage
/outages/countiesGETCounty customersOut, customersTracked and lastUpdatedAt, with include=fips for the FIPS codes Tableau maps.Core

Step 1: Get a personal access token and a project to publish to

The job signs in as a Tableau user, so that user needs the Creator site role and permission to publish to the target project. Personal access tokens must be turned on for the site: on Tableau Cloud sites created since June 2023 they are off until a site administrator enables them in the site settings, and Tableau Server administrators can turn them off too. Then, signed in as that user, open My Account Settings, create a token named for this job, and copy its secret, which Tableau shows only once. The token carries that user's own permissions; there are no scopes to set. The machine that runs the job needs outbound HTTPS to poweroutage.us and to your Tableau site.

Step 2: Install the libraries and store the settings

Use Python 3.10 or later, which Tableau Server Client requires, and install tableauhyperapi, tableauserverclient and requests in a virtual environment. Then create the settings file: the block writes it with placeholders and makes it readable only by its owner, and you paste the PowerOutage.us key and the token secret into it with an editor, so neither lands in your shell history. If the job runs in the cloud, inject the same variables from your cloud secret manager instead; never put them in the script. TABLEAU_SERVER is the address you see in the browser: your Tableau Cloud pod, such as https://prod-useast-a.online.tableau.com, or your Tableau Server URL. TABLEAU_SITE is the part after /site/ in your Tableau URLs and is required on Tableau Cloud; on Tableau Server, leave it empty for the Default site.

bash
python3 -m venv /opt/poweroutage/venv
/opt/poweroutage/venv/bin/pip install tableauhyperapi tableauserverclient requests

# Create the settings file with placeholders, readable only by the account that runs the job
cat > /opt/poweroutage/poweroutage.env <<'EOF'
export POWEROUTAGE_API_KEY='...'
export TABLEAU_SERVER='https://prod-useast-a.online.tableau.com'
export TABLEAU_SITE='yoursite'
export TABLEAU_PROJECT='Outages'
export TABLEAU_PAT_NAME='poweroutage-publisher'
export TABLEAU_PAT_SECRET='...'
EOF
chmod 600 /opt/poweroutage/poweroutage.env

# Then open the file in an editor and replace each ... with the real value

Step 3: Write the extract script

Save this as publish_counties.py. It requests county counts, maps each field to an extract column, writes a new .hyper file with CreateMode.CREATE_AND_REPLACE, and publishes it with PublishMode.Overwrite. The mapping is id to County ID, name to County, stateId to State ID, fips.full to FIPS (null for the Unknown county row), customersOut and customersTracked to the two counts, lastUpdatedAt to Last Updated (UTC) and meta.generatedAt to Generated At (UTC). Both timestamps are stored as UTC date-times, as their column names say. On a 429 the script waits the Retry-After seconds and tries again, three times at most, without waiting after the last try.

python
import os
import time
from datetime import datetime
from pathlib import Path

import requests
import tableauserverclient as TSC
from tableauhyperapi import (
    Connection,
    CreateMode,
    HyperProcess,
    Inserter,
    SqlType,
    TableDefinition,
    TableName,
    Telemetry,
)

# 44 is Florida and 45 is Georgia. List ids with GET /outages/states.
STATE_IDS = '44,45'
DATASOURCE_NAME = 'PowerOutage county outages'
HYPER_FILE = Path(__file__).with_name('poweroutage_counties.hyper')

# A single table named "Extract"."Extract", which every Tableau version can publish
COUNTIES = TableDefinition(
    TableName('Extract', 'Extract'),
    [
        TableDefinition.Column('County ID', SqlType.big_int()),
        TableDefinition.Column('County', SqlType.text()),
        TableDefinition.Column('State ID', SqlType.big_int()),
        TableDefinition.Column('FIPS', SqlType.text()),
        TableDefinition.Column('Customers Out', SqlType.big_int()),
        TableDefinition.Column('Customers Tracked', SqlType.big_int()),
        TableDefinition.Column('Last Updated (UTC)', SqlType.timestamp()),
        TableDefinition.Column('Generated At (UTC)', SqlType.timestamp()),
    ],
)


def get(url, params):
    headers = {'Authorization': f"Bearer {os.environ['POWEROUTAGE_API_KEY']}"}
    for attempt in range(1, 4):
        response = requests.get(url, params=params, headers=headers, timeout=60)
        if response.status_code != 429:
            response.raise_for_status()
            return response.json()
        if attempt < 3:
            time.sleep(int(response.headers.get('Retry-After', '10')))
    raise RuntimeError(f'Still rate limited after 3 tries: {url}')


def utc(value):
    # The API sends UTC timestamps such as 2026-12-03T16:30:46.551Z
    return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ') if value else None


def build_extract():
    payload = get(
        'https://poweroutage.us/api/v2/outages/counties',
        {'stateId': STATE_IDS, 'include': 'fips'},
    )
    generated_at = utc(payload['meta']['generatedAt'])
    rows = [
        [
            county['id'],
            county['name'],
            county['stateId'],
            county['fips']['full'] if county['fips'] else None,
            county['customersOut'],
            county['customersTracked'],
            utc(county['lastUpdatedAt']),
            generated_at,
        ]
        for county in payload['data']
    ]
    with HyperProcess(Telemetry.DO_NOT_SEND_USAGE_DATA_TO_TABLEAU) as hyper:
        with Connection(hyper.endpoint, HYPER_FILE, CreateMode.CREATE_AND_REPLACE) as connection:
            connection.catalog.create_schema('Extract')
            connection.catalog.create_table(COUNTIES)
            with Inserter(connection, COUNTIES) as inserter:
                inserter.add_rows(rows)
                inserter.execute()
    return len(rows)


def publish():
    auth = TSC.PersonalAccessTokenAuth(
        os.environ['TABLEAU_PAT_NAME'],
        os.environ['TABLEAU_PAT_SECRET'],
        site_id=os.environ.get('TABLEAU_SITE', ''),
    )
    server = TSC.Server(os.environ['TABLEAU_SERVER'], use_server_version=True)
    with server.auth.sign_in(auth):
        project_name = os.environ['TABLEAU_PROJECT']
        project = next((p for p in TSC.Pager(server.projects) if p.name == project_name), None)
        if project is None:
            raise RuntimeError(f'No project named {project_name} on this site')
        datasource = TSC.DatasourceItem(project.id, name=DATASOURCE_NAME)
        # Overwrite creates the data source on the first run and replaces its data after that
        server.datasources.publish(datasource, HYPER_FILE, TSC.Server.PublishMode.Overwrite)


if __name__ == '__main__':
    print(f'{build_extract()} counties written to {HYPER_FILE.name}')
    publish()

Step 4: Run it once, then schedule it

Run the script by hand first; it prints how many counties it wrote, and the data source appears in your project. Then schedule it every 15 minutes, which is enough for most dashboards. The data updates every minute, so run it every 1 or 2 minutes if you need the latest numbers, as long as each run finishes before the next one starts. On Linux or macOS, use cron. On Windows, create a Task Scheduler task whose action starts the virtual environment's python.exe with publish_counties.py, set its trigger to repeat every 15 minutes for a duration of Indefinitely, and set the variables as user environment variables of the account it runs as. A container job on a cloud scheduler works the same way, with the variables from its secret store.

bash
# Run once by hand and check the data source appears in your project
. /opt/poweroutage/poweroutage.env && /opt/poweroutage/venv/bin/python /opt/poweroutage/publish_counties.py

# Then add this line with crontab -e to republish every 15 minutes
*/15 * * * * . /opt/poweroutage/poweroutage.env && /opt/poweroutage/venv/bin/python /opt/poweroutage/publish_counties.py >> /opt/poweroutage/publish.log 2>&1

Step 5: Build views on the published data source

In Tableau Desktop or web authoring, connect to the published data source PowerOutage county outages. Give the FIPS field the County geographic role (Geographic Role, then County) and Tableau draws a filled map of counties. Add these calculated fields: percent out divides the sums so it rolls up correctly to states, and minutes since report shows how stale each county's count is, because records are not zeroed when a utility stops reporting. Group and filter by State ID and County ID rather than names, which repeat across states. Workbooks keep working after each overwrite, because the data source keeps its name, project and columns.

tableau calculation
// Percent Out
SUM([Customers Out]) / SUM([Customers Tracked])

// Minutes Since Report
DATEDIFF('minute', [Last Updated (UTC)], [Generated At (UTC)])

Tips for Tableau

  • Give the job its own personal access token. Tableau allows one session per token, so signing in elsewhere with the same token ends the job's session and makes its next call fail with an authentication error.
  • Tokens expire after 15 days without use, and at the end of the expiration period your site administrator set (one year by default on sites created before June 2023). A job that runs every 15 minutes never goes idle, but plan to create a new token and update the environment file before the period ends.
  • Don't add an extract refresh schedule to this data source. A published .hyper file has no connection behind it, so Tableau has nothing to refresh; the script is the refresh.
  • Each state can include a county named Unknown for customers a utility could not place in a county. Its FIPS is null, so Tableau lists it under unknown locations on a map; filter it out there and keep it in totals.
  • Each run makes one API request, well under the limit of 10 requests per 10 seconds, so several jobs for different regions can share a key.

Used by

Related integrations

FAQ

Here are some commonly asked questions

Request API access

Tell us what you're building and we'll set you up with a trial key.