Help on REST API Rate Limit
Options
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-25-2023 11:40 PM
Can someone help me to understand how the rate limit works in Inbound REST API and where the code resides in. Basically require to design a custom framework for controlling the API consumed. I can't use the OOB feature since multiple consumers consuming same endpoints with the same API user account.
1 REPLY 1
Options
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-25-2023 11:46 PM
HI @venkatkk ,
I trust you are doing great.
Here's a step-by-step solution:
Step 1: Create a Script Include
- Navigate to "System Definition" > "Script Includes" in the ServiceNow application.
- Click on "New" to create a new script include.
- Provide a name for the script include, such as "APIRateLimitControl".
- Write the following code in the script include:
var APIRateLimitControl = Class.create();
APIRateLimitControl.prototype = {
initialize: function() {},
checkRateLimit: function(request) {
// Implement your rate limit logic here
// This function should return true if the request is within the allowed rate limit, or false otherwise
}
};
return new APIRateLimitControl();
Step 2: Create a Business Rule
- Go to "System Definition" > "Business Rules" in the ServiceNow application.
- Click on "New" to create a new business rule.
- Provide a name for the business rule, such as "API Rate Limit Control".
- Set the "Table" field to "Inbound REST API" or "ECC Queue" (depending on where you want to enforce rate limits).
- Choose the appropriate "When to run" and "Advanced" conditions based on your requirements.
- In the "Script" section, write the following code:
(function executeRule(current) {
var apiRateLimitControl = new APIRateLimitControl();
var request = current.request;
// Check the rate limit using the custom framework
var isWithinRateLimit = apiRateLimitControl.checkRateLimit(request);
if (!isWithinRateLimit) {
current.setAbortAction(true);
current.setReturnValues(responseCode, responseBody);
}
})(current);
Step 3: Implement Rate Limit Logic
- Modify the checkRateLimit function in the script include (APIRateLimitControl) to implement your rate limit logic.
- You can consider using counters, time-based checks, or any other custom logic to enforce the rate limits.
- Evaluate the incoming requests and determine if they are within the allowed limits.
- Return true if the request is within the rate limit, or false if it exceeds the limit.