Power Outage Data in ServiceNow

To get power outage data into ServiceNow, create an Outbound REST Message that calls the PowerOutage.us v2 REST API with your key from a password2 system property, and run a Scheduled Script Execution every 15 minutes that sends the coordinates of your cmn_location records. When a location sits inside an active outage, the script opens an incident on that location, updates it while the outage changes, and resolves it when the outage no longer covers the location. Each incident carries the outage key in correlation_id, so later runs find it instead of opening a duplicate.

What you'll have

  • An incident on each location that sits inside an active outage, naming the utility, customers out, cause and estimated restoration.
  • One incident per outage and location: the job looks up correlation_id, built from utilityId and outageId, before it creates anything.
  • Work notes when an outage's numbers or restoration estimate change, and automatic resolution once the location is clear.
  • Up to 1,000 locations checked in 10 requests per run, with the API key stored encrypted in a system property.

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/at-pointPOSTChecks up to 100 locations per request and returns, in request order, the active outages covering each one and the utilities serving it.Standard + Locations

Step 1: Check roles, coordinates and network access

Setting this up needs the admin role: web_service_admin is enough for the REST Message, but system properties and scheduled jobs are admin-only. The job runs as the user in its Run as field, so pick an integration user that can read cmn_location and create and update incidents, which the itil role allows. Your locations need values in Latitude and Longitude; ServiceNow fills them only when geocoding is set up, so check those columns in the Locations list first. The instance calls poweroutage.us over public HTTPS, so no MID Server is needed. /geojson/at-point is in the Standard + Locations package.

Step 2: Store the key in a password2 system property

Type sys_properties.list in the filter navigator and select New. Name the property poweroutage.api_key, set Type to password2, paste your API key into Value, and save. ServiceNow stores password2 values encrypted, and gs.getProperty returns the key to server-side scripts, so it never appears in the REST Message or the script.

Step 3: Create the Outbound REST Message

Create the REST Message and one HTTP Method with these values. The Authorization header uses the ${api_key} variable, which the script fills from the system property on each run. Keep Authentication type at No authentication: the header carries the key, and the API takes neither Basic nor OAuth. Leave the method's Content empty, because the script sets the body.

text
REST Message (System Web Services > Outbound > REST Message > New)
  Name:                 PowerOutage.us
  Endpoint:             https://poweroutage.us/api/v2/geojson/at-point
  Authentication type:  No authentication

HTTP Method (HTTP Methods related list > New)
  Name:                 Outages at points
  HTTP method:          POST
  Endpoint:             https://poweroutage.us/api/v2/geojson/at-point
  HTTP Request tab, HTTP Headers:
    Authorization       Bearer ${api_key}
    Content-Type        application/json
  Variable Substitutions related list:
    api_key             (no test value; the script sets it)

Step 4: Write the scheduled script

This script reads every location with coordinates, sends them in batches of 100, and walks the results, which come back in the same order as the points. For each outage covering a location it looks for an open incident (New, In Progress or On Hold) with the same correlation_id and location, updates it if the details changed, or creates one. Afterwards it resolves open PowerOutage.us incidents whose outage no longer covers a location it checked. On a 429 or any other error it stops sending and skips resolution for the locations it didn't reach, so a failed request never closes an incident. Set RESOLUTION_CODE to a Resolution code value from your instance's incident close_code choices.

javascript
// Checks cmn_location coordinates against live outages, then opens, updates
// and resolves incidents. Runs as a Scheduled Script Execution every 15 minutes.
var LOCATION_QUERY = 'latitudeISNOTEMPTY^longitudeISNOTEMPTY';
var POINTS_PER_REQUEST = 100; // the endpoint's maximum
var MAX_REQUESTS = 10; // the API allows 10 requests per 10 seconds
var RESOLUTION_CODE = 'Solution provided'; // a close_code value from your instance

function checkPoints(batch) {
	var request = new sn_ws.RESTMessageV2('PowerOutage.us', 'Outages at points');
	request.setStringParameterNoEscape('api_key', gs.getProperty('poweroutage.api_key'));
	request.setRequestBody(JSON.stringify({
		points: batch.map(function (loc) {
			return { lat: loc.lat, lon: loc.lon };
		})
	}));
	request.setHttpTimeout(30000);
	var response = request.execute();
	var status = response.getStatusCode();
	if (status == 429) {
		// A server script has no documented way to pause, so stop and let the next run retry.
		gs.warn('PowerOutage.us: rate limited, Retry-After ' + response.getHeader('Retry-After') + ' s');
		return null;
	}
	if (status != 200) {
		gs.error('PowerOutage.us: HTTP ' + status + ' ' + response.getErrorMessage());
		return null;
	}
	return JSON.parse(response.getBody()).data.points;
}

function utilityName(utilities, utilityId) {
	for (var i = 0; i < utilities.length; i++) {
		if (utilities[i].utilityId == utilityId) return utilities[i].name;
	}
	return 'Utility ' + utilityId;
}

function openOrUpdate(loc, outage, utility) {
	var key = 'poweroutage:' + outage.utilityId + ':' + outage.outageId;
	var details = utility +
		'. Customers out: ' + (outage.customersOut == null ? 'not reported' : outage.customersOut) +
		'. Cause: ' + (outage.cause || 'not reported') +
		'. Estimated restoration (UTC): ' + (outage.estimatedRestorationAt || 'not given') + '.';

	var inc = new GlideRecord('incident');
	inc.addQuery('correlation_id', key);
	inc.addQuery('location', loc.sysId);
	inc.addQuery('state', 'IN', '1,2,3'); // New, In Progress, On Hold
	inc.query();
	if (inc.next()) {
		if (inc.getValue('description') != details) {
			inc.setValue('description', details);
			inc.work_notes = 'PowerOutage.us update. ' + details;
			inc.update();
		}
		return key;
	}

	var created = new GlideRecord('incident');
	created.initialize();
	created.setValue('short_description', 'Power outage at ' + loc.name);
	created.setValue('description', details);
	created.setValue('location', loc.sysId);
	created.setValue('correlation_id', key);
	created.setValue('correlation_display', 'PowerOutage.us');
	created.setValue('impact', 2);
	created.setValue('urgency', 2);
	created.insert();
	return key;
}

var locations = [];
var gr = new GlideRecord('cmn_location');
gr.addEncodedQuery(LOCATION_QUERY);
gr.orderBy('sys_id');
gr.query();
while (gr.next()) {
	var lat = parseFloat(gr.getValue('latitude'));
	var lon = parseFloat(gr.getValue('longitude'));
	if (lat >= -90 && lat <= 90 && lon >= -180 && lon <= 180) {
		locations.push({ sysId: gr.getUniqueValue(), name: gr.getValue('name'), lat: lat, lon: lon });
	}
}
var limit = POINTS_PER_REQUEST * MAX_REQUESTS;
if (locations.length > limit) {
	gs.warn('PowerOutage.us: ' + locations.length + ' locations, checking the first ' + limit +
		'. Split LOCATION_QUERY across more jobs.');
	locations = locations.slice(0, limit);
}

var checked = {}; // location sys_ids that got an answer this run
var current = {}; // correlation_id + '|' + location sys_id still in an outage
for (var i = 0; i < locations.length; i += POINTS_PER_REQUEST) {
	var batch = locations.slice(i, i + POINTS_PER_REQUEST);
	var results = checkPoints(batch);
	if (!results) break; // unchecked locations keep their incidents until the next run
	for (var j = 0; j < batch.length; j++) {
		checked[batch[j].sysId] = true;
		var outages = results[j].outages; // results come back in request order
		for (var k = 0; k < outages.length; k++) {
			var utility = utilityName(results[j].utilities, outages[k].utilityId);
			current[openOrUpdate(batch[j], outages[k], utility) + '|' + batch[j].sysId] = true;
		}
	}
}

// Resolve incidents whose outage no longer covers a location checked this run.
var open = new GlideRecord('incident');
open.addQuery('correlation_id', 'STARTSWITH', 'poweroutage:');
open.addQuery('state', 'IN', '1,2,3');
open.query();
while (open.next()) {
	var locationId = open.getValue('location');
	if (!checked[locationId] || current[open.getValue('correlation_id') + '|' + locationId]) continue;
	open.setValue('state', 6); // Resolved
	open.setValue('close_code', RESOLUTION_CODE);
	open.setValue('close_notes', 'PowerOutage.us no longer reports this outage at the location.');
	open.update();
}
gs.info('PowerOutage.us: checked ' + Object.keys(checked).length + ' locations');

Step 5: Map the fields your instance requires

This is everything the script writes. The script sets fields directly, so form UI policies don't apply; if your process needs caller_id, category, assignment_group or other fields on every incident, add them where the script creates incidents. To narrow which locations are watched, extend LOCATION_QUERY with your own encoded query, such as a custom flag or a list of states.

text
incident field        value
short_description     Power outage at <location name>
description           <utility>. Customers out: <customersOut>. Cause: <cause>.
                      Estimated restoration (UTC): <estimatedRestorationAt>.
location              the cmn_location record
correlation_id        poweroutage:<utilityId>:<outageId>
correlation_display   PowerOutage.us
impact, urgency       2 (Medium)
work_notes            added when the description changes
state                 6 (Resolved) once the outage no longer covers the location
close_code            RESOLUTION_CODE from the script
close_notes           PowerOutage.us no longer reports this outage at the location.

Step 6: Run it every 15 minutes

Go to System Definition, Scheduled Jobs, select New, and choose Automatically run a script of your choosing. Name the job, set Run to Periodically with a Repeat interval of 15 minutes, paste the script into Run this script, and set Run as; if the field isn't on the form, add it with Configure Form Layout. Save, select Execute Now once, and look for the job's line in the system log. The data updates every minute, so a Repeat interval of 1 or 2 minutes gets the latest answers.

Tips for ServiceNow

  • One job checks up to 1,000 locations, which takes 10 requests, the whole rate limit for 10 seconds. For more, copy the job with a different LOCATION_QUERY, for example by state, and set its Starting time a minute after the first so the two never share the same 10 seconds.
  • A location whose utilities all have providesGeospatialData: false never gets an incident: those utilities report counts by area only, so the API cannot place an outage at a point. The utilities list in each result tells you which locations are affected.
  • Utilities sometimes report overlapping outages, so one location can get two incidents with different correlation_id values. If you want one incident per location, key on the location alone and list the outages in the description.
  • If your instance only allows outbound traffic through a MID Server, add request.setMIDServer('<your MID Server>') in checkPoints.
  • Use a separate API key for ServiceNow, restricted to the areas your locations are in, so other tools don't use up this job's rate limit and a leaked key exposes less.

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.