Scenario: You want to limit API calls/time interval based on message weight.
Steps:
1. Add an instance of Javascript and Quota respectively in Preflow for incoming request.
2. Create a Java Script to set Message weight based on call type. As GET call will consume less resources than POST, we will assign a message weight of 1 for GET and 2 for POST.
Code:
var callType = context.proxyRequest.method;
context.setVariable("messageWeight","1");
if(callType == 'POST')
{
context.setVariable("messageWeight","2");
}
3. Modify the code for JS policy.
Code:
<!-- this policy allows us to execute java script code during execution of an API Proxy -->
<Javascript async="false" continueOnError="false" enabled="true" timeLimit="200" xmlns='http://www.sap.com/apimgmt'>
<!-- contains the name of the main code file -->
<ResourceURL>jsc://setMessageWeight.js</ResourceURL>
</Javascript>
4. Modify the code for Quota policy
Code (Allow 4 calls/min. So, it will allow 4 calls/min for GET, 2 calls/min for POST.)
<Quota async="false" continueOnError="false" enabled="true" xmlns="http://www.sap.com/apimgmt">
<Identifier ref="request.queryparam.app"></Identifier>
<MessageWeight ref="messageWeight"></MessageWeight>
<Allow count="4"/>
<Interval>1</Interval>
<Distributed>true</Distributed>
<Synchronous>true</Synchronous>
<TimeUnit>minute</TimeUnit>
</Quota>
5. Test the API
In this case, during 5th GET call within a minute for the same client application, the below response is received.
No comments:
Post a Comment