⭐ Featured Article

OpenAPI Integration Framework

Published on January 13, 2026

OpenAPI Integration Framework is a ServiceNow scoped application that automates REST API integration by parsing OpenAPI specification endpoints. It generates structured operation templates with built-in JSON schema validation, eliminating the need to manually configure REST Message v2 records for each API endpoint.

Problem Statement

Integrating with external REST APIs in ServiceNow typically requires:

  • Manually creating REST Message v2 records for each endpoint
  • Configuring HTTP methods, paths, headers, and query parameters individually
  • Writing custom validation logic for request payloads
  • Maintaining documentation separately from the integration code

For APIs with dozens of endpoints, this process becomes repetitive and error-prone. Additionally, when API specifications change, updating each REST Message configuration manually is time-consuming and risks inconsistencies between the API contract and the ServiceNow integration.

What It Does

The OpenAPI Integration Framework consists of two primary components that work together to streamline REST API integration:

  • OpenApiProcessor: Fetches and parses OpenAPI specification JSON from a URL, automatically generating Specification and Operation records in ServiceNow tables
  • OpenApiRequestExecutor: Executes API calls using stored operation definitions, handling URL construction, parameter injection, payload validation, and authentication

Data Model

The application uses two custom tables to store API definitions:

  • Specification Table (x_650842_openapi_spec): Stores API-level metadata including name, version, and base URL
  • Operation Table (x_650842_openapi_operation): Stores individual endpoint definitions with HTTP method, path, headers, payload schema, query parameters, and path parameters

How It Works

Step 1: Processing an OpenAPI Specification

The OpenApiProcessor script fetches an OpenAPI JSON endpoint and automatically generates structured records:

var processor = new x_650842_openapi.OpenApiProcessor();
processor.processFromUrl('https://api.example.com/openapi.json');

This performs the following operations:

  1. Fetches the OpenAPI specification via RESTMessageV2
  2. Parses the JSON to extract API metadata (title, version, base URL)
  3. Creates or updates a Specification record
  4. Iterates through all paths and HTTP methods defined in the specification
  5. Generates Operation records for each endpoint with method, path, headers, payload schema, and parameter definitions

Step 2: Executing Operations

Once operations are generated, the OpenApiRequestExecutor uses them as templates for runtime execution:

var executor = new x_650842_openapi.OpenApiRequestExecutor();

var inputs = {
    pathParams: { user_id: "12345" },
    queryParams: { verbose: "true" },
    body: { name: "John Doe", email: "john@example.com" },
    authToken: "your_bearer_token_here"
};

var response = executor.executeOperation(
    'My API Specification',  // Spec name
    'get_user_by_id',        // Operation ID
    inputs
);

The executor handles:

  • Retrieving operation details from the database
  • Replacing path parameter placeholders (e.g., /users/{user_id} becomes /users/12345)
  • Applying query parameters to the URL
  • Setting headers (static from database plus runtime auth override)
  • Validating the request body against the stored JSON schema
  • Executing the REST request and returning structured response (status, body, error)

Payload Validation

The executor includes a lightweight JSON schema validator that runs before each request:

  • Required field validation: Ensures all fields marked as required in the schema are present in the payload
  • anyOf schema support: Validates that the payload matches at least one of the defined schema variations
  • Error handling: Throws descriptive errors listing missing fields or schema mismatches before the request is sent

This prevents malformed requests from reaching external APIs and provides immediate feedback during development.

Advanced Features

Multipart Form Data Support

For file uploads or multipart requests, the executor supports a special payload format:

var inputs = {
    pathParams: {},
    queryParams: {},
    body: {
        type: 'multipart_text_stream',
        content: 'File content here...',
        fileName: 'document.txt',
        contentType: 'text/plain'
    },
    authToken: "your_token"
};

var response = executor.executeOperation('API Name', 'upload_file', inputs);

The executor automatically constructs the multipart/form-data boundary, creates a temporary attachment, and cleans up after execution.

Dynamic Authentication

While headers can be stored in the Operation record, the authToken parameter allows runtime authentication injection. This is useful for:

  • User-specific API calls where each user has their own token
  • Integration with credential stores or vaults
  • Token refresh workflows where credentials change dynamically

Usage Example: Data Import

This example demonstrates retrieving user data from an external system using multiple operations in sequence:

var executor = new x_650842_openapi.OpenApiRequestExecutor();
var userList = [];

// Step 1: Get all users
var getAllInputs = {
    pathParams: {},
    queryParams: { verbose: "true" },
    body: {},
    authToken: instance.getValue('admin_api_key')
};

var allUsersResponse = executor.executeOperation(
    instance.getDisplayValue('openapi_spec'),
    "get_all_users_api_v1_users_all_get",
    getAllInputs
);

if (allUsersResponse.status === 200) {
    var userData = JSON.parse(allUsersResponse.body);
    
    // Step 2: Iterate and fetch details for each user
    for (var i = 0; i < userData.users.length; i++) {
        var userId = userData.users[i].id;
        
        var userDetailInputs = {
            pathParams: { user_id: userId },
            queryParams: { verbose: "true" },
            body: {},
            authToken: instance.getValue('admin_api_key')
        };
        
        var detailResponse = executor.executeOperation(
            instance.getDisplayValue('openapi_spec'),
            "get_user_by_id_api_v1_users__user_id__get",
            userDetailInputs
        );
        
        if (detailResponse.status === 200) {
            var userDetail = JSON.parse(detailResponse.body);
            userList.push(userDetail);
        }
    }
    
    // Process userList for import or transformation
}

Use Cases

  • Integrating with third-party SaaS platforms that expose OpenAPI specifications
  • Building data import scripts that pull from external REST APIs
  • Creating scheduled jobs that sync data between ServiceNow and external systems
  • Developing custom integrations in scoped applications without managing REST Message v2 complexity
  • Rapidly prototyping API integrations during proof-of-concept phases
  • Maintaining version-controlled API definitions that update automatically when specifications change

Benefits

  • Reduced configuration time: Generate dozens of operation templates from a single API specification URL
  • Built-in validation: Catch payload errors before requests are sent to external systems
  • Centralized management: Update base URLs or authentication headers in the Specification record without modifying scripts
  • Self-documenting: Operation records serve as live documentation of available endpoints and their parameters
  • Version control: Track API specification changes by reprocessing the OpenAPI endpoint

Data Model Reference

Specification Table Fields:

  • name - API specification title (unique identifier)
  • version - API version from the OpenAPI spec
  • base_url - Root URL for all operations (derived from servers or source URL)

Operation Table Fields:

  • api_specification - Reference to parent Specification record
  • operation_id - Unique identifier from OpenAPI (used for lookup during execution)
  • http_method - HTTP verb (GET, POST, PUT, DELETE, PATCH)
  • path - Endpoint path with parameter placeholders (e.g., /users/{user_id})
  • headers - JSON object of static headers
  • payload_schema - JSON schema for request body validation
  • query_parameters - JSON object defining available query parameters
  • path_parameters - JSON object defining path parameter requirements
  • summary - Human-readable description of the operation

Implementation Notes

The framework is designed as a scoped application (x_650842_openapi) and can be called from other scoped applications or global scope. Key implementation details:

  • Uses sn_ws.RESTMessageV2 for all HTTP requests (no dependency on predefined REST Messages)
  • Supports both standard JSON payloads and multipart/form-data uploads
  • Automatically cleans up temporary attachments created for multipart requests
  • Logs execution details using gs.info and gs.error for troubleshooting
  • Validates path parameter resolution and warns if placeholders remain unresolved

More Articles

Jan 09, 2026

MidCommand Script Include

Read More →