{{announcement.body}}
{{announcement.title}}

Enforcing MuleSoft Rate Limiting Policy Using API Manager API

DZone 's Guide to

Enforcing MuleSoft Rate Limiting Policy Using API Manager API

In this article, we discuss how to enforce a rate limiting policy using MuleSoft's API Manager API to better manage your API security.

· Integration Zone ·
Free Resource

Introduction

A Rate Limiting policy limits the number of requests an API accepts within a window of time. The API rejects requests that exceed the limit. You can configure multiple limits with window sizes ranging from milliseconds to years.

Generally, we configure the Rate Limiting policy from the AnyPoint Platform API Manager, but we can enforce Rate Limiting or any other Policy using API Manager API. MuleSoft provides a set of APIs that can be used to enforce policies in API Manager.

Configuring rate limiting policy

There are various attributes required to enforce a rate-limiting policy. So, we can configure the maximum number of requests needed to be processed in a particular time frame.

Applying the Rate Limiting Policy Using API Manager API

First, we need to identify which API can be used to apply the policies. So, MuleSoft provided a developer portal that can be used to fetch details about policies API.

https://anypoint.mulesoft.com/exchange/portals/anypoint-platform/f1e97bc6-315a-4490-82a7-23abe036327a.anypoint-platform/api-manager-api/minor/1.0/pages/Applying_a_policy/

API Manager API

Policies API Url

https://anypoint.mulesoft.com/apimanager/api/v1/organizations/{organizationId}/environments/{environmentId}/apis/{environmentApiId}/policies

We need to pass organizationId, environmentId, and apiId in the above URL as a URI parameter.

Fetching Organization Id

To fetch Organization Id, navigate to Access Management ⇒ Organization and click on your organization. It will open a pop-up window that will provide the OrganizationId. This can be used in the URI parameter of the policies API.

Getting Organization Id

Fetching Environment Id 

To fetch the Environment Id, navigate to Access Management ⇒ Environment and click on your environment (i.e. Sandbox). This will open a pop-up window. From there, we can get the environmentId in the URL. This can be used in the URI parameter of the policies API.

Getting environment Id

Fetching API Id

For fetching the API Id, navigate to the API Manager in the AnyPoint Platform and select the API that you need to apply the policy. From there, you can see the API Id.

Getting API Id

Now, we have the organizationId, environmentId, and apiId that needs to be passed to policies API as URI parameters.

We will also require an access token that needs to be passed in the Authorization header of the Policies API request.

Generating Access Token

MuleSoft provides a separate API for generating an access token. To do this, we need to pass the username and password in the body of our request.

You can use curl utility to generate the token.

Plain Text
 




xxxxxxxxxx
1


 
1
$ curl -H "Content-Type: application/json" -X POST -d '{"username":"<<Anypoint_Username>>","password":"<<Anypoint_Password>>"}' https://anypoint.mulesoft.com/accounts/login



Response

JSON
 




xxxxxxxxxx
1


 
1
{
2
"access_token": "0cf70dc0-1982-42b5-8140-836048c15ce8",
3
"token_type": "bearer",
4
"redirectUrl": "/home/"
5
}



Alternatively, you can use Postman to generate the token.

Generating token with Postmn

Applying the Policy Using API Manager API

First, we need to identify what attributes we need to pass for applying rate limiting policy.

Go to exchange and search for “Rate Limiting Policy Template”.

https://anypoint.mulesoft.com/exchange/68ef9520-24e9-4cf2-b2f5-620025690913/rate-limiting/

Assets provided by MuleSoft

 Click on “API Gateway Rate limiting policy template”. 

Downloading policy definition

Now, download the policy definition, which will download a yaml file that will provide all attribute details that we need to pass.

YAML
 




xxxxxxxxxx
1
42


 
1
id: rate-limiting
2
name: Rate limiting
3
supportedPoliciesVersions: '>=v1'
4
description: Specifies the maximum value for the number of messages processed per time period, and rejects any messages beyond the maximum. Applies rate limiting to all API calls, regardless of the source.
5
category: Quality of service
6
violationCategory: qos
7
type: system
8
resourceLevelSupported: true
9
standalone: true
10
requiredCharacteristics: []
11
providedCharacteristics:
12
  - Baseline Rate Limiting
13
configuration:
14
  - propertyName: keySelector
15
    name: Identifier
16
    description: "For each identifier value, the set of Limits defined in the policy will be enforced independently. I.e.: #[attributes.queryParams['identifier']]."
17
    type: expression
18
    optional: true
19
    allowMultiple: false
20
  - propertyName: rateLimits
21
    name: Limits
22
    description: Pairs of maximum quota allowed and time window.
23
    type: rateLimits
24
    optional: true
25
    allowMultiple: true
26
    defaultValue: [{}]
27
  - propertyName: clusterizable
28
    name: Clusterizable
29
    description: When using a clustered runtime with this flag enabled, configuration will be shared among all nodes.
30
    type: boolean
31
    optional: true
32
    defaultValue: true
33
    allowMultiple: false
34
  - propertyName: exposeHeaders
35
    name: Expose Headers
36
    description: |
37
        Defines if headers should be exposed in the response to the client. These headers are: x-ratelimit-remaining,
38
        x-ratelimit-limit and x-ratelimit-reset.
39
    type: boolean
40
    optional: true
41
    defaultValue: false
42
    allowMultiple: false



Now, you can use CURL to apply policy by calling the policies API.

Plain Text
 




xxxxxxxxxx
1
20


 
1
curl -X POST \
2
https://anypoint.mulesoft.com/apimanager/api/v1/organizations/:organizationId/environments/:environmentId/apis/:apiInstanceId/policies \
3
  -H 'authorization: Bearer 0cf70dc0-1982-42b5-8140-836048c15ce8 \
4
  -H 'content-type: application/json' \
5
  -d '{
6
   "configurationData":{
7
      "rateLimits":[
8
         {
9
            "timePeriodInMilliseconds":60000,
10
            "maximumRequests":100
11
         }
12
      ],
13
      "clusterizable":true,
14
      "exposeHeaders":false
15
   },
16
   "policyTemplateId":"rate-limiting",
17
   "assetId":"rate-limiting",
18
   "assetVersion":"1.3.3",
19
   "groupId":"68ef9520-24e9-4cf2-b2f5-620025690913"
20
}'


JSON
 




x
11


 
1
{
2
    "configurationData":{
3
        "rateLimits":[{"timePeriodInMilliseconds":60000,"maximumRequests":100}],
4
        "clusterizable":true,
5
        "exposeHeaders":false
6
    },
7
    "policyTemplateId":"rate-limiting",
8
    "assetId":"rate-limiting",
9
    "assetVersion":"1.3.3",
10
    "groupId":"68ef9520-24e9-4cf2-b2f5-620025690913"
11
}



You need to pass organizationId, environmentId, and apiId that we have fetched above. Currently, we have a placeholder in the curl policies API.

You can use Postman to call the policies API.

Calling policies API with Postman



This is a very useful utility when you need to apply policies via CI/CD, and now you know how to apply rate-limiting policy using the API Manager API!

Topics:
mulesoft

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}