Not yet rated

Problem

A ColdFusion application needs to call a RESTful web service.

Solution

ColdFusion provides a simple and easy way to call RESTful webservices with <cfhttp>.

Detailed explanation

Often times an application will need to access data from a third party provider.  One of these providers may provide data in a RESTful web service. (Representational State Transfer - http://en.wikipedia.org/wiki/Representational_State_Transfer) For this example the application will use a HTTP based RESTful service utilizing XML.

An application might have a need to verify a zip code is accurate to the city and state a user entered and could possibly use a web service to do this.  Assuming the web service has a method called verifyZipCode and requires that a zipcode be passed in the application would need to construct an XML packet like the following:

<cfsavecontent variable="verifyZipCodeRequestXML">
<request>
<method>verifyZipCode</method>
<zipCode>46032></zipCode>
</request>
</cfsavecontent>

The XML the application constructs will depend on the XML signature that the web service provider requires.  Nex the application will need to make an HTTP POST to the web service URL and pass in the request as well as specify a variable to hold the response from the service.

<cfhttp url="#webServiceURL#" method="POST"
result="verifyZipCodeResponse">
<cfhttpparam type="body"
value="request=#verifyZipCodeRequestXML#"  />
</cfhttp>

The response variable, verifyZipCodeResponse, will be a structure with keys containing data about the request, with the actual response from the service being in the key Filecontent.

The Filecontent variable might contain XML that looks like this:

<?xml version='1.0' ?>
<response>
<city>Carmel</city>
<state>IN</state>
</response>

The XML response will be dependent on the service provider.

At this point, it's simply a matter of parsing the XML and making sure the city and state returned from the web service match up with the city and the state the user entered into the application.

ColdFusion makes calling RESTful services, quick, easy and simple!

 

 

 


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes