Contact Us 1-800-596-4880

REST API Example

The following example describes how to write an API that retrieves data from a publicly available REST API, using Anypoint Studio or a standalone XML in Mule runtime engine. The example API generates lorem ipsum text and queries the Bacon Ipsum REST API at:

http://baconipsum.com/

Consume a REST API in Anypoint Studio

To consume the REST API in Studio, you must configure HTTP connectors, add a file write operation, and then run the application.

  1. Begin in Studio by adding and configuring an HTTP Listener and an HTTP Request connector. You don’t have to use HTTPS or set up an account.

ConsumeRestAPI flow with HTTP Listener and HTTP Request Connectors
Figure 1. ConsumeRestAPI flow with HTTP Listener and HTTP Request Connectors.

At this point, you can call the API and receive bacon ipsum text in a web browser.

  1. Next, add a File Write component to save the output of the request for bacon ipsum text to a file on your file system:

Flow with HTTP Listener Connector, HTTP Request Connector and File Write component
Figure 2. Flow with HTTP Listener, HTTP Request Connectors and File Write component.

The first element, an HTTP Listener, listens on localhost port 8081 (default) for incoming GET requests. Calling the listener from a browser triggers the flow.

  1. Finally, send requests using the following syntax:

http://localhost:8081?<query>

The <query> consists of the parameters accepted by the REST API. When the HTTP Listener receives the HTTP Request, the application records <query> as a set of query parameters. The HTTP Listener passes these parameters to the next element in the flow, the HTTP Request operation. This operation is configured to query the remote REST API at http://baconipsum.com/api. The HTTP Request Connector uses DataWeave expressions to extract the query parameters from the properties in the message, and constructs the full URL for the remote API, including the query parameters.

For example, assume that you enter the following local browser request:

http://localhost:8081?type=meat-and-filler

As a result, the application issues the following query:

http://baconipsum.com/api/?type=meat-and-filler

Configure HTTP Connectors

Specify how to call the API and what to return by configuring the HTTP Listener and HTTP Request Connectors.

HTTP Listener

To configure the HTTP Listener, follow these steps:

  1. Select the HTTP Listener component.

  2. In Connector Configuration, click mruntime add plus, and set Host to localhost and Port to 8081.

  3. Click OK.

HTTP Listener Configuration with Host and Port
Figure 3. HTTP Listener Configuration with Host and Port.
  1. In the HTTP Listener properties editor, set Path to /:

HTTP Listener properties editor with Path
Figure 4. HTTP Listener properties editor with Path.

HTTP Request

  1. In Connector Configuration, click mruntime add plus, and set Host to baconipsum.com, Port to 80 , and Base Path to api . This configuration sends requests to http://baconipsum.com/api.

  2. Click OK.

HTTP Request Connector Configuration Settings
Figure 5. HTTP Request Connector Configuration Settings.
  1. In the properties editor, set Path to / and Method to GET.

  2. In the Query Parameters tab, add two query parameters.
    For each value field, provide a Mule expression that takes the specified value from the query parameters of the request that first reaches the HTTP Listener.

Parameter Value

Type

query-param

Name

type

Value

#[message.attributes.queryParams['type']]

Parameter Value

Type

query-param

Name

sentences

Value

`#[message.attributes.queryParams['sentences']]

Query Parameters with name and values
Figure 6. Query Parameters with name and values.

The Bacon Ipsum API page contains a list of parameters that you can use, but this application only uses type and sentences parameters. The optional sentences parameter determines the number of sentences to return in the JSON response.

File Write Operation

Set up the File Write component properties to save the output of the application to a file.

  1. Drag a File Write component onto the canvas.

  2. In the properties editor, set the directory and file name for storing the output: /tmp/output.

    mruntime rest api example 2
  3. In the properties editor, specify any actual path on your file system for Path:

File Write properties editor and Path
Figure 7. File Write properties editor and Path.

Run the Application to Consume a REST API

Follow these steps to run the application:

  1. In Studio, within your project, click 2% to run the example as a Mule application. Test

  2. In a web browser window, trigger the flow of the application by querying the HTTP Listener on localhost port 8081:

http://localhost:8081?type=meat-and-filler

The Bacon Ipsum API page contains a list of parameters you can use, but when configuring the HTTP Request Connector, you set up your connector to use only the type and sentences parameters.

  • The first parameter=value pair must be preceded by the ? operator.

  • To insert additional parameter=value pairs, use the & operator.

The following queries are examples that you can send to the HTTP Listener on localhost port 8081:

http://localhost:8081?type=meat-and-filler
http://localhost:8081?sentences=2
http://localhost:8081?type=all-meat&sentences=3

The type=meat-and-filler example returns the following output:

["Doner ullamco ea non, porchetta incididunt brisket ball tip in chuck ex bresaola beef tongue.  Et aute ham hock kielbasa chuck fatback short ribs.  Kevin in reprehenderit est esse, ham bacon ut ball tip.  Laborum ut nulla ex irure t-bone flank, biltong cupidatat venison proident aliquip pork belly ham hock.  In consequat proident, cillum labore pariatur nisi.  Reprehenderit boudin beef ribs, frankfurter cillum enim pork loin consectetur kielbasa laboris.  Hamburger prosciutto nisi, jerky biltong ex pork chop venison.","Fatback tongue anim, irure ut ut cupidatat occaecat eiusmod ham hock laborum commodo.  Anim pig shank kielbasa, drumstick corned beef esse nostrud ham salami id laborum ribeye aute.  Duis pancetta sunt magna occaecat dolor leberkas, short loin meatloaf flank enim pastrami.  Prosciutto proident landjaeger deserunt tenderloin short loin.  Adipisicing aute in bresaola meatball, ut frankfurter pastrami shoulder porchetta turducken strip steak doner.  In filet mignon bresaola, sed deserunt pariatur eu mollit commodo shankle laborum.  Andouille aliqua jowl pork chop jerky sed consequat turkey voluptate bacon pastrami.","Ground round elit boudin reprehenderit.  Brisket shankle esse, leberkas veniam andouille rump proident drumstick.  Consequat sausage do ut prosciutto nostrud andouille tongue ullamco bacon est exercitation.  Do fugiat biltong est tempor short ribs reprehenderit adipisicing shoulder.  Tail venison shank incididunt, hamburger adipisicing voluptate corned beef fugiat sirloin fatback in tri-tip nisi ut.  Tail non excepteur, fugiat veniam corned beef dolore ex pig pork belly sint mollit chuck pork.","Pig hamburger dolore proident brisket landjaeger in boudin kielbasa ut elit.  Velit incididunt boudin qui.  Fatback anim adipisicing, pig jowl voluptate sirloin drumstick chicken esse.  Strip steak consequat tenderloin pastrami, ullamco brisket hamburger bacon beef adipisicing.  Tri-tip ham hock eu non et, flank dolore kevin.  Et duis frankfurter, ut ullamco do non quis boudin andouille aliqua venison ham.  Ut aliqua shoulder, aliquip pariatur bacon spare ribs irure.","Aliqua jerky frankfurter, swine ham in ground round sed qui laborum cow.  Sint turducken shank ut ea id.  Kevin dolore pig excepteur, anim ut magna.  Enim consequat short ribs corned beef ham hock nostrud fugiat chuck.  Tail spare ribs dolore boudin, andouille incididunt laboris occaecat strip steak.  Cow frankfurter capicola, landjaeger cupidatat porchetta ad ground round voluptate."]

Consume a REST API in Standalone XML

To consume the REST API in Standalone XML, you need to configure the HTTP Listener and HTTP Request connectors as well as add the File Write component.

Configure HTTP Connectors

Specify how to call the API and what to return by configuring the HTTP Listener and HTTP Request connectors.

HTTP Listener

To configure the HTTP Listener, reference an abstract element called a Connector Configuration, which contains several of the high level necessary configuration properties:

<http:listener config-ref="HTTP_Listener_config" path="/"/>

The config-ref attribute in the connector references this connector configuration element. You must now create an element outside the flow that matches the referenced name.

<http:listener-config name="HTTP_Listener_config">
	<http:listener-connection host="0.0.0.0" port="8081" />
</http:listener-config>

HTTP Request

To configure the HTTP Request, reference an abstract element called a Connector Configuration, which contains several of the high level necessary configuration properties.

<http:request method="GET" config-ref="HTTP_Request_configuration" path="/">
	<http:query-params >
		<![CDATA[#[output application/java
			---
			{
				"type" : message.attributes.queryParams['type'],
				"sentences" : message.attributes.queryParams['sentences']
			}
		]]]>
	</http:query-params>
</http:request>

The config-ref attribute in the connector references this connector configuration element. You must now create an element outside the flow that matches the referenced name.

<http:request-config name="HTTP_Request_configuration" basePath="/api">
		<http:request-connection host="baconipsum.com" port="80"/>
	</http:request-config>

File Write Operation

Finally, add the File Write operation in the XML:

<file:write path="/Users/max/output.txt"/>

XML

Review the complete XML:

<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:file="http://www.mulesoft.org/schema/mule/file"
	xmlns:http="http://www.mulesoft.org/schema/mule/http"
	xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd">
	<http:request-config name="HTTP_Request_configuration" basePath="/api">
		<http:request-connection host="baconipsum.com" port="80"/>
	</http:request-config>
	<http:listener-config name="HTTP_Listener_config">
		<http:listener-connection host="0.0.0.0" port="8081" />
	</http:listener-config>

	<flow name="consumeRestAPI">
		<http:listener config-ref="HTTP_Listener_config" path="/"/>
		<http:request method="GET" config-ref="HTTP_Request_configuration" path="/">
			<http:query-params ><![CDATA[#[output application/java
				---
				{
					"type" : message.attributes.queryParams['type'],
					"sentences" : message.attributes.queryParams['sentences']
				}]]]>
			</http:query-params>
		</http:request>
		<file:write path="/Users/max/output.txt"/>
	</flow>
</mule>