Nav

Anypoint MQ APIs

The Anypoint MQ APIs let you use REST to send and receive messages, administer queues and message exchanges, and analyze results. Anypoint provides these APIs, which are described later in this document:

Anypoint MQ portals are available in the Developer portal.

Get an Organization ID, Environment ID, and Bearer Token

After you get an application’s client ID and client secret from Anypoint Platform > MQ, you can run a curl command from a command line to get the bearer token, organization ID, and environment ID by using the Authorize resource. Once authorized, you can use the bearer token organization ID and environment ID in the rest of the calls.

To get API access information:

  1. Log into Anypoint Platform.

  2. Click MQ, Client Apps, and click the blue plus circle icon to create an app.

  3. Get the Client ID and Client Secret and plug these values into the curl command below replacing myclientId and myclientSecret:

    curl -X POST -H "Contentorm-urlencoded" -d 'client_id=<client_ID>&client_secret=<client_Secret>&grant_type=client_credentials' "https://mq-us-east-1.anypoint.mulesoft.com/api/v1/authorize"
  4. Submit the curl command.

    This returns output similar to:

    {"access_token":"<token>","simple_client":{"envId":"<env_ID>","orgId":"<org-ID>"},"token_type":"bearer"}

Two other ways to view the Organization ID:

From Your Anypoint Platform Profile JSON Listing

  1. Log into Anypoint Platform.

  2. Copy and paste this address into your browser’s address bar: https://anypoint.mulesoft.com/accounts/api/profile

  3. Scroll down to find the organization profile information.

    Line #4 shows your Organization ID value:

    "id": "42d0gf0g-4254-4254-4254-425442544254",

    For example:

    
                 
              
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    },
      "organization": {
        "name": "memyself.andi",
        "id": "42d0gf0g-4254-4254-4254-425442544254",
        "createdAt": "2014-10-27T23:35:41.369Z",
        "updatedAt": "2016-10-14T18:58:17.886Z",
        "ownerId": "42544254-4254-4254-4254-425442544254",
        "clientId": "42424242424242424242424242424242",
        "domain": "memyselfandi",
        "idprovider_id": "example",
        "isFederated": false,
        "parentOrganizationIds": [],
        "subOrganizationIds": [],
        "tenantOrganizationIds": [],
        "isMaster": true,
        "subscription": {
          "type": "RocketScientist",
          "expiration": null
        },

From Access Management

  1. View the Organization ID and Environment ID from Anypoint Platform by clicking Access Management and getting the ID values from the URLs in the Environments and Organization sections.

    Environment ID

    mq-envid-from-url

    Organization ID

    mq-get-orgid-from-url

API Workflow

The following example with the Broker API illustrates the workflow for accessing an API:

mq-api-workflow

Steps:

  1. An application sends a request to Anypoint MQ and sets how long to hold the lock on the message.

  2. Anypoint MQ sends the message and the lock ID.

  3. The application acknowledges the message and requests Anypoint MQ to delete the message, or the application negatively acknowledges the message and requests Anypoint MQ to make the message available to other applications. The application sends the message ID and lock ID to Anypoint MQ. For additional information on setting automatic ack or nack, see the Acknowledgement Mode guide.

  4. If no action is taken and the duration of the lock’s time to live expires, the message is negatively acknowledged and returns to the queue to be available for other applications.

API Access Examples

The following examples let you test Anypoint MQ from either the command line using the curl command, or from a combination of Postman, Anypoint Studio, and a browser.

Example: Command Line Using Curl

The examples in this section use the MQ Broker API to publish and consume messages. You need to substitute the placeholder string, 42544254-4254-4254-4254-425442544254 for the proper values for authorization and token strings. These examples use Postman to access the queue.

The following curl command publishes a message:


          
       
1
2
3
4
5
6
7
8
9
curl -X PUT -H "Content-Type: application/json" -H "Authorization: bearer 42544254-4254-4254-4254-425442544254" -H "Cache-Control: no-cache" -H "Postman-Token: 42544254-4254-4254-42544254-425442544254" -d '{
  "properties": {
    "userDefinedHeader": "User defined stuff",
    "anotherUserDefinedHeader": "Random stuff"
  },

  "body": "This is a message payload"
}
' "https://mq-us-east-1.anypoint.mulesoft.com/api/v1/organizations/42544254-4254-4254-4254-425442544254/environments/42544254-4254-4254-4254-425442544254/destinations/postmanExchange/messages/552"

The following curl command gets a message:


          
       
1
curl -X GET -H "Authorization: bearer 42544254-4254-4254-4254-425442544254" -H "Cache-Control: no-cache" -H "Postman-Token: 42544254-4254-4254-4254-425442544254" "https://mq-us-east-1.anypoint.mulesoft.com/api/v1/organizations/42544254-4254-4254-4254-425442544254/environments/42544254-4254-4254-4254-425442544254/destinations/postmanQueue/messages?poolingTime=10000&batchSize=1&lockTtl=10000"

Example: Postman, Studio, and Browser

This example lets you access the Anypoint MQ APIs from these products:

Postman Set Up

The Postman application provides a platform for accessing the Anypoint MQ APIs. After downloading and installing Postman, supply this information to create an environment:

After you are able to authorize to an Anypoint MQ API, publish a message, consume the message, and get the lock ID from the returned information in the Body.

For example, this information is returned from the consume (GET) command:


           
        
1
2
3
4
5
6
7
8
9
10
11
12
{
    "properties": {
      "anotherUserDefinedHeader": "Random stuff",
      "userDefinedHeader": "User defined stuff"
    },
    "headers": {
      "messageId": "514",
      "lockId": "<lockIDvalue>",
      "created": "Fri, 24 Jun 2016 21:17:57 GMT",
      "deliveryCount": "2"
    },
    ...

After you have the lock ID, you can add it to your Postman environment to facilitate future requests.

Anypoint Studio Set Up

Anypoint Studio lets you create a Mule application that uses the Anypoint MQ connector. The steps in this section are summarized. For more information, see the Anypoint Studio guide in the Anypoint MQ documentation set.

To set up Studio for use with Anypoint MQ:

  1. Use Anypoint Platform > MQ > Client Apps to get Client ID and Client Secret values.

  2. If you have not done so, download and install Anypoint Studio.

  3. Download the Anypoint MQ connector using Anypoint Exchange.

  4. Create a new Mule Project.

  5. Search for "http" and drag the HTTP connector to the Canvas.

  6. Click the Connector Configuration green plus icon to configure the connector.

  7. In the Global Element Properties window, click OK (take the default settings).

  8. Search for "mq" and drag the Anypoint MQ connector to the Canvas.

  9. Click the Connector Configuration green plus icon to configure the connector.

  10. In the Global Element Properties window, copy the Anypoint Platform > MQ > Client Apps > Client ID and Client Secret one at a time to the clipboard and then paste into Studio.

  11. Click OK to exit the Global Element Properties window.

  12. In the connector properties window, set Operation to consume.

  13. Set the Destination to the name of the queue you created in Postman.

  14. Search for "log" and drag the Logger to the Canvas. Set the Message to the #[payload] value.

  15. Right-click the project name in the Package Explorer window and click Run As > Mule Application.

  16. Ensure that the Console messages end with the "DEPLOYED" value.

Go back to Postman and publish a new message.

Browser Set Up

Browse to this address: 0.0.0.0:8081. The browser displays the message sent by Postman, which the Anypoint MQ connector received, and the HTTP connector sent to the browser.

Anypoint MQ Administration Portal

Administration API - Create and manage applications, queues, and message exchanges.

mq-rest-admin-portal

Create a FIFO Queue From the Administration Portal

You can create a FIFO queue from the Admistration portal by including the new "fifo": true field.

The organization from which you use the Administration portal must have an Anypoint MQ FIFO entitlement, and the only supported region for FIFO has the us-west-2 regionId value. If needed, see Get an Organization ID, Environment ID, and Bearer Token.

For the following path using the PUT operation:

/organizations/{organizationId}/environments/{environmentId}/regions/{regionId}/destinations/queues/{queueId}

Use this body:


          
       
1
2
3
4
5
6
{
  "defaultTtl" : 120000,
  "defaultLockTtl" : 10000,
  "encrypted" : false,
  "fifo" : true
}

Anypoint MQ Broker Portal

Broker API - Publish, consume, ack, and nack messages between queues and message exchanges.

mq-rest-broker-portal

Anypoint MQ Statistics Portal

Statistics API - Perform statistical analysis of queue performance.

mq-rest-statistics-portal

Scripting Example to Create Queues and Exchanges

To create queues and exchanges programatically, you can use a language such as groovy.

The following example consists of the cloudhub.properties file where you list the queues and exchanges to create, and a script file that references the properties file.

Command to Invoke

After modifying the properties file for access to your Anypoint Platform account, use this command to start the script file:

groovy <program_name>.groovy

Properties File

The following example properties file defines the access credentials, organization and environment IDs, region ID, and the names of the queues and exchanges to create:


          
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
username="<anypoint_platform_username>"
password="<anypoint_platform_password>"
organizationID="<organization_ID>"
environmentID {
    development="<development_environment_ID>"
    qa="<qa_environment_ID>"
    staging="<staging_environment_ID>"
    production="<production_environment_ID>"
}
regionID="us-east-1"

queues=[
    "Queue1",
    "Queue2",
    "QueueN",
]

exchanges=[
    "Exchange1",
    "Exchange2",
    "ExchangeN"
]

Script File

The following example script creates the queues and exchanges listed in the properties file.


          
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package guru.oso.mule

@Grab(group = 'org.apache.httpcomponents', module = 'httpclient', version = '4.5.3')

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.client.methods.HttpPut
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClientBuilder

class AnypointMQAdminClient {

  static String HOST = "https://anypoint.mulesoft.com"

    static void main(String[] args) {

        def props

        if (args) {
            props = new ConfigSlurper().parse(new File(args[0]).toURI().toURL())
        } else {
            props = new ConfigSlurper().parse(new File("cloudhub.properties").toURI().toURL())
        }

        def envID = props.environmentID.production

        def token = authenticate(props.username, props.password)

        retrieveDestinations(props, token, envID)

//        def creator = new AnypointMQCreator()
//        creator.createQueues(props, token, envID)
//        creator.createExchanges(props, token, envID)

    }

    static authenticate(String username, String password) {

      // build JSON
        def map = [:]
        map["username"] = username
        map["password"] = password
        def jsonBody = new JsonBuilder(map).toString()

        // build HTTP POST
        def url = HOST + '/accounts/login'
        def post = new HttpPost(url)

        post.addHeader("Content-Type", "application/json")
        post.setEntity(new StringEntity(jsonBody))

        // execute
        def client = HttpClientBuilder.create().build()
        def response = client.execute(post)

        // read and print response
        def bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
        def jsonResponse = bufferedReader.getText()
        println "response: \n" + jsonResponse

        // parse and return token
        def slurper = new JsonSlurper()
        def resultMap = slurper.parseText(jsonResponse)

        return resultMap["access_token"]

    }

    static retrieveDestinations(ConfigObject props, String token, String envID) {

        def orgID = props.organizationID
        def regionID = props.regionID

        // build HTTP GET
        def getDestinationsURL = HOST + '/mq/admin/api/v1/organizations/' + orgID + '/environments/' + envID + '/regions/' + regionID + '/destinations'
        def getDestinations = new HttpGet(getDestinationsURL)

        // set token
        getDestinations.setHeader("Authorization", "Bearer " + token)

        // execute
        def client = HttpClientBuilder.create().build()
        def response = client.execute(getDestinations)

        // parse and print results
        def bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
        def jsonResponse = bufferedReader.getText()
        println "response: \n" + jsonResponse

    }

    static retrieveQueue(ConfigObject props, String token, String envID, String queueID) {

        def orgID = props.organizationID
        def regionID = props.regionID

        // build HTTP GET
        def getQueueURL = HOST + '/mq/admin/api/v1/organizations/' + orgID + '/environments/' + envID + '/regions/' + regionID + '/destinations/queues/' + queueID
        def getQueue = new HttpGet(getQueueURL)

        // set token
        getQueue.addHeader("Authorization", "Bearer " + token)

        // execute
        def client = HttpClientBuilder.create().build()
        def response = client.execute(getQueue)

        // parse and print results
        def bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
        def jsonResponse = bufferedReader.getText()
        println "response: \n" + jsonResponse

    }

    static createQueues(ConfigObject props, String token, String envID) {

        def orgID = props.organizationID
        def regionID = props.regionID

        def queues = props.queues

        queues.each { queueID ->

            def putQueueURL = HOST + '/mq/admin/api/v1/organizations/' + orgID + '/environments/' + envID + '/regions/' + regionID + '/destinations/queues/' + queueID
            def putQueue = new HttpPut(putQueueURL)

            putQueue.addHeader("Content-Type", "application/json")
            putQueue.addHeader("Authorization", "Bearer " + token)

            def queueMap = [:]
            queueMap["defaultTtl"] = 604800000
            queueMap["defaultLockTtl"] = 120000
            queueMap["encrypted"] = false
            queueMap["fifo"] = false

            def putQueueJSONBody = new JsonBuilder(queueMap).toString()
            putQueue.setEntity(new StringEntity(putQueueJSONBody))

            def client = HttpClientBuilder.create().build()
            def response = client.execute(putQueue)

            def bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
            def jsonResponse = bufferedReader.getText()
            println "response: \n" + jsonResponse

        }

    }

    static createExchanges(ConfigObject props, String token, String envID) {

        def orgID = props.organizationID
        def regionID = props.regionID

        def exchanges = props.exchanges

        exchanges.each { exchangeID ->

            def putExchangeURL = HOST + '/mq/admin/api/v1/organizations/' + orgID + '/environments/' + envID + '/regions/' + regionID + '/destinations/exchanges/' + exchangeID
            def putExchange = new HttpPut(putExchangeURL)

            putExchange.addHeader("Content-Type", "application/json")
            putExchange.addHeader("Authorization", "Bearer " + token)

            def exchangeMap = [:]
            exchangeMap["encrypted"] = false

            def putExchangeJSONBody = new JsonBuilder(exchangeMap).toString()
            putExchange.setEntity(new StringEntity(putExchangeJSONBody))

            def client = HttpClientBuilder.create().build()
            def response = client.execute(putExchange)

            def bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
            def jsonResponse = bufferedReader.getText()
            println "response: \n" + jsonResponse

        }

    }

}