> For the complete documentation index, see [llms.txt](https://docs.sharelogic.com/unifi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sharelogic.com/unifi/integration-guides/servicenow-table-api/table-api-supporting-data-pollers.md).

# Table API: Supporting Data Pollers

This guide explains how to configure and use the poller template to pull supporting data using ServiceNow Table API.

{% hint style="info" %}
For access to this template please contact us.
{% endhint %}

## Overview

This guide explains how to **configure and adapt reusable pollers** that **pull supporting data from a ServiceNow instance through the Table API**. The pattern is intended to minimise the changes required when adding additional supporting-data syncs.

{% hint style="warning" %}
\
This document and accompanying template are provided for general use only. Information may be incomplete, outdated, or inaccurate. No responsibility or liability is accepted for any use or reliance on its contents. Users should review and verify all information independently.
{% endhint %}

<table data-header-hidden data-search="false"><thead><tr><th>Item</th><th>Value</th></tr></thead><tbody><tr><td>Host System</td><td>ServiceNow with Unifi</td></tr><tr><td>Target System</td><td>ServiceNow without Unifi</td></tr><tr><td>Direction</td><td>Inbound</td></tr><tr><td>Sync method</td><td>Polling</td></tr><tr><td>Target API</td><td>ServiceNow Table API (latest)</td></tr></tbody></table>

### ServiceNow Table API

* This template uses the [ServiceNow Table API](https://www.servicenow.com/docs/r/api-reference/rest-apis/c_TableAPI.html) to retrieve records from the target instance.
  * Authentication can use a 'Web service access only' integration user with Basic authentication or OAuth 2.0, subject to the access configured on the target instance.
* The same polling principles can be adapted for other record types and, with further changes, other systems.

### Features

* Inbound synchronisation of selected target record attributes.
* Pagination and logging on inserts, updates and errors.

#### Limitations

* Polling requires separate pollers to sync relations to records, such as the `sys_user_grmember` of a `sys_user_group`.
* This polling pattern doesn't contain a function to facilitate mapping choices.
  * This logic may be added if required.

### Pre-Requisites

* Access to a ServiceNow instance and test environment with Table API enabled.
  * An **integration user** account on ServiceNow with sufficient access to the test environment.
* A ServiceNow development instance with **Unifi** installed.

## Implementation

The following describes the template configuration on ServiceNow and the steps to implement on the Unifi ServiceNow instance. Please review how this configuration should be translated to your own instance.

### Usage

1. **Import** and create a **new integration from** the **template**.
2. **Set up** integration users on both systems.
3. **Set up** a **connection** to the target system.
4. **Select** a **Poller** and click **'Execute Now'** to run the poller and review the outcome.
5. **Review** the **Code Overview** to decide on changes needed to adapt the integration to your instance.
6. **Copy** the **configured Pollers & Poll Processors** to your integration to **add supporting data syncs**.

### Create a new integration from the Template

**Import the integration**; for guidance, see the following: [Import the Integration (external instance)](https://docs.sharelogic.com/unifi/integration-guides/bidirectional-asynchronous-incident-guide/build-the-other-half/move-the-integration#import-the-integration-external-instance)\
Once imported, **open Unifi** and **navigate to the template** and **select** it; the option to create a **new integration from** the **template** will appear.\
**Name** the new integration and '**Create**'. This will duplicate all components of the integration and change their `sys_id`’s.

### Connection Setup

Two connections will need to be created, one connection to the customer's ServiceNow sandbox and another to production. Within each connection enter the following details:

**Details**

* **Environment:** Sandbox or Production
* **Direction:** Bi-directional

**Outbound**

* **Endpoint URL:** `https://changeme.service-now.com`
* **Authentication:** Basic or OAuth
* **User:** `{integrationuser@email.com}`
* **Password:** `{integrationUserPassword}`

**Inbound**

* **Inbound User:** `{Select user created in next section}`

#### **Account Setup**

Integration users need to be created on both ServiceNow instances; these are the user accounts the API uses to make changes on their respective systems.

**ServiceNow Unifi User (Inbound user)**\
An inbound user is required for the integration to make updates. For this we **create a ServiceNow user with the** [**`x_snd_eb.integration`**](https://docs.sharelogic.com/unifi/about/roles) **role**. All integrations within the same process share the same endpoint, so when data is sent inbound, the inbound user is used to identify which integration to target, requiring a unique user per integration in the process. **This user should then be set on the connection**.

**Table API ServiceNow User (Outbound user)**\
To connect to the other ServiceNow instance we need to create a `Web service access only` user with roles that allow access to `Table API` and `Attachment API`. This user should then be added to the Unifi instances' connection.<br>

## Included Pollers

| Poller (Poll processor) | Trigger           | Function                                                                                                  |
| ----------------------- | ----------------- | --------------------------------------------------------------------------------------------------------- |
| Pull Group Memberships  | Weekly/ On demand | Poller will create group memberships based on a given group or user sys\_id or the default query.         |
| Pull Groups             | Weekly            | Poller will create/update groups based on groups matching the query result from the other instance.       |
| Pull Locations          | Weekly            | Poller will create/update locations based on locations matching the query result from the other instance. |
| Pull Users              | Daily             | Poller will create/update users based on users matching the query result from the other instance.         |

## Code Overview

The standard poll processors follow three stages: Setup Script, Request Script and Response Script. Most adaptations should be limited to the documented configuration sections rather than the supporting functions.

The Poll Processors in this integration all use the same basic code with the exception of the 'Pull Group Memberships' Poller which uses the same supporting function with some modifications for flexibility. The code for Location sync is given below as an example for where changes may be needed.

### Setup Script

The setup script sets the endpoint including parameters used throughout the integration. ([More info](https://docs.sharelogic.com/unifi/~/changes/44/configure/polling/poll-processors#setup-script))\
The following variables should be updated:

* `params.pageSize`(Optional): Maximum records requested per page. A small value is useful while testing pagination; production values can be adjusted to suit the integration.
* `params.table`: The table the poller is polling. This only needs to be updated when re-using the code on a different table.
* `sysparm_query`: Sets the records to be returned by the poller. This is a standard ServiceNow query.

```javascript
(function (poll_request, poller, params) {
	
	// Configure the table and pagination settings for this poll.
	params.offset = params.offset || 0;
	params.pageSize = 10;
	params.table = "cmn_location";
	
	// Define the ServiceNow query used to identify records to sync.
	var sysparm_query = "sys_created_by=email@example.com";
	
	// Build the Table API query parameters.
	var qParams = [
		'sysparm_query='	+ encodeURIComponent(sysparm_query),
		'sysparm_limit='	+ params.pageSize,
		'sysparm_offset='	+ params.offset
	].join('&');
	
	// Build the endpoint URL for this page of records.
	poll_request.endpoint_url = poll_request.endpoint_url + 
		'/api/now/table/' + params.table + '?' + qParams;
		
})(poll_request, poller, params);
```

### Request Script

Builds and executes the API request using the connections configured authentication, then handles any response errors.\
This shouldn't need any updates for polling Table API unless connection authentication uses a MID server or other complication.

```javascript
// Process the request e.g. by executing a web service and returning the response
(function (poll_request, poller, connection, params) {
	var request, response;

	request = new sn_ws.RESTMessageV2();
	request.setHttpMethod('GET');
	request.setEndpoint(poll_request.endpoint_url);
	request.setRequestHeader('Content-Type', 'application/json');
	request.setRequestHeader('Accept', 'application/json');

	if (connection.useBasicAuth()) {
		console.debug('Using basic authentication');
		request.setBasicAuth(connection.getBasicAuthUser(), connection.getBasicAuthPassword());
	}

	else if (connection.useOAuth()) {
		console.debug('Using OAuth');
		request.setRequestorProfile('x_snd_eb_connection', connection.getValue('sys_id'));
		request.setAuthenticationProfile('oauth2', connection.getOAuthProfile());
	}
	
	response = request.execute();
	poll_request.response_code = response.getStatusCode();

	answer = response.getBody() + '';
	
	if (response.haveError()) {
		// Set response status to contain error
		poll_request.response_status = response.getErrorMessage();
		
		// Throw the error to error the poller
		throw '\nResponse Code: ' + response.getStatusCode() + ' \nResponse error: ' +
		response.getErrorMessage();
	}
})(poll_request, poller, connection, params);
```

### Response Script

The Response Script processes the records returned by the API. For each record, it maps the inbound data to the host table, checks whether a matching record already exists, and then inserts, updates or skips the record as appropriate. It also logs the outcome and manages pagination. Only the config section requires updating.

#### Script sections

* Config: Values designed to be changed when adapting the poller
* General: Shared runtime variables used for processing statistics..
* Runtime: Parses the response, processes each record and handles pagination.
* Supporting Functions: Reusable helpers used by the runtime logic. These should not normally need to be changed.

#### Config Values to Customise

* `correlation_field`: The field used to store the inbound record’s unique identifier.
* `inbound_identifier`: The inbound field containing the unique identifier to be stored in the correlation field.
* `fallback_identifier`: An optional directly mapped field used to find existing records without a correlation value. This helps prevent duplicate records when data has already been partially imported.
* `field_map`: Defines how inbound fields are mapped to the host's fields. Mapping functions such as `mapReference` can be used for more complex mappings.
* `field_values`: Defines fixed values applied to records processed by the integration, such as a shared company, domain or source.

{% hint style="info" %}
Reference mapping relies on the referenced record already being present and identifiable on the target instance. Depending on poll order, references may only populate on a later run.
{% endhint %}

#### Mapping Patterns

The response script supports three common mapping patterns:

```javascript
// Direct mapping  
name: "name"  
  
// Dot-walked inbound property  
some_field: "parent.value"  
  
// Function-based mapping, for example a reference lookup  
manager: mapReference("sys_user", correlation_field, "manager")
```

#### Supporting functions

These functions provide the reusable processing behaviour behind the template. They are documented to aid understanding but should not normally be edited when simply adapting a poller to another table.

**ensureRecord(table, query, data, field\_map, field\_values, fallback\_query)**

Finds the local record using the correlation query, optionally tries the fallback query, applies fixed and mapped values, and passes the result to updateAndLog.

**updateAndLog(grd)**

Checks whether the GlideRecord has changed, inserts or updates it when required, increments the processing counters and logs commit errors.

**getRecord(table, query)**

Returns a GlideRecord for the first record matching the encoded query. It first checks that the queried field exists; an invalid field returns the un-positioned GlideRecord rather than running an unsafe lookup.

**mapReference(table, ref\_field, ref\_prop)**

Creates a field-mapping function for references. It reads the inbound reference value, finds the corresponding host record using the configured reference field, and returns its sys\_id when found.

**dotWalk(data, splitPath)**

Reads a nested property from the inbound response one path segment at a time. If any segment is missing or is not an object, it returns undefined so the mapping can be skipped safely.

#### Record Matching Behaviour

* The correlation field is the primary identifier used on synchronisations.
* If no correlated record is found and `fallback_identifier` is configured, the poller attempts the fallback lookup.
  * Once matched through the fallback, the normal field map writes the inbound identifier into the correlation field for future runs.
* If neither lookup finds a record, a new GlideRecord is populated and inserted.
* Empty inbound values are skipped by the current template. Remove or alter that check only if the integration must clear host values.

#### Pagination

The Setup Script sends `sysparm_limit` and `sysparm_offset`. After each page, the Response Script can trigger another poll request with an increased offset. The next page continues until the returned page is shorter than the expected page size. **Keep the pagination settings consistent when modifying this behaviour**.

### Pull Group Memberships

This poller works slightly differently to the others pollers configured as above. As group memberships are group/user pairs no mapping is needed. Instead this poller is configured fully in the setups script here the `sys_user` and `sys_user_group` correlation fields may be set. The poller is configure to allow syncing of group memberships based on a query or all members of a group or all group memberships of a user. This allows the poller to be triggered as a sub-poller from the user or groups pollers depending on desired behaviour.

## Conclusion

With the above guidance, you should be able to configure a Supporting poll between Unifi and a ServiceNow instance using the Table API. If you encounter any difficulties, **please reach out to support**, and **we would be happy to help**.

***

## Change History

| Version | Date       | Changes          |
| ------- | ---------- | ---------------- |
| 1.0.0   | 2026-10-13 | Initial template |
