Wednesday, November 25, 2026

ServiceNow Outbound REST Message Example: Pull SEC EDGAR Data into a Custom Table

 In this post I will show how to call a public market-data REST API from ServiceNow, parse the JSON, and store the values in a custom table. The example uses the SEC EDGAR company concept endpoint. It does not require an API key, which makes it a good lab for outbound REST Message, JSON parsing, and a scheduled upsert. The same pattern works for any JSON feed you want to keep inside the platform.

A common use case is a finance or IR team that wants official filing facts (assets, revenue, net income) next to a vendor or customer record, without someone pasting numbers into a spreadsheet every quarter.

What the SEC API gives you

The company concept API returns the history of a single US-GAAP tag for one company. The CIK must be 10 digits and zero-padded. For Apple's assets the URL looks like this:

https://data.sec.gov/api/xbrl/companyconcept/CIK0000320193/us-gaap/Assets.json

A shortened response looks like this:

{
  "cik": 320193,
  "taxonomy": "us-gaap",
  "tag": "Assets",
  "entityName": "Apple Inc.",
  "units": {
    "USD": [
      {
        "end": "2023-09-30",
        "val": 352583000000,
        "accn": "0000320193-23-000106",
        "fy": 2023,
        "fp": "FY",
        "form": "10-K",
        "filed": "2023-11-03"
      }
    ]
  }
}

Two things are easy to miss. First, the SEC will return HTTP 403 unless you send a User-Agent header that identifies your application and a contact email, for example MyCompany contact@mycompany.com. Second, they ask that you stay under 10 requests per second. A nightly scheduled job that pulls a short ticker list is well within that limit. Do not put this call in a business rule that runs on every form load.

Not every company uses the same tag. Many filers now report revenue as RevenueFromContractWithCustomerExcludingAssessedTax instead of Revenues. If a call returns 404, try the other tag, or open the larger company facts document at /api/xbrl/companyfacts/CIK##########.json and see which keys exist under facts["us-gaap"].

Step 1: Create the custom table

Create a table, for example u_sec_company_fact, with these columns:

  • u_ticker — String (10)
  • u_cik — String (10)
  • u_company_name — String (100)
  • u_concept — String (100), for example Assets
  • u_unit — String (20), for example USD
  • u_period_end — Date
  • u_fiscal_year — Integer
  • u_fiscal_period — String (10), for example FY or Q2
  • u_form — String (10), for example 10-K
  • u_filed — Date
  • u_accession — String (25)
  • u_value — Decimal, with enough length for large totals (Apple's assets are in the 10^11 range). If your instance truncates the number, store it as a String instead.

Add a unique index on u_cik, u_concept, u_period_end, u_form and u_accession so a rerun updates the same row instead of inserting a duplicate. Grant the scheduled job user and the fulfillers who will read the list the right ACLs.

Step 2: Create the outbound REST Message

Go to System Web Services > Outbound > REST Message and create a new record.

  • Name: SEC EDGAR Company Concept
  • Endpoint: https://data.sec.gov/api/xbrl/companyconcept/CIK${cik_padded}/us-gaap/${concept}.json

Open the default GET HTTP method (or create one named getConcept) and confirm it inherits that endpoint. Under HTTP Request, add two headers:

  • User-Agent — ${user_agent}
  • Accept — application/json

You do not need a MID Server unless the instance cannot reach the public internet. Save the record and use "Test" only after you have a valid User-Agent, a 10-digit CIK and a concept name. A 403 almost always means the User-Agent is missing or too generic (for example, a blank value or just "ServiceNow").

Create a system property, for example u.sec.edgar.user_agent, and put the User-Agent string there. Do not hard-code the email in every script.

Optional but useful: a second REST Message named SEC EDGAR Company Tickers with endpoint https://www.sec.gov/files/company_tickers.json and the same User-Agent header. That file maps ticker symbols to CIKs so callers can pass AAPL instead of 0000320193.

Step 3: Script Include to call the API and upsert rows

The Script Include below is written for a global or scoped application. In a scoped app, make sure the application has access to sn_ws.RESTMessageV2. I use JSON.parse, which works on current releases. On older instances you can replace it with new JSON().decode(body) or new JSONParser().parse(body), as I have used in earlier posts on this blog.

var SecEdgarFactsHelper = Class.create();
SecEdgarFactsHelper.prototype = {
    initialize: function() {
        this.userAgent = gs.getProperty('u.sec.edgar.user_agent', '');
        this.tickers = null;
    },

    padCik: function(cik) {
        var s = String(cik || '');
        while (s.length < 10) {
            s = '0' + s;
        }
        return s;
    },

    loadTickerMap: function() {
        if (this.tickers) {
            return this.tickers;
        }
        var rm = new sn_ws.RESTMessageV2('SEC EDGAR Company Tickers', 'get');
        rm.setStringParameterNoEscape('user_agent', this.userAgent);
        var response = rm.execute();
        var status = response.getStatusCode();
        if (status != 200) {
            gs.error('SEC ticker list failed: HTTP ' + status + ' ' + response.getErrorMessage());
            this.tickers = {};
            return this.tickers;
        }
        var body = JSON.parse(response.getBody());
        var map = {};
        for (var key in body) {
            if (!body.hasOwnProperty(key)) {
                continue;
            }
            var row = body[key];
            map[String(row.ticker).toUpperCase()] = {
                cik: this.padCik(row.cik_str),
                name: row.title
            };
        }
        this.tickers = map;
        return map;
    },

    resolveTicker: function(ticker) {
        var map = this.loadTickerMap();
        return map[String(ticker).toUpperCase()] || null;
    },

    syncFacts: function(tickers, concept) {
        concept = concept || 'Assets';
        var results = [];
        for (var i = 0; i < tickers.length; i++) {
            results.push(this.syncOne(tickers[i], concept));
            // stay well under the SEC rate limit
            gs.sleep(200);
        }
        return results;
    },

    syncOne: function(ticker, concept) {
        var resolved = this.resolveTicker(ticker);
        if (!resolved) {
            gs.warn('No CIK found for ticker ' + ticker);
            return { ticker: ticker, status: 'unknown_ticker', upserted: 0 };
        }

        var rm = new sn_ws.RESTMessageV2('SEC EDGAR Company Concept', 'getConcept');
        rm.setStringParameterNoEscape('cik_padded', resolved.cik);
        rm.setStringParameterNoEscape('concept', concept);
        rm.setStringParameterNoEscape('user_agent', this.userAgent);

        var response = rm.execute();
        var status = response.getStatusCode();
        var bodyText = response.getBody();
        if (status != 200) {
            gs.error('SEC concept call failed for ' + ticker + ' ' + concept +
                ': HTTP ' + status + ' ' + response.getErrorMessage() +
                ' body=' + String(bodyText).substring(0, 300));
            return { ticker: ticker, status: status, upserted: 0 };
        }

        var body = JSON.parse(bodyText);
        var units = body.units || {};
        var unitName = units.USD ? 'USD' : Object.keys(units)[0];
        if (!unitName) {
            return { ticker: ticker, status: 'no_units', upserted: 0 };
        }
        var points = units[unitName] || [];
        var count = 0;
        for (var i = 0; i < points.length; i++) {
            if (this._upsertRow(ticker, resolved, body.entityName, concept, unitName, points[i])) {
                count++;
            }
        }
        return { ticker: ticker, status: 200, upserted: count };
    },

    _upsertRow: function(ticker, resolved, entityName, concept, unitName, point) {
        var gr = new GlideRecord('u_sec_company_fact');
        gr.addQuery('u_cik', resolved.cik);
        gr.addQuery('u_concept', concept);
        gr.addQuery('u_period_end', point.end);
        gr.addQuery('u_form', point.form || '');
        gr.addQuery('u_accession', point.accn || '');
        gr.query();
        var isUpdate = gr.next();
        if (!isUpdate) {
            gr.initialize();
            gr.u_cik = resolved.cik;
            gr.u_concept = concept;
            gr.u_period_end = point.end;
            gr.u_form = point.form || '';
            gr.u_accession = point.accn || '';
        }
        gr.u_ticker = String(ticker).toUpperCase();
        gr.u_company_name = entityName || resolved.name || '';
        gr.u_unit = unitName;
        gr.u_fiscal_year = point.fy || '';
        gr.u_fiscal_period = point.fp || '';
        gr.u_filed = point.filed || '';
        gr.u_value = point.val;
        isUpdate ? gr.update() : gr.insert();
        return true;
    },

    type: 'SecEdgarFactsHelper'
};

I keep the company name from the ticker file. You can also read body.entityName from the concept response if you prefer that source.

Step 4: Scheduled job

Create a Scheduled Script Execution that runs nightly, off business hours:

var helper = new SecEdgarFactsHelper();
var summary = helper.syncFacts(
    ['AAPL', 'MSFT', 'GOOGL', 'AMZN'],
    'Assets'
);
gs.info('SEC EDGAR fact sync: ' + JSON.stringify(summary));

Start with a short ticker list and one concept. Once that is stable, add a second job for another concept, or drive the list from a property or a simple tickers table. If you want only annual 10-K rows on a dashboard, filter u_form=10-K and u_fiscal_period=FY in the list or report. The API also returns quarterly values, and the same period can appear in more than one filing, which is why the unique key includes form and accession number.

The same idea — pull a public JSON feed on a schedule, keep a local copy, and let people look at the source values — shows up outside ServiceNow as well. I've been using a similar approach while building MarketCatalyst, an AI-powered market research terminal for traders and investors.

Step 5: Optional Flow Designer action

If you would rather not call the Script Include from a scheduled script, wrap it in a Flow Designer Action:

  1. Create an Action with two string inputs, ticker and concept, and an integer output, upserted.
  2. Add a Script step that instantiates SecEdgarFactsHelper, calls syncOne, and sets the output.
  3. Build a scheduled flow that loops through your ticker list and calls the Action. Put a short wait between iterations so you stay under the rate limit.

You can also use Flow Designer's REST step against the same REST Message. I still prefer the Script Include when I need upsert logic and consistent error logging.

Things that usually go wrong

  • HTTP 403. User-Agent is missing, empty, or does not include a contact address. Set it on the REST Message and pass it with setStringParameterNoEscape so nothing is encoded unexpectedly.
  • HTTP 404. The CIK is not zero-padded to 10 digits, or that company does not report the tag you asked for.
  • Empty table after a 200. The values may not be in units.USD. Log Object.keys(body.units) and persist the unit name you actually used.
  • Numbers look truncated. Switch u_value to a longer Decimal or a String, and do not use a Currency field for raw totals this large.
  • Scoped app errors on RESTMessageV2. Grant the application access to the REST Message records, or make the Script Include in the same scope as the REST Message.

Once the job has run, you can put a related list or a simple report on a company record, or expose the table to a Service Portal widget. The data is only as current as the last accepted filing, so treat it as a copy of official facts, not a live quote feed.

I'm Vinay Polisetti. I used to write these ServiceNow notes while implementing custom platform work, and I'm now building MarketCatalyst, an AI-powered market research terminal for traders and investors.

Thursday, September 29, 2022

ServiceNow script to retrieve oAuth token programatically

var instance = 'https://test.service-now.com';

var username = 'testadmin1'; 

var password = 'testadmin1'; 

var clientId = '539decb2e5968b00f5ac882d078e787d'; 

var clientSecret = 'test123'; 

  

// Request a token 

var getTokenRM = new sn_ws.RESTMessageV2(); 

getTokenRM.setEndpoint(instance + '/oauth_token.do'); 

getTokenRM.setHttpMethod("post"); 

getTokenRM.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 

getTokenRM.setRequestBody('grant_type=password&client_id=' + clientId + '&client_secret=' + clientSecret + '&username=' + username + '&password=' + password); 

var responseToken = getTokenRM.execute(); 

gs.print('response..'+ responseToken.getBody());

var token = new JSONParser().parse(responseToken.getBody()); 

Thursday, February 3, 2022

ServiceNow business rule to print the list of columns changed

For Global Scope Applications

 (function executeRule(current, previous /*null when async*/ ) {
    var gru = GlideScriptRecordUtil.get(current);
    var changedFields = gru.getChangedFields();
    var changedFieldNames = gru.getChangedFieldNames();

    //Convert to JavaScript Arrays
    gs.include('j2js');

    changedFields = j2js(changedFields);
    changedFieldNames = j2js(changedFieldNames);

    var arrayLength = changedFields.length;
    gs.log(arrayLength);


    for (var i = 0; i < arrayLength; i++) {
        gs.addErrorMessage(changedFields[i]);
    }

    var arrayLength1 = changedFieldNames.length;
    gs.log(arrayLength);

    for (var i = 0; i < arrayLength1; i++) {
        gs.addErrorMessage(changedFieldNames[i]);
    }
})(current, previous);

For Scoped application tables

 (function executeRule(current, previous /*null when async*/ ) {
    var result = [];
    var elements = current.getElements();
    var size = elements.length;
    for (var i = 0; i < size; i++) {
     var ge = elements[i];
     if (ge.changes()) {
      gs.addErrorMessage(ge.getName());
     }
    }
   })(current, previous);

Monday, January 10, 2022

ServiceNow backend script to wait for a few milliseconds

 function waitForTime(time){  

  var t1 = new GlideDateTime().getNumericValue();  

  var t2 = new GlideDateTime().getNumericValue();  

  var duration = t2 - t1;  

  while(duration < time){  

  t2 = new GlideDateTime().getNumericValue();  

  duration = t2 - t1;  

  }  

}

Wednesday, June 2, 2021

Parse attached CSV file in ServiceNow using script in UI Action

The following is a sample script to parse a CSV file in UI Action.


var gr = new GlideRecord('sys_attachment');

gr.addQuery("table_name", "incident");

gr.addQuery("table_sys_id", current.sys_id); // sys_id of attachment record

gr.query();


if (gr.next()) {

    var gsa = new GlideSysAttachment();

    var bytesInFile = gsa.getBytes('incident', current.sys_id);

    var fileContent = Packages.java.lang.String(bytesInFile); 

    gs.log("Contents of CSV:  " + fileContent);

    fileContent = String(fileContent);

    var delimiter = ',';

    var quoteChar = '"';


    var x = new sn_impex.CSVParser().parseLineToArray(fileContent, delimiter, quoteChar);

gs.log("line 0 content" + x[0]);

}

Thursday, July 25, 2019

Reset Button or Clear Values button widget to clear catalog item variable values

Step 1: Create a widget as shown below

Body HTML Template:


<button type="button" class="btn btn-danger btn-block" ng-click="c.setFieldValue(inputValue)">Reset Values</button>


Client Controller script


function($scope) {
var c = this;
c.setFieldValue = function(uploadname) {
var g_form = $scope.page.g_form;
g_form.clearValue("acrobat");
g_form.setValue("Additional_software_requirements", "");
g_form.setValue("test","");
g_form.setValue("photoshop", "");
};
}


Step-2: Create a variable of type Macro and in the default section give this widget name.

Thursday, June 27, 2019

ServiceNow parseInt() is returning NaN all the times

This is a common issue and the resolution is to pass both the parameters to the parseInt() method. It accepts the second parameter, which is the base

var testString = "10101"
var number = parseInt(testString, 10) + 100


The second parameter indicates that this integer has to be generated in base10

-------------------------------------------------------------------------------------------------------------
Are you looking to implement custom solutions in ServiceNow?

You are at the right place. Reach us at

Conyx IT Solutions | ServiceNow experts
partners@conyxit.com