Developer's Guide: Asynchronous REST API Calls via Business Rules in ServiceNow

BillMartin
Mega Sage

As a ServiceNow developer, you might need to integrate third-party REST APIs into your workflows. Making these calls asynchronously can enhance system performance by allowing other processes to run without waiting for the API response. This guide provides a detailed walkthrough on implementing asynchronous REST API calls using business rules in ServiceNow, tailored specifically for developers.

 

Step-by-Step Implementation

 

1. Create a REST Message

  1. Navigate to: System Web Services > Outbound > REST Message.
  2. Create a New REST Message:
  3. Define REST Message Function:
    • HTTP Method: POST (or GET, depending on API requirements).
    • Add required headers, query parameters, or request body as needed.

2. Create a Business Rule

Create a business rule that triggers after a record is inserted or updated, initiating the asynchronous API call.

  1. Navigate to: System Definition > Business Rules.
  2. Create a New Business Rule:
    • Name: Async API Call.
    • Table: Select the appropriate table (e.g., Incident).
    • When: After (ensures the record exists before the API call).
  3. Advanced Configuration:
    • Check: Advanced option to enable scripting.
    • Script: Use the following code in the script field:

(function executeRule(current, previous) {
     var recordId = current.sys_id.toString();

                    // Call the AsyncApiProcessor script include

                    var asyncProcessor = new AsyncApiProcessor();

                    var response = asyncProcessor.invokeApi(recordId);

                   // Log the response (optional)

                   gs.info("Response from AsyncApiProcessor: " + response);
})(current, previous);

 

3. Create a Script Include

The script include contains the logic for making the asynchronous API call using sn_ws.RESTMessageV2.

  1. Navigate to: System Definition > Script Includes.
  2. Create a New Script Include:
    • Name: AsyncApiProcessor.
    • API Name: AsyncApiProcessor (auto-filled).
    • Accessible From: All application scopes.
    • Client Callable: Checked.
  3. Script: Use the following code:

var AsyncApiProcessor = Class.create();
AsyncApiProcessor.prototype = Object.extendsObject(AbstractAjaxProcessor, {
              invokeApi: function() {
                   try {
                            var recordId = this.getParameter('sysparm_record_id');
                             var gr = new GlideRecord('incident'); // Replace 'incident' with your table if different
                             if (gr.get(recordId)) {
                                          var restMessage = new sn_ws.RESTMessageV2('Third Party API', 'default');

                                            // Set parameters as needed
                                           restMessage.setStringParameterNoEscape('parameter1', gr.short_description);

                                           restMessage.executeAsync();
                                           gs.info('Async REST API request sent: Record ID ' + recordId);
                                          return 'Request initiated successfully.';
                               }

                             else {
                                        gs.error('Record not found: ' + recordId);
                                      return 'Record not found.';
                              }
                      }

                     catch (e) {
                                  gs.error('Error in AsyncApiProcessor: ' + e.message);
                                  return 'Failed to initiate request.';
                       }
                },

                type: 'AsyncApiProcessor'
});

 

Notes for Developers:

 

  • Ensure that the Script Include extends AbstractAjaxProcessor to allow GlideAjax calls.
  • Replace 'incident' with the appropriate table name if you're not working with the Incident table.
  • Adjust the setStringParameterNoEscape method calls to match the parameters required by your API.

 

Testing the Integration

 

  1. Trigger the Business Rule: Create or update a record in the specified table.
  2. Verify Logs:
    • Navigate to System Logs > All.
    • Look for the gs.info messages confirming that the async request was sent.
  3. Check API Responses:
    • Monitor the third-party API endpoint to ensure it received the request.
    • Handle any responses or callbacks as necessary.

 

ServiceNow Rest-API Calls Best Practices

  1. Implement Robust Error Handling

    • Use try-catch blocks to handle exceptions.
    • Log errors using gs.error for easier troubleshooting.
  2. Secure Sensitive Data

    • Store API credentials using the Credentials module or Encrypted Text fields.
    • Avoid hardcoding sensitive information.
  3. Optimize Performance

    • Use executeAsync to prevent blocking threads.
    • Avoid unnecessary queries or processing within the business rule.
  4. Maintain Clean Code

    • Add comments to clarify complex logic.
    • Follow naming conventions for variables and functions.
  5. Handle API Limits and Throttling

    • Implement logic to handle HTTP 429 (Too Many Requests) responses.
    • Respect rate limits specified by the third-party API.

 

Want to See It in Action?

For a live demo of how to implement this process step-by-step, check out my video on my YouTube channel, TechTalk with Bill. Subscribe for more hands-on ServiceNow tutorials and demos!

Happy coding!

2 ACCEPTED SOLUTIONS

Thanks @Nick Parsons , well spotted 😊.

 

Appreciate in contributing to my post and verifying the correctness of the video 👌👍 

View solution in original post

Hi @James Fricker and @Nick Parsons ,

 

I have created this video to show a live demo of how scripts include works. Hope this helps 😊

 

View solution in original post

9 REPLIES 9

James Fricker
Tera Guru

Did you use AI to write this stuff? Because it's garbage.

Hi @James Fricker ,

 

Thank you for sharing your thoughts. I appreciate your feedback and would love to understand your perspective better. Could you elaborate on what specifically you found unhelpful or lacking in the content? Your insights could help me refine the answer and ensure it provides more value to the community.

If there's something I can clarify or improve, please let me know. I'm here to help!"

Hey @BillMartin - Main issue I see with this post is that you're saying to use make a "GlideAjax" call from the business rule - That won't work. GladAjax is a client side API and doesn't work on the server side. 

 

The video is good and accurate, but doesn't align with the content in this post.

Thanks @Nick Parsons , well spotted 😊.

 

Appreciate in contributing to my post and verifying the correctness of the video 👌👍