Help on REST API Rate Limit

venkatkk
Tera Contributor

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

Amit Gujarathi
Giga Sage
Giga Sage

HI @venkatkk ,
I trust you are doing great.

Here's a step-by-step solution:

Step 1: Create a Script Include

  1. Navigate to "System Definition" > "Script Includes" in the ServiceNow application.
  2. Click on "New" to create a new script include.
  3. Provide a name for the script include, such as "APIRateLimitControl".
  4. 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

  1. Go to "System Definition" > "Business Rules" in the ServiceNow application.
  2. Click on "New" to create a new business rule.
  3. Provide a name for the business rule, such as "API Rate Limit Control".
  4. Set the "Table" field to "Inbound REST API" or "ECC Queue" (depending on where you want to enforce rate limits).
  5. Choose the appropriate "When to run" and "Advanced" conditions based on your requirements.
  6. 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

  1. Modify the checkRateLimit function in the script include (APIRateLimitControl) to implement your rate limit logic.
  2. You can consider using counters, time-based checks, or any other custom logic to enforce the rate limits.
  3. Evaluate the incoming requests and determine if they are within the allowed limits.
  4. Return true if the request is within the rate limit, or false if it exceeds the limit.

Was this answer helpful?


Please consider marking it correct or helpful.


Your feedback helps us improve!


Thank you!


Regards,


Amit Gujrathi