You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ServiceNow能否添加调用外部REST API的关联CI查询属性?如何实现?

Can ServiceNow call external REST APIs for custom query attributes?

Absolutely! ServiceNow totally supports this kind of reverse integration—you can absolutely add a custom 'Associated CIs' query attribute in the Incident module that pulls results from your Java app's REST API whenever users search. Let me walk you through a practical, step-by-step way to set this up:

1. Build a Script Include to Handle External API Calls

First up, you’ll need a server-side script to safely call your Java app’s API—server-side is better here because it avoids CORS headaches and keeps your auth credentials secure.

Head over to System Definition > Script Includes and create a new Script Include:

  • Name: ExternalCISearchUtil
  • API Name: global.ExternalCISearchUtil
  • Check the Client callable box (so it can be triggered from UI scripts)
  • Paste in this script (adjust the endpoint, auth, and response parsing to match your Java app’s API):
var ExternalCISearchUtil = Class.create();
ExternalCISearchUtil.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    searchCIs: function() {
        var searchTerm = this.getParameter('sysparm_search_term');
        var request = new sn_ws.RESTMessageV2();
        
        // Replace with your Java app's REST API endpoint
        request.setEndpoint('https://your-java-app-domain/api/cis/search');
        request.setHttpMethod('GET');
        
        // Add any required auth headers (e.g., API key, OAuth token)
        request.setRequestHeader('Authorization', 'Bearer YOUR_SECURE_TOKEN');
        request.setRequestHeader('Content-Type', 'application/json');
        
        // Pass the user's search term as a query parameter
        request.setQueryParameter('q', searchTerm);
        
        try {
            var response = request.execute();
            var responseBody = response.getBody();
            // Parse the API response and format it for ServiceNow's lookup UI
            var parsedCIs = JSON.parse(responseBody);
            var lookupResults = [];
            
            parsedCIs.forEach(function(ci) {
                lookupResults.push({
                    value: ci.unique_id, // Use the unique ID from your Java app
                    display_value: `${ci.name} (${ci.category})` // Friendly display text for users
                });
            });
            
            return JSON.stringify(lookupResults);
        } catch (ex) {
            gs.error(`Failed to fetch CIs from external API: ${ex.getMessage()}`);
            return JSON.stringify([]);
        }
    },
    type: 'ExternalCISearchUtil'
});

2. Create a UI Macro for the 'Associated CIs' Search Field

Next, you’ll build a UI macro to render the search input that triggers the API call. This gives you control over how the field looks and behaves.

Go to System UI > UI Macros and create a new macro:

  • Name: external_ci_lookup
  • Paste this XML content (tweak the field IDs if you plan to store the selected CI):
<?xml version="1.0" encoding="utf-8" ?>
<j:jelly trim="false" xmlns:j="jelly:core" xmlns:g="glide" xmlns:j2="null" xmlns:g2="null">
    <g:ui_reference id="associated_ci_search" 
                    name="associated_ci_search" 
                    onchange="updateSelectedCI()"
                    lookup="true"
                    completer="AJAXTableCompleter"
                    completerOptions="{
                        'table': 'dummy', // Placeholder table—we don't use a native ServiceNow table
                        'searchFields': 'name',
                        'displayField': 'name',
                        'valueField': 'sys_id',
                        'ajaxProcessor': 'global.ExternalCISearchUtil',
                        'ajaxMethod': 'searchCIs',
                        'minimumCharacters': 2 // Wait for 2+ characters before triggering the API
                    }" />
    <script>
        function updateSelectedCI() {
            // Optional: Store the selected CI's details in custom Incident fields
            var selectedValue = gel('associated_ci_search').value;
            var selectedDisplay = gel('associated_ci_search').getAttribute('displayValue');
            
            // Replace these with your custom field names if you created them
            gel('u_associated_ci_id').value = selectedValue;
            gel('u_associated_ci_name').value = selectedDisplay;
        }
    </script>
</j:jelly>

If you want to save the selected CI’s details to the Incident record, create custom fields first:

  • Go to System Definition > Tables, open the Incident table
  • Add two new string fields:
    • u_associated_ci_id: Stores the unique ID from your Java app
    • u_associated_ci_name: Stores the friendly display name of the CI

Then, add the UI macro to the Incident form:

  • Open any Incident record, right-click the form header > Configure > Form Layout
  • Find your external_ci_lookup macro in the "Available" list, add it to "Selected", and place it where you want the 'Associated CIs' field to appear.

4. Test the Integration

Open an Incident form, start typing in the new 'Associated CIs' field. ServiceNow will trigger your Script Include, call your Java app’s API, fetch matching CIs, and display them in a dropdown just like native ServiceNow fields.

Key Tips for Success

  • Security: Never hardcode credentials! Store auth tokens or API keys in Credential Records or System Properties, then retrieve them in your Script Include.
  • Error Handling: The script includes basic error handling, but you can expand it to handle timeouts, invalid responses, or rate limits from your Java app.
  • Performance: Add a minimum character threshold (like 2) to avoid spamming your API with every keystroke.

内容的提问来源于stack exchange,提问作者Jerry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:21:42