- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-11-2024 02:34 AM - edited 12-19-2024 10:38 PM
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
- Navigate to: System Web Services > Outbound > REST Message.
- Create a New REST Message:
- Name: Third Party API.
- Endpoint: https://api.thirdparty.com/resource (Replace with the actual API endpoint).
- 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.
- Navigate to: System Definition > Business Rules.
- 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).
- 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.
- Navigate to: System Definition > Script Includes.
- Create a New Script Include:
- Name: AsyncApiProcessor.
- API Name: AsyncApiProcessor (auto-filled).
- Accessible From: All application scopes.
- Client Callable: Checked.
- 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
- Trigger the Business Rule: Create or update a record in the specified table.
- Verify Logs:
- Navigate to System Logs > All.
- Look for the gs.info messages confirming that the async request was sent.
- 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
Implement Robust Error Handling
- Use try-catch blocks to handle exceptions.
- Log errors using gs.error for easier troubleshooting.
Secure Sensitive Data
- Store API credentials using the Credentials module or Encrypted Text fields.
- Avoid hardcoding sensitive information.
Optimize Performance
- Use executeAsync to prevent blocking threads.
- Avoid unnecessary queries or processing within the business rule.
Maintain Clean Code
- Add comments to clarify complex logic.
- Follow naming conventions for variables and functions.
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!
Solved! Go to Solution.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-19-2024 10:27 PM
Thanks @Nick Parsons , well spotted 😊.
Appreciate in contributing to my post and verifying the correctness of the video 👌👍
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-20-2024 12:57 AM
Hi @James Fricker and @Nick Parsons ,
I have created this video to show a live demo of how scripts include works. Hope this helps 😊
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-19-2024 03:14 PM
Did you use AI to write this stuff? Because it's garbage.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-19-2024 07:10 PM
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!"
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-19-2024 08:19 PM
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-19-2024 10:27 PM
Thanks @Nick Parsons , well spotted 😊.
Appreciate in contributing to my post and verifying the correctness of the video 👌👍