Power Outage Data in QGIS

To get power outage data into QGIS, store your PowerOutage.us API key in an API Header authentication configuration, then run a short script in the Python Console that downloads active outages as GeoJSON and reloads two layers every 15 minutes. Utilities report some outages as points and others as polygons, so the script keeps one layer of each. The key stays in the QGIS authentication database, encrypted with your master password; the script and the project only hold the configuration's ID. The script was tested with QGIS 4.4 and uses only APIs that QGIS 3.44 LTR also has.

What you'll have

  • Two layers, Outage points and Outage polygons, with customers out, cause and estimated restoration for every active outage in the states you choose.
  • Layers that reload in place every 15 minutes, keeping your symbology, labels and filters.
  • An API key stored in the QGIS authentication database, never typed into a layer source, script or project file.
  • Plain GeoJSON files on disk that other tools, and a QGIS project reopened later, can read.

What you need

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

EndpointMethodUsed forPackage
/geojson/outagesGETEvery active outage as a GeoJSON feature, requested once with geometryType=point and once with geometryType=polygon so each layer holds one geometry type.Standard

Step 1: Store the key in an API Header authentication configuration

Open Settings > Options, go to the Authentication tab and add a new configuration. Choose the API Header method and add one header named Authorization whose value is Bearer followed by a space and your key. The first time you save anything here, QGIS asks you to set a master password, which encrypts the authentication database (qgis-auth.db in your profile folder). QGIS gives the configuration a random 7-character ID; copy it for the script.

text
Settings > Options > Authentication > Add a new authentication configuration (+)
  Name:            PowerOutage.us
  Method:          API Header
  Header Name:     Authorization
  Header Value:    Bearer <your API key>
Save, then copy the 7-character ID that QGIS assigns to the configuration.

Step 2: Paste the refresh script into the Python Console

Open Plugins > Python Console, select Show Editor and paste this script. Set AUTHCFG to your configuration's ID and STATE_IDS to your states. For each geometry type, the script requests /geojson/outages through QgsBlockingNetworkRequest, which adds the Authorization header from your configuration and uses QGIS's proxy settings. It writes the response to a GeoJSON file in ~/poweroutage, adds the layer the first time, and reloads it after that. On a 429 it schedules a retry of that request alone after the Retry-After seconds with QTimer.singleShot, so QGIS stays responsive while it waits. Any other error shows in the message bar and leaves that layer as it was; the other geometry type still updates.

python
import json
import os

from qgis.core import QgsBlockingNetworkRequest, QgsProject, QgsVectorLayer
from qgis.PyQt.QtCore import QTimer, QUrl
from qgis.PyQt.QtNetwork import QNetworkRequest

AUTHCFG = 'abc1234'  # the ID of your API Header configuration
# 44 is Florida and 45 is Georgia. List ids with GET /outages/states.
STATE_IDS = '44,45'
FOLDER = os.path.expanduser('~/poweroutage')
LAYERS = {'point': 'Outage points', 'polygon': 'Outage polygons'}


def update(kind, attempt=1):
    """Download one geometry type and reload its layer."""
    name = LAYERS[kind]
    request = QNetworkRequest(QUrl(
        f'https://poweroutage.us/api/v2/geojson/outages?stateId={STATE_IDS}&geometryType={kind}'
    ))
    client = QgsBlockingNetworkRequest()
    client.setAuthCfg(AUTHCFG)  # adds the Authorization header from the authentication database
    client.get(request, True)  # True skips QGIS's network cache
    reply = client.reply()
    status = reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute)
    if status == 429 and attempt < 3:
        wait = int(bytes(reply.rawHeader(b'Retry-After')) or b'10')
        QTimer.singleShot(wait * 1000, lambda: update(kind, attempt + 1))  # waits without freezing QGIS
        return
    if status != 200:
        iface.messageBar().pushWarning('PowerOutage.us', f'{name}: {client.errorMessage()}')
        return
    content = bytes(reply.content())
    path = os.path.join(FOLDER, f'outages_{kind}.geojson')
    with open(path, 'wb') as file:
        file.write(content)
    layers = QgsProject.instance().mapLayersByName(name)
    if layers:
        layers[0].reload()
        layers[0].triggerRepaint()
    elif json.loads(content)['meta']['count']:
        # A layer made from an empty file has no geometry type, so add it once there are outages
        QgsProject.instance().addMapLayer(QgsVectorLayer(path, name, 'ogr'))


def refresh():
    for kind in LAYERS:
        update(kind)  # a failure leaves that layer as it was and still updates the other


os.makedirs(FOLDER, exist_ok=True)
refresh()
timer = QTimer()
timer.timeout.connect(refresh)
timer.start(15 * 60 * 1000)  # every 15 minutes while QGIS is open

Step 3: Run it and check the attributes

Select Run script in the editor. Outage points and Outage polygons appear in the Layers panel once each has at least one outage, and the timer reloads them every 15 minutes while QGIS is open. These are the attributes each feature carries; times are UTC. The polygons layer can mix Polygon and MultiPolygon features, which QGIS draws together. To follow one outage between refreshes, use utilityId and outageId, never id.

text
Attribute                Type       Meaning
utilityId                Integer    Utility id, as listed by /outages/utilities
outageId                 String     The utility's own id for the outage
customersOut             Integer    Customers without power (null when not reported)
cause                    String     Cause as reported by the utility (often null)
estimatedRestorationAt   DateTime   When the utility expects power back, UTC
firstSeenAt              DateTime   When PowerOutage.us first saw the outage, UTC
recordedAt               DateTime   When this record was last read from the utility, UTC
id                       Integer    Row id within one response; changes every refresh

Step 4: Style the layers and find affected sites

In Layer Properties > Symbology, choose Graduated on customersOut to size or color outages by how many customers are affected. To list your sites inside an outage, use Vector > Research Tools > Select by Location with your sites layer and Outage polygons. Point outages have no area, so buffer your sites by a few hundred meters in a projected CRS before selecting against Outage points. Styles and filters survive each refresh, because the script reloads the same layers instead of replacing them.

Step 5: Keep it running

The timer lives in the Python Console session. Run timer.stop() to pause it. If you save the project, it reopens the layers from the GeoJSON files with the data from the last refresh; run the script again to resume updates. It finds the existing layers by name, so it reloads them rather than adding duplicates. Each refresh makes two API requests, well inside the limit of 10 requests per 10 seconds.

Tips for QGIS

  • Add &minCustomersOut=100, &countyId= or &utilityId= to the URL in the script to keep the layers focused on what you watch.
  • For county shading, /geojson/counties returns county boundaries with customersOut and customersTracked (use simplify to shrink the shapes). Download it the same way into a third file and style it with a graduated renderer on the expression CASE WHEN "customersTracked" > 0 THEN 100 * "customersOut" / "customersTracked" END, the percentage of customers out.
  • If several people need the same live layers, load the outages into PostGIS on a schedule and add the tables as PostGIS layers. Database layers can use Refresh layer at interval with Reload data, with no script in anyone's QGIS.
  • Your API Header configuration is local to your QGIS profile. If you share the script, each person creates their own configuration and sets AUTHCFG to its ID.
  • /geojson/outages covers only utilities that publish outage locations. A utility that reports counts by area only appears in /outages/counties, not on these layers.

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.