Power Outage Data in Microsoft Fabric

To get power outage data into Microsoft Fabric, schedule a PySpark notebook that reads your PowerOutage.us API key from Azure Key Vault, calls the v2 REST API every 15 minutes, and overwrites two Delta tables in a Lakehouse. Power BI and the Lakehouse's SQL analytics endpoint read those tables directly. A notebook is the better route here than a Data Pipeline Copy activity: a Fabric REST connection has no setting for an API key header, so the Copy activity would keep the key in its Additional headers, inside the pipeline definition.

What you'll have

  • A county_outages Lakehouse table with customers out, customers tracked and the last report time for every county in the states you choose.
  • An active_outages table with each current outage, its cause and estimated restoration, longitude and latitude for point outages, and the shape as GeoJSON text.
  • An API key that stays in Azure Key Vault and is fetched at run time, never saved in the notebook or a pipeline.
  • A notebook schedule that refreshes both tables every 15 minutes, with email alerts when a scheduled run fails.

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 for one or more stateId values, with include=fips for joins to your own county data.Core
/geojson/outagesGETEvery active outage as a GeoJSON feature, flattened by the notebook into one row per outage.Standard

Step 1: Check capacity, roles and the vault

Notebooks and schedules need a workspace on a Fabric capacity, either an F SKU or a trial. You need the Contributor role or higher in the workspace to create the Lakehouse and notebook and to set the schedule. The key goes in an Azure Key Vault in your tenant, which must already exist. Notebooks can call public HTTPS endpoints such as poweroutage.us with no gateway. If the vault's firewall blocks public access, create a managed private endpoint to it from the workspace.

Step 2: Store the key in Azure Key Vault

To create the secret you need the Key Vault Secrets Officer role on the vault, or Set on secrets if the vault uses access policies; Owner or Key Vault Contributor alone doesn't give access to secrets. To grant the role below you need Owner, User Access Administrator or Key Vault Data Access Administrator on the vault. Create the secret, then give the person who will own the schedule the Key Vault Secrets User role on the vault, or Get on secrets if the vault uses access policies. notebookutils.credentials.getSecret authenticates as the user running the notebook, and a scheduled run runs as whoever created or last updated the schedule, so that person needs to be able to read the secret.

bash
# Paste the key at the prompt; nothing is echoed or kept in history
read -rs POWEROUTAGE_API_KEY
# Pass it in a file only you can read; --value would show it in the process list
( umask 077; printf '%s' "$POWEROUTAGE_API_KEY" > poweroutage-key.txt )
az keyvault secret set --vault-name outage-kv --name poweroutage-api-key \
  --file poweroutage-key.txt
rm poweroutage-key.txt
unset POWEROUTAGE_API_KEY

# The person who will own the notebook's schedule reads the secret at run time
az role assignment create --assignee data.engineer@example.com \
  --role "Key Vault Secrets User" \
  --scope "$(az keyvault show --name outage-kv --query id --output tsv)"

Step 3: Create a Lakehouse and a notebook

In the workspace, create a Lakehouse named outages, then a new notebook. In the notebook's explorer, add the outages Lakehouse and pin it as the default, so saveAsTable writes Delta tables into it. Keep the language at PySpark (Python). requests is already installed in the Fabric Spark runtime.

Step 4: Paste the notebook code

Put this in one cell and change the vault URL and STATE_IDS. The key goes in an Authorization: Bearer header, and on a 429 the code waits the Retry-After seconds before trying again. Each run overwrites both tables with the latest data. Rows are built with an explicit schema so a column that is null in every row still gets the right type, and the ISO 8601 timestamps from the API are converted with to_timestamp. Fabric redacts the secret if it is printed by mistake, but only on a best-effort basis, so never print API_KEY.

python
import json
import time

import requests
from pyspark.sql import functions as F

# Read as the user who runs the notebook, or who owns its schedule
API_KEY = notebookutils.credentials.getSecret(
    'https://outage-kv.vault.azure.net/', 'poweroutage-api-key'
)
# 44 is Florida and 45 is Georgia. List ids with GET /outages/states.
STATE_IDS = '44,45'


def get(url, params):
    """GET a PowerOutage.us endpoint, waiting out a 429 for as long as Retry-After says."""
    for attempt in range(3):
        response = requests.get(
            url, params=params, headers={'Authorization': f'Bearer {API_KEY}'}, timeout=60
        )
        if response.status_code != 429:
            response.raise_for_status()
            return response.json()
        if attempt < 2:
            time.sleep(int(response.headers.get('Retry-After', '10')))
    raise RuntimeError(f'Still rate limited after 3 tries: {url}')


def save(rows, schema, table, mode='overwrite'):
    """Write a Lakehouse table. Columns ending in _at arrive as ISO 8601 strings in UTC."""
    df = spark.createDataFrame(rows, schema)
    df = df.withColumns({c: F.to_timestamp(c) for c in df.columns if c.endswith('_at')})
    df.write.mode(mode).saveAsTable(table)


def outage_row(feature, generated_at):
    p, geometry = feature['properties'], feature['geometry']
    point = geometry['type'] == 'Point'
    return (
        p['utilityId'], p['outageId'], p['customersOut'], p['cause'],
        p['estimatedRestorationAt'], p['firstSeenAt'], geometry['type'],
        float(geometry['coordinates'][0]) if point else None,
        float(geometry['coordinates'][1]) if point else None,
        json.dumps(geometry), generated_at,
    )


counties = get(
    'https://poweroutage.us/api/v2/outages/counties', {'stateId': STATE_IDS, 'include': 'fips'}
)
save(
    [
        (c['id'], c['name'], c['stateId'], (c['fips'] or {}).get('full'), c['customersOut'],
         c['customersTracked'], c['lastUpdatedAt'], counties['meta']['generatedAt'])
        for c in counties['data']
    ],
    'county_id BIGINT, county_name STRING, state_id BIGINT, fips STRING, customers_out BIGINT, '
    'customers_tracked BIGINT, last_updated_at STRING, generated_at STRING',
    'county_outages',
)

outages = get('https://poweroutage.us/api/v2/geojson/outages', {'stateId': STATE_IDS})
save(
    [outage_row(f, outages['meta']['generatedAt']) for f in outages['features']],
    'utility_id BIGINT, outage_id STRING, customers_out BIGINT, cause STRING, '
    'estimated_restoration_at STRING, first_seen_at STRING, geometry_type STRING, '
    'longitude DOUBLE, latitude DOUBLE, geometry_geojson STRING, generated_at STRING',
    'active_outages',
)
print(f"{counties['meta']['count']} counties, {outages['meta']['count']} outages")

Step 5: Check the field mapping

These are the columns the notebook writes and the API fields they come from. Lakehouse tables have no geography type, so the shape is kept as GeoJSON text; point outages also get longitude and latitude columns that map visuals can use directly.

text
county_outages (from /outages/counties, one row per county)
  county_id           id
  county_name         name
  state_id            stateId
  fips                fips.full (null for Unknown counties and outside the US)
  customers_out       customersOut
  customers_tracked   customersTracked
  last_updated_at     lastUpdatedAt, as a timestamp
  generated_at        meta.generatedAt, as a timestamp

active_outages (from /geojson/outages, one row per outage)
  utility_id                 properties.utilityId
  outage_id                  properties.outageId
  customers_out              properties.customersOut (null when not reported)
  cause                      properties.cause
  estimated_restoration_at   properties.estimatedRestorationAt, as a timestamp
  first_seen_at              properties.firstSeenAt, as a timestamp
  geometry_type              geometry.type: Point, Polygon or MultiPolygon
  longitude, latitude        geometry.coordinates for points; null for polygons
  geometry_geojson           the geometry object as GeoJSON text
  generated_at               meta.generatedAt, as a timestamp

Step 6: Run it, then schedule it every 15 minutes

Select Run all and check that both tables appear under Tables in the Lakehouse. Then, in the workspace, open the notebook's menu and select Schedule. Turn the schedule on, choose a minute-based repeat every 15 minutes, set a start and end time, and add yourself under Failure notifications. The data updates every minute, so a 1- or 2-minute repeat gets the latest numbers, but every run starts a Spark session and uses capacity. Each run makes two API requests.

Step 7: Query the tables from the SQL analytics endpoint

Every Lakehouse has a SQL analytics endpoint that reads the Delta tables with T-SQL. The gap between last_updated_at and generated_at shows how long ago each county was reported; records are not zeroed when a utility stops reporting. Group by county_id or utility_id rather than by name, because names repeat across states.

sql
-- SQL analytics endpoint of the Lakehouse
SELECT TOP 20
    county_name,
    customers_out,
    customers_tracked,
    CAST(100.0 * customers_out / NULLIF(customers_tracked, 0) AS DECIMAL(5, 2)) AS pct_out,
    DATEDIFF(minute, last_updated_at, generated_at) AS minutes_since_report
FROM county_outages
ORDER BY customers_out DESC;

-- Customers out by utility, from outages with a location
SELECT utility_id, SUM(customers_out) AS customers_out, COUNT(*) AS outages
FROM active_outages
GROUP BY utility_id
ORDER BY customers_out DESC;

Tips for Microsoft Fabric

  • A schedule runs as the person who created or last updated it, and it expires if that person does not sign in to Fabric for 90 days. Have the account that should own the job save the schedule.
  • Fabric disables a schedule after a run of consecutive failures, typically 10. Failure notifications tell you before that happens; restart the schedule from the same pane once the cause is fixed.
  • Spark sessions on the starter pool usually start in seconds, but every scheduled run uses capacity units. Check the Fabric Capacity Metrics app after the first day of runs.
  • Each state can include a county named Unknown for customers a utility could not place in a county. Its fips is null.
  • /geojson/outages covers only utilities that publish outage locations, so county totals can be higher than the sum of customers_out in active_outages.

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.