Skip to content
rest-integration logo

REST Integration Patterns for ServiceNow

rest-integration

Make outbound REST calls from ServiceNow with sn_ws.RESTMessageV2 — basic/bearer/OAuth/API-key auth, error handling by status code, response parsing, sys_rest_message records, and retry with exponential backoff.

SKILL.md

Full skill instructions

REST Integration Patterns for ServiceNow

ServiceNow provides RESTMessageV2 for outbound REST API calls and the REST API for inbound requests.

Outbound REST (Calling External APIs)

Basic GET Request

var request = new sn_ws.RESTMessageV2()
request.setEndpoint("https://api.example.com/​users")
request.setHttpMethod("GET")
request.setRequestHeader("Accept", "application/​json")

var response = request.execute()
var httpStatus = response.getStatusCode()
var body = response.getBody()

if (httpStatus == 200) {
  var data = JSON.parse(body)
  gs.info("Found " + data.length + " users")
}

POST Request with JSON Body

var request = new sn_ws.RESTMessageV2()
request.setEndpoint("https://api.example.com/​incidents")
request.setHttpMethod("POST")
request.setRequestHeader("Content-Type", "application/​json")
request.setRequestHeader("Accept", "application/​json")

var payload = {
  title: "New Incident",
  description: "Created from ServiceNow",
  priority: "high",
}
request.setRequestBody(JSON.stringify(payload))

var response = request.execute()

Using REST Message Records

Create a REST Message record for reusable integrations:

// Using predefined REST Message from sys_rest_message
var request = new sn_ws.RESTMessageV2("External API", "Create User")

// Set variable substitutions defined in the REST Message
request.setStringParameter("user_name", userName)
request.setStringParameter("email", email)

var response = request.execute()

Authentication Methods

Basic Authentication

var request = new sn_ws.RESTMessageV2()
request.setEndpoint("https://api.example.com/​data")
request.setHttpMethod("GET")
request.setBasicAuth("username", "password")

Bearer Token

var request = new sn_ws.RESTMessageV2()
request.setEndpoint("https://api.example.com/​data")
request.setHttpMethod("GET")
request.setRequestHeader("Authorization", "Bearer " + token)

OAuth 2.0 (Using OAuth Profile)

var request = new sn_ws.RESTMessageV2()
request.setEndpoint("https://api.example.com/​data")
request.setHttpMethod("GET")
request.setAuthenticationProfile("oauth2", "My OAuth Profile")

API Key

var request = new sn_ws.RESTMessageV2()
request.setEndpoint("https://api.example.com/​data")
request.setHttpMethod("GET")
request.setRequestHeader("X-API-Key", apiKey)
// Or as query parameter
request.setQueryParameter("api_key", apiKey)

Error Handling

try {
  var request = new sn_ws.RESTMessageV2()
  request.setEndpoint("https://api.example.com/​data")
  request.setHttpMethod("GET")
  request.setHttpTimeout(10000) // 10 second timeout

  var response = request.execute()
  var httpStatus = response.getStatusCode()

  if (httpStatus == 200) {
    var body = response.getBody()
    var data = JSON.parse(body)
    // Process successful response
  } else if (httpStatus == 401) {
    gs.error("Authentication failed")
  } else if (httpStatus == 404) {
    gs.error("Resource not found")
  } else if (httpStatus >= 500) {
    gs.error("Server error: " + httpStatus)
  } else {
    gs.error("Unexpected status: " + httpStatus)
  }
} catch (ex) {
  gs.error("REST Exception: " + ex.message)
}

Response Handling

Parse JSON Response

var body = response.getBody()
var data = JSON.parse(body)

// Access nested data
var userName = data.user.name
var items = data.items || []

Handle Arrays

var body = response.getBody()
var users = JSON.parse(body)

for (var i = 0; i < users.length; i++) {
  var user = users[i]
  gs.info("User: " + user.name + " (" + user.email + ")")
}

Response Headers

var contentType = response.getHeader("Content-Type")
var rateLimitRemaining = response.getHeader("X-RateLimit-Remaining")

MCP Tools for REST

// Create REST Message record
snow_create_rest_message({
  name: "External API",
  endpoint: "https://api.example.com",
  authentication: "basic", // or "oauth2", "api_key"
  methods: [
    {
      name: "Get Users",
      http_method: "GET",
      endpoint: "/​users",
    },
    {
      name: "Create User",
      http_method: "POST",
      endpoint: "/​users",
      content_type: "application/​json",
    },
  ],
})

// Test REST connection
snow_test_rest_connection({
  endpoint: "https://api.example.com/​health",
})

Best Practices

  1. Use REST Message records - Centralized configuration, easier maintenance
  2. Set timeouts - Prevent hanging scripts with setHttpTimeout()
  3. Handle all status codes - Not just 200
  4. Log failures - Use gs.error() for debugging
  5. Use Async for slow APIs - Don't block business rules
  6. Store credentials securely - Use Connection & Credential Aliases
  7. Implement retry logic - For transient failures
  8. Rate limit awareness - Check response headers, implement backoff

Retry Pattern

function callApiWithRetry(endpoint, maxRetries) {
  var retries = 0
  var delay = 1000 // Start with 1 second

  while (retries < maxRetries) {
    try {
      var request = new sn_ws.RESTMessageV2()
      request.setEndpoint(endpoint)
      request.setHttpMethod("GET")

      var response = request.execute()

      if (response.getStatusCode() == 200) {
        return JSON.parse(response.getBody())
      }

      if (response.getStatusCode() >= 500) {
        // Server error - retry
        retries++
        gs.sleep(delay)
        delay = delay * 2 // Exponential backoff
        continue
      }

      // Client error - don't retry
      throw new Error("Client error: " + response.getStatusCode())
    } catch (ex) {
      retries++
      if (retries >= maxRetries) {
        throw ex
      }
      gs.sleep(delay)
      delay = delay * 2
    }
  }
}

More Security skills

supabase logo
Security

supabase

Handles the full Supabase workflow from schema changes to deployment, with built-in security guardrails that catch common traps like RLS...

2.7K 308.9K
View

Comprehensive guides and best practices for Neon Serverless Postgres, covering setup, connection methods, authentication, and platform APIs.

98 216.2K
View

Guide for setting up and using Firebase Authentication. Use this skill when the user's app requires user sign-in, user management, or secure data access using auth rules.

462 163.8K
View

A skill to evaluate how secure Firestore security rules are. Use this when Firestore security rules are updated to ensure that the generated rules are extremely secure and robust.

462 127.7K
View

Official skill for integrating Firebase AI Logic (Gemini API) into web applications. Covers setup, multimodal inference, structured output, and security.

462 125.1K
View

Complete Better Auth server and client setup with database adapters, session management, plugins, and security configuration.

222 118.2K
View

Deploy and manage projects on Vercel using token-based authentication. Use when working with Vercel CLI using access tokens rather than interactive login — e.g. "deploy to vercel", "set up vercel", "add environment variables to vercel".

31.9K 116.1K
View
cloudflare logo
Security

cloudflare

Complete Cloudflare platform integration with decision trees for compute, storage, AI, networking, security, and infrastructure-as-code.

3K 110.7K
View

Run Azure compliance and security audits with azqr plus Key Vault expiration checks. Covers best-practice assessment, resource review, policy/compliance validation, and security posture checks. WHEN: compliance scan, security audit, BEFORE running azqr (compliance cli tool), Azure best practices, Key Vault expiration check, expired certificates, expiring secrets, orphaned resources, compliance assessment.

253 103K
View
gws-gmail logo
Security

gws-gmail

Send, read, and manage Gmail messages, drafts, labels, and account settings.

31.2K 78.9K
View

Comprehensive website auditing across 230+ rules in 21 categories including SEO, performance, security, and accessibility.

94 72.3K
View
gws-shared logo
Security

gws-shared

Shared authentication, CLI syntax, and output formatting patterns for gws Google Workspace commands.

31.2K 63.4K
View

Security AI tools

StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
GeoSpy logo
Security

GeoSpy

GeoSpy: Pricing, Features, FAQs, and Alternatives for AI Teams

Free
View

Detect AI-generated voices to protect against audio fraud.

Paid
View

Ensure Your Content's Originality with AI Plagiarism Checker

Freemium
View
Img Upscaler logo
Security

Img Upscaler

Upscale images by 400% without quality loss

Freemium
View
AICheatCheck logo
Security

AICheatCheck

Accurately Detect AI-Generated Content with TheChecker.AI

Free
View
D
Security

Detect GPT

Chrome extension that detects and flags AI-generated content

Free
View