- Use Our Data
- Integrations
- Databricks
Power Outage Data in Databricks
To get power outage data into Databricks, call the PowerOutage.us v2 REST API from a notebook, read the API key from a secret scope with dbutils.secrets.get, and write the results to Delta tables in Unity Catalog. Schedule the notebook as a Job every 15 minutes and you have a current snapshot for dashboards, a history table for trend analysis, and outage shapes you can turn into GEOMETRY values with Databricks spatial SQL. The code below runs on serverless or classic compute.
What you'll have
- A
county_outagesDelta table with customers out and customers tracked for every US county, replaced on each run. - A
county_outages_historytable that grows by one row per county per run, for peaks, trends and storm reviews. - An
active_outagestable with each outage as GeoJSON text, ready forst_geomfromgeojson. - A Job that refreshes all three every 15 minutes, with the key kept in a secret scope.
What you need
An API key (request one with the form below) and these endpoints. Full details are in the API reference.
| Endpoint | Method | Used for | Package |
|---|---|---|---|
/outages/counties | GET | Every county in one call: customersOut, customersTracked and lastUpdatedAt, with include=fips for joins. | Core |
/geojson/outages | GET | Active outages as GeoJSON features, filtered with minCustomersOut. | Standard |
Step 1: Store the key in a secret scope
Create a workspace secret scope and add the key with the Databricks CLI. Without a value flag, put-secret prompts for the value, so the key stays out of your shell history. Grant READ on the scope to the user or service principal the Job will run as. Notebooks then read it with dbutils.secrets.get, and Databricks shows [REDACTED] if the value is printed in cell output.
databricks secrets create-scope poweroutage
databricks secrets put-secret poweroutage api-key # paste the key when prompted
# Let the identity the job runs as read the scope
databricks secrets put-acl poweroutage data-jobs@example.com READ Step 2: Read the key and call the API from a notebook
Put this in the first cell. It reads the key from the scope and sends it as an Authorization: Bearer header; the API does not accept it in the URL. The API allows 10 requests per 10 seconds, and on a 429 the helper waits for the Retry-After seconds before trying again. Set SCHEMA to a catalog and schema you can create tables in.
import json
import time
import requests
from pyspark.sql import functions as F
API_KEY = dbutils.secrets.get(scope='poweroutage', key='api-key')
SCHEMA = 'main.poweroutage' # catalog.schema the tables are written to
def get_json(url, params):
"""GET a PowerOutage.us endpoint, waiting out a 429 for as long as Retry-After says."""
for _ 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()
time.sleep(int(response.headers.get('Retry-After', '10')))
raise RuntimeError(f'Still rate limited after 3 tries: {url}') Step 3: Write county counts to Delta
Without a stateId, /outages/counties returns every US county in one response, about 3,300 rows, so there is no pagination to handle. The rows become a Spark DataFrame with an explicit schema, timestamps are parsed from ISO 8601, and meta.generatedAt is stamped on every row. The snapshot table is overwritten, which Delta does atomically and keeps in table history; the history table is appended to.
payload = get_json('https://poweroutage.us/api/v2/outages/counties', {'include': 'fips'})
rows = [
(
c['id'], c['name'], c['stateId'], (c['fips'] or {}).get('full'),
c['customersOut'], c['customersTracked'], c['lastUpdatedAt'],
)
for c in payload['data']
]
counties = (
spark.createDataFrame(
rows,
'county_id BIGINT, county_name STRING, state_id BIGINT, fips STRING, '
'customers_out BIGINT, customers_tracked BIGINT, last_updated_at STRING',
)
.withColumn('last_updated_at', F.to_timestamp('last_updated_at'))
.withColumn('generated_at', F.to_timestamp(F.lit(payload['meta']['generatedAt'])))
)
# Latest snapshot: every county, replaced on each run
counties.write.mode('overwrite').saveAsTable(f'{SCHEMA}.county_outages')
# History: one row per county per run, for trends and storm peaks
counties.write.mode('append').saveAsTable(f'{SCHEMA}.county_outages_history') Step 4: Write outage shapes to Delta
/geojson/outages returns a FeatureCollection. Each feature becomes one row, with its geometry kept as GeoJSON text so the table works on any runtime. Track an outage across runs by utility_id plus outage_id; the feature id changes on every refresh. cause and estimated_restoration_at come from the utility and are often null.
collection = get_json(
'https://poweroutage.us/api/v2/geojson/outages', {'minCustomersOut': 10}
)
rows = [
(
f['properties']['utilityId'], f['properties']['outageId'],
f['properties']['customersOut'], f['properties']['cause'],
f['properties']['estimatedRestorationAt'], json.dumps(f['geometry']),
)
for f in collection['features']
]
outages = (
spark.createDataFrame(
rows,
'utility_id BIGINT, outage_id STRING, customers_out BIGINT, cause STRING, '
'estimated_restoration_at STRING, geometry_geojson STRING',
)
.withColumn('estimated_restoration_at', F.to_timestamp('estimated_restoration_at'))
.withColumn('generated_at', F.to_timestamp(F.lit(collection['meta']['generatedAt'])))
)
outages.write.mode('overwrite').saveAsTable(f'{SCHEMA}.active_outages') Step 5: Schedule the notebook as a Job
Create a Job with a Notebook task pointing at this notebook, on serverless compute or a small job cluster. Add a Scheduled trigger, choose Advanced, and enter the Quartz cron expression 0 0/15 * * * ? in UTC to run every 15 minutes. Leave maximum concurrent runs at 1, so a slow run is not overlapped by the next one, and add a failure notification so a bad key or a network block does not go unnoticed. Set the Job to run as the identity you granted READ on the scope.
Step 6: Query the tables
Use the tables from a SQL warehouse, a dashboard or another notebook. The gap between last_updated_at and generated_at shows how long ago each county was reported, and a null last_updated_at means no utility reports for it. On Databricks Runtime 17.1 and above, or a SQL warehouse that is not Classic, st_geomfromgeojson turns the stored GeoJSON into a GEOMETRY for spatial joins.
-- Counties with the most customers out, and minutes since a utility reported
SELECT county_name,
state_id,
customers_out,
customers_tracked,
round(100 * customers_out / nullif(customers_tracked, 0), 2) AS pct_out,
timestampdiff(MINUTE, last_updated_at, generated_at) AS minutes_since_report
FROM main.poweroutage.county_outages
ORDER BY customers_out DESC
LIMIT 20;
-- Peak customers out per county over the last 7 days
SELECT county_name, state_id, max(customers_out) AS peak_out
FROM main.poweroutage.county_outages_history
WHERE generated_at >= current_timestamp() - INTERVAL 7 DAYS
GROUP BY county_name, state_id
ORDER BY peak_out DESC
LIMIT 20;
-- Outage shapes as GEOMETRY (Databricks Runtime 17.1+ or a non-Classic SQL warehouse)
SELECT utility_id, outage_id, customers_out, st_geomfromgeojson(geometry_geojson) AS geom
FROM main.poweroutage.active_outages; Tips for Databricks
- If your workspace uses serverless egress control with restricted access, add
poweroutage.usto the network policy before running on serverless compute. On classic compute, allow outbound HTTPS to it from your workspace network. [REDACTED]in notebook output hides the literal key but is not access control. Limit who can read the scope with secret ACLs.- The history table grows by about 3,300 rows every run, around 300,000 a day. Partition or cluster it by date if you keep it for months, and filter on
generated_atin queries. - Each state can include a county named
Unknownfor customers a utility could not place in a county. Itsfipsis null. - There are no webhooks or streams to subscribe to, so Auto Loader and Structured Streaming do not apply. Polling on a Job schedule is the supported pattern.
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.