Power Outage Data in Snowflake

To get power outage data into Snowflake, let a Python stored procedure call the PowerOutage.us v2 REST API through an external access integration, keep your API key in a Snowflake secret, and run the procedure from a task every 15 minutes. Nothing runs outside your account: the procedure fetches JSON and GeoJSON, MERGEs county counts into a table, and loads each outage shape as a GEOGRAPHY you can join to your own sites. This guide sets up the network rule, secret and integration, then the tables, the procedure and the task.

What you'll have

  • A county_outages table, kept current with MERGE, holding customers out and customers tracked for every county in the states you choose.
  • An active_outages table with each outage stored as a GEOGRAPHY, ready for ST_CONTAINS joins against your site locations.
  • An API key held in a Snowflake secret that only the procedure can read, never in a worksheet or a table.
  • A task that refreshes both tables every 15 minutes with no servers or pipelines outside Snowflake.

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 and customersTracked for one or more stateId values, with include=fips for joins to your own county data.Core
/geojson/outagesGETEach active outage as a GeoJSON feature, which TRY_TO_GEOGRAPHY turns into a GEOGRAPHY value.Standard

Step 1: Let Snowflake reach the API

Snowflake blocks outbound calls from procedures until you allow them. Create a network rule for poweroutage.us (port 443 is the default), a GENERIC_STRING secret holding your API key, and an external access integration that ties the two together. Then grant the role that will own the procedure USAGE on the integration, READ on the secret, and EXECUTE TASK so it can schedule the load. Unless that role owns the schema, it also needs USAGE on the database, the schema and the warehouse, plus CREATE TABLE, CREATE PROCEDURE and CREATE TASK on the schema. Creating the integration needs ACCOUNTADMIN or the CREATE INTEGRATION privilege.

sql
-- Run as ACCOUNTADMIN, or a role with CREATE INTEGRATION on the account
-- and CREATE NETWORK RULE and CREATE SECRET on the schema.
USE SCHEMA analytics.poweroutage;

CREATE OR REPLACE NETWORK RULE poweroutage_api
  MODE = EGRESS
  TYPE = HOST_PORT
  VALUE_LIST = ('poweroutage.us');

CREATE OR REPLACE SECRET poweroutage_api_key
  TYPE = GENERIC_STRING
  SECRET_STRING = '<YOUR_API_KEY>';

CREATE OR REPLACE EXTERNAL ACCESS INTEGRATION poweroutage_access
  ALLOWED_NETWORK_RULES = (poweroutage_api)
  ALLOWED_AUTHENTICATION_SECRETS = (poweroutage_api_key)
  ENABLED = TRUE;

-- The role that will own the tables, the procedure and the task
GRANT USAGE ON INTEGRATION poweroutage_access TO ROLE data_engineer;
GRANT READ ON SECRET poweroutage_api_key TO ROLE data_engineer;
GRANT EXECUTE TASK ON ACCOUNT TO ROLE data_engineer;
-- Not needed if data_engineer already owns the schema
GRANT USAGE ON DATABASE analytics TO ROLE data_engineer;
GRANT USAGE ON SCHEMA analytics.poweroutage TO ROLE data_engineer;
GRANT CREATE TABLE, CREATE PROCEDURE, CREATE TASK ON SCHEMA analytics.poweroutage TO ROLE data_engineer;
GRANT USAGE ON WAREHOUSE transform_wh TO ROLE data_engineer;

Step 2: Create the target tables

Switch to the role you granted above and create two tables. county_outages keeps one row per county and is updated in place. active_outages is replaced on every run, so it always holds the outages that are active now. Timestamps arrive as ISO 8601 strings in UTC and load as TIMESTAMP_TZ.

sql
CREATE TABLE IF NOT EXISTS county_outages (
  county_id NUMBER PRIMARY KEY,
  county_name STRING,
  state_id NUMBER,
  fips STRING,
  customers_out NUMBER,
  customers_tracked NUMBER,
  last_updated_at TIMESTAMP_TZ,
  generated_at TIMESTAMP_TZ
);

CREATE TABLE IF NOT EXISTS active_outages (
  utility_id NUMBER,
  outage_id STRING,
  customers_out NUMBER,
  cause STRING,
  estimated_restoration_at TIMESTAMP_TZ,
  shape GEOGRAPHY,
  generated_at TIMESTAMP_TZ
);

Step 3: Write the loading procedure

The procedure reads the key with secrets.get_generic_secret_string, using the alias from its SECRETS clause, and sends it as an Authorization: Bearer header. On a 429 it sleeps for the Retry-After seconds and tries again. Each response is passed to SQL as one bound JSON string: FLATTEN turns the county rows into a MERGE source, and the GeoJSON features are written with INSERT OVERWRITE, which clears and reloads the table in one statement. TRY_TO_GEOGRAPHY stores NULL instead of failing the whole load if a utility reports a shape Snowflake cannot parse.

sql
CREATE OR REPLACE PROCEDURE load_poweroutage(state_ids STRING)
  RETURNS STRING
  LANGUAGE PYTHON
  RUNTIME_VERSION = '3.12'
  PACKAGES = ('snowflake-snowpark-python', 'requests')
  HANDLER = 'run'
  EXTERNAL_ACCESS_INTEGRATIONS = (poweroutage_access)
  SECRETS = ('api_key' = poweroutage_api_key)
AS
$$
import json
import time

import requests
from snowflake.snowpark import secrets

MERGE_COUNTIES = """
MERGE INTO county_outages t
USING (
  SELECT
    c.value:id::NUMBER AS county_id,
    c.value:name::STRING AS county_name,
    c.value:stateId::NUMBER AS state_id,
    c.value:fips:full::STRING AS fips,
    c.value:customersOut::NUMBER AS customers_out,
    c.value:customersTracked::NUMBER AS customers_tracked,
    c.value:lastUpdatedAt::TIMESTAMP_TZ AS last_updated_at,
    r.payload:meta:generatedAt::TIMESTAMP_TZ AS generated_at
  FROM (SELECT PARSE_JSON(?) AS payload) r,
    LATERAL FLATTEN(INPUT => r.payload:data) c
) s
ON t.county_id = s.county_id
WHEN MATCHED THEN UPDATE SET
  customers_out = s.customers_out,
  customers_tracked = s.customers_tracked,
  last_updated_at = s.last_updated_at,
  generated_at = s.generated_at
WHEN NOT MATCHED THEN INSERT
  (county_id, county_name, state_id, fips, customers_out, customers_tracked, last_updated_at, generated_at)
  VALUES (s.county_id, s.county_name, s.state_id, s.fips, s.customers_out, s.customers_tracked,
          s.last_updated_at, s.generated_at)
"""

LOAD_OUTAGES = """
INSERT OVERWRITE INTO active_outages
SELECT
  f.value:properties:utilityId::NUMBER,
  f.value:properties:outageId::STRING,
  f.value:properties:customersOut::NUMBER,
  f.value:properties:cause::STRING,
  f.value:properties:estimatedRestorationAt::TIMESTAMP_TZ,
  TRY_TO_GEOGRAPHY(f.value:geometry),
  r.payload:meta:generatedAt::TIMESTAMP_TZ
FROM (SELECT PARSE_JSON(?) AS payload) r,
  LATERAL FLATTEN(INPUT => r.payload:features) f
"""


def get(url, params):
    headers = {'Authorization': 'Bearer ' + secrets.get_generic_secret_string('api_key')}
    for _ in range(3):
        response = requests.get(url, params=params, headers=headers, timeout=60)
        if response.status_code != 429:
            response.raise_for_status()
            return response.json()
        time.sleep(int(response.headers.get('Retry-After', '10')))
    raise RuntimeError('Still rate limited after 3 tries: ' + url)


def run(session, state_ids):
    counties = get(
        'https://poweroutage.us/api/v2/outages/counties',
        {'stateId': state_ids, 'include': 'fips'},
    )
    session.sql(MERGE_COUNTIES, params=[json.dumps(counties)]).collect()

    outages = get('https://poweroutage.us/api/v2/geojson/outages', {'stateId': state_ids})
    session.sql(LOAD_OUTAGES, params=[json.dumps(outages)]).collect()

    return f"{counties['meta']['count']} counties, {outages['meta']['count']} outages"
$$;

Step 4: Run it once, then schedule it with a task

Call the procedure by hand first; it returns how many counties and outages it loaded. stateId accepts a comma-separated list, so one call can cover a whole region. Then create a task on a 15-minute schedule and resume it. The data updates every minute, so a 1- or 2-minute schedule gets the latest numbers, at a higher warehouse cost.

sql
-- 44 is Florida and 45 is Georgia. List ids with GET /outages/states.
CALL load_poweroutage('44,45');

CREATE OR REPLACE TASK refresh_poweroutage
  WAREHOUSE = transform_wh
  SCHEDULE = '15 MINUTES'
AS
  CALL load_poweroutage('44,45');

-- Tasks are created suspended.
ALTER TASK refresh_poweroutage RESUME;

Step 5: Query outages next to your own data

Percentage out is customers_out divided by customers_tracked. The gap between last_updated_at and generated_at shows how long ago each county was last reported; a county with a NULL last_updated_at has no reporting utility. ST_MAKEPOINT takes longitude first. Outages that a utility reports as a single point have no area, so ST_CONTAINS will not match them; use ST_DWITHIN with a distance in meters for those, or the /geojson/at-point endpoint for an exact site check.

sql
-- Counties with the most customers out, and how long since a utility reported
SELECT county_name,
       customers_out,
       customers_tracked,
       ROUND(100 * customers_out / NULLIF(customers_tracked, 0), 2) AS pct_out,
       DATEDIFF(minute, last_updated_at, generated_at) AS minutes_since_report
FROM county_outages
ORDER BY customers_out DESC
LIMIT 20;

-- Your sites that sit inside an outage polygon right now
SELECT s.site_name, o.utility_id, o.outage_id, o.customers_out, o.estimated_restoration_at
FROM sites s
JOIN active_outages o
  ON ST_CONTAINS(o.shape, ST_MAKEPOINT(s.longitude, s.latitude));

Tips for Snowflake

  • Snowflake does not enable external access on trial accounts by default. Ask your Snowflake account team to turn it on before you start.
  • Leave out WAREHOUSE in CREATE TASK to make it a serverless task, which suits a short job that runs 96 times a day. The owning role then also needs EXECUTE MANAGED TASK.
  • Check runs with SELECT * FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY(TASK_NAME => 'REFRESH_POWEROUTAGE')). A failed run shows the Python error, including any HTTP status from the API.
  • Each response is parsed into a single VARIANT, which has a size limit. Keep /geojson/outages filtered by stateId or minCustomersOut rather than loading every outage in the country in one call.
  • Each state can include a county named Unknown for customers a utility could not place in a county. Its fips is null, so it drops out of FIPS joins.
  • Run CREATE SECRET in a worksheet you do not save or share. To rotate the key, run CREATE OR ALTER SECRET with the new value; the procedure reads it on its next run, with no code change.

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.