Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Adobe ColdFusion

This chapter is from the book

Building Your First Web Service

Now it’s time to get started building a web service with ColdFusion.

To build a web service in ColdFusion, all we need to do is to write a ColdFusion component (CFC). CFCs take an object-like approach to the grouping of related functions and encapsulation of business logic. They also play a pivotal role in defining and accessing a web service.

We can create or reuse a prebuilt CFC with the operations we want to expose as functions and make the CFC accessible to remote calls by specifying access="remote". The CFC location then becomes the endpoint for the web service, and its remote functions become operations that can be invoked on this web service.

Now let’s create our first web service. We’ll start with the component in Listing 4.1.

Listing 4.1. /cfwack/4/hello.cfc

<cfcomponent>
   <cffunction name="helloWorld" returnType="string" access="remote">
      <cfreturn "Hello World!">
   </cffunction>
</cfcomponent>

The hello CFC starts with a <cfcomponent> tag, which wraps the component’s content. Then the <cffunction> tag with a name and return type defines a single function, which simply returns a static string. The optional access attribute is set to remote, which exposes this CFC as a web service. And now we have a simple CFC-based web service, which we can publish and allow to be called by web service clients across the web.

To quickly verify that this web service works, open http://localhost:8500/cfwack/4/hello.cfc?wsdl in a browser. It should output the generated WSDL. Listing 4.2 shows part of the generated WSDL for this hello CFC.

Listing 4.2. Part of the WSDL Generated for hello.cfc

<!— Some attributes have been omitted to keep focus only on elements relevant to our discussion later in this section-->
<wsdl:binding name="cfwack.4.hello.cfcSoap12Binding" ...>
  <soap12:binding ... style="document"/>
  <wsdl:operation name="helloWorld">
    <soap12:operation ... style="document"/>
    <wsdl:input>
      <soap12:body use="literal"/>
    </wsdl:input>
    <wsdl:output>
      <soap12:body use="literal"/>
    </wsdl:output>
    <wsdl:fault ...>
      <soap12:fault use="literal" .../>
    </wsdl:fault>
  </wsdl:operation>
</wsdl:binding>
<wsdl:service name="cfwack.4.hello.cfc">
  <wsdl:port name="cfwack.4.hello.cfcHttpSoap11Endpoint" ...>
  <wsdl:port name="cfwack.4.hello.cfcHttpSoap12Endpoint" ...>
</wsdl:service>

Here are a few details that you will observe here:

  • An operation "helloWorld" is listed with the same name as that of the <cffunction> function.
  • The WSDL has all the information such as types, endpoints, and message style required to execute this operation.
  • Both SOAP 1.1 and SOAP 1.2 endpoints are supported through the same WSDL.
  • The default WSDL style generated is Document Literal. You can change this style, as you will see later in this chapter.

ColdFusion will additionally log the web service engine used to deploy and access this web service on the console. This log can come in handy when you want to verify that the WSDL was refreshed and identify which web service engine was used for that particular operation.

Consuming a Web Service

Next we will see how to invoke this web service from ColdFusion. There are several ways to invoke any web service in ColdFusion, and we will look at them one by one.

Let’s start with the <cfinvoke> tag. This tag can be used to invoke a web service by specifying the webservice attribute, as shown in Listing 4.3.

Listing 4.3. Calling a Web Service with <cfinvoke>

<cfset wsURL = "http://localhost:8500/cfwack/4/hello.cfc?wsdl">
<cfinvoke
  webservice = "#wsURL#"
  method = "helloWorld"
  returnVariable = "result">
<cfoutput> <H1> #result# </H1></cfoutput>

Here we are trying to invoke the hello CFC that we wrote earlier, using the <cfinvoke> tag. We specified the CFC’s WSDL using the webservice attribute, the method to be invoked as “helloWorld” uses the same name as the function, and returnVariable is used to store the result of this operation. Then we simply output the result using <cfoutput> wrapped with HTML <H1> tags. If you run this code in a browser, you should get output similar to that in Figure 4.3.

Figure 4.3

Figure 4.3. Output generated from hello CFC.

Also, since web services are built on top of HTTP, you may need to provide other attributes such as proxy details if you are using an HTTP proxy server to connect to the web service provider and passwords similar to those for the <cfhttp> tag for calls using the <cfinvoke> tag.

Similarly, you can use the <cfobject> tag to create a web service proxy object. Then you can invoke methods on this object, which will be delegated as web service calls to actual endpoints. Listing 4.4 uses <cfobject> to call the same hello web service described earlier, by specifying the type as webservice.

Listing 4.4. Calling a Web Service with <cfobject>

<cfset wsURL = "http://localhost:8500/cfwack/4/hello.cfc?wsdl">
<cfobject
  name = "ws"
  webservice= "#wsURL#"
  type = "webservice">
<cfset result = ws.helloWorld()>
<H1><cfoutput>#result#</cfoutput></H1>

When in script mode—that is, within a <cfscript> block or when writing CFCs in script syntax—you can use the CreateObject() method to invoke a web service. It is the script equivalent of the <cfobject> tag. Listing 4.5 shows how to use CreateObject to invoke a web service.

Listing 4.5. Calling a Web Service with CreateObject

<cfscript>
  wsURL = "http://localhost:8500/cfwack/4/hello.cfc?wsdl";
  ws = CreateObject("webservice", wsURL);
  result = ws.helloWorld();
  writeoutput(result);
</cfscript>

Refreshing Stubs

Recall the steps we have discussed for calling a web service. Creation of a web service proxy with <cfobject> or CreateObject() consists of steps 3 and 4 in Figure 4.1. Any call to a web service using this proxy will be steps 5 and 6. A web service call using <cfinvoke> involves steps 3 through 6.

However, steps 3 and 4 are computationally heavy operations and should be performed only once for a WSDL that is not changing. Hence, ColdFusion optimizes this operation significantly. ColdFusion makes a call to get the WSDL and generates the required stubs and artifacts only for the first call to the web service, using <cfinvoke> or <cfobject>. From the next call onward, it uses the generated stubs themselves, eliminating the need for steps 3 and 4.

This optimization creates a challenge in a development environment in which CFCs are being constantly modified. ColdFusion does not implicitly refresh the stubs for changed WSDL. The clients themselves have to refresh these stubs every time the WSDL changes. This operation can be accomplished by setting the refreshWSDL attribute as true with <cfinvoke> or <cfobject>. Although in a production environment refreshWSDL should be false, this is its default value, too.

Using Complex Data Types

In this section, you will see how to work with different ColdFusion data types. For that purpose, let’s look at another CFC, this one with several functions that take some complex data types, such as a struct or query, as arguments (Listing 4.6). Here we will focus on two processes: how to pass an argument to a web service call and how to work on the result.

Listing 4.6. /cfwack/4/complex.cfc

<cfcomponent hint="echoes back the input specified">

<!---
The purpose of these functions merely is to demo accepting
and returning a complex object
--->

    <cffunction name="echoStruct" returntype="struct" access="remote">
    <cfargument type="struct" name="argStruct"/>

        <!---
        outputs argument passed to this function to console
        good for debugging while developing the service
        --->
        <cfdump var="#argStruct#" output="console">
        <!--- typically your logic goes here --->
        <cfreturn argStruct>
    </cffunction>

    <cffunction name="echoQuery" returntype="query" access="remote">
    <cfargument type="query" name="argQuery"/>

    <cfreturn argQuery>
    </cffunction>

    <cffunction name="echoDocument" returntype="xml" access="remote">
    <cfargument type="xml" name="argDocument"/>

    <cfreturn argDocument>
    </cffunction>

    <cffunction name="echoAny" returntype="any" access="remote">
    <cfargument type="any" name="argAny"/>

    <cfreturn argAny>
    </cffunction>

</cfcomponent>

Let’s analyze what’s going on here. We have created a complex CFC that isn’t actually very complicated. As you can see, it simply takes native ColdFusion data types as arguments and returns them back: the function echoStruct takes a struct as an argument, the function echoQuery takes a query as an argument, and the function echoAny can take any type as an argument.

Note that no special treatment is required to handle web service calls, and this CFC can work directly by creating its object and can also serve Ajax Remoting and Adobe Flash Remoting calls. You get the same data types to work with. It is ColdFusion’s responsibility to internally serialize the given data type to XML format before sending the web service call as a client, and to deserialize this XML back to the desired data type and pass it as an argument to the invoked function when it receives the web service to process it as a server.

Passing Arguments

Next, let’s see how to invoke this web service with ColdFusion. We have already talked about different ways to invoke web services, and for this example we will use <cfinvoke>. Let’s look at how to pass an argument and work with the returned object (Listing 4.7).

Listing 4.7. /cfwack/4/complex.cfm

<cfset wsURL = "http://localhost:8500/cfwack/4/complex.cfc?wsdl">

<cfset varStruct = {key1:"value 1", key2:"value 2"} >
<!-- Passing arguments with cfinvokeparam --->
<cfinvoke webservice = "#wsURL#"
           method = "echoStruct"
           returnVariable = "result">
   <cfinvokeargument name="argStruct" value="#varStruct#" >
</cfinvoke>

<h2> Dumping struct </h2>
<cfdump var="#result#"/>

<cfset varQuery = QueryNew("column1,column2,column3") >
<cfset QueryAddRow(varQuery,["row 1", "row 2", "row 3"])>

<!-- Passing arguments inline as key value pair --->
<cfinvoke webservice = "#wsURL#"
           method = "echoQuery"
           argQuery = "#varQuery#"
           returnVariable = "result">
</cfinvoke>

<h2> Dumping query </h2>
<cfdump var="#result#"/>

<!-- Passing arguments as argument collection --->
<cfinvoke webservice = "#wsURL#"
           method = "echoAny"
           argumentcollection = "#{argAny:'passing a string'}#"
           returnVariable = "result">
</cfinvoke>

<h2> Dumping String </h2>
<cfdump var="#result#"/>

As shown here, there are three ways to pass arguments to web service calls. Let’s look at them one by one.

First we will see how to pass an argument using the <cfinvokeparam> tag. We begin by creating the WSDL URL to be passed with <cfinvoke>. We then create a struct with implicit notation. And in case the syntax confuses you, ColdFusion also supports JavaScript-style syntax for declaring the struct. Next we use <cfinvoke> to call the web service by using <cfinvokeparam> as its child tag and passing the arguments specified as a key-value pair. This key will be matched with the arguments declared in the function and will be populated likewise.

Alternatively, you can pass arguments as superfluous attributes in the <cfinvoke> tag itself, as shown in next call to echoQuery. Again, the attribute name is the argument name, and its value is the value that we want to pass to the call.

Finally, you can also use argumentcollection to pass a struct with the argument name as the key and the value to be passed as its corresponding value as shown for the call echoAny call.

Note that you cannot use positional arguments with <cfinvoke> because the key is a mandatory attribute in all three scenarios described here. To use positional arguments, you can use <cfobject> or CreateObject() to generate a web service proxy and call methods on it. This call will behave similarly to any other method invocation for components and supports positional arguments, key-value syntax, and argument collection.

Also note that we passed a simple string to echoAny. We did this because the type definition of “any” in generated WSDL supports only simple data types. If you passed any complex object instead, it would fail with the “unknown type cannot serialize” exception.

We have now seen various ways to pass complex objects as arguments and get back complex objects as the result of that particular web service call. What’s interesting is that there is almost no difference between calling a web service and calling a component locally. That is the beauty of ColdFusion: the capability to abstract the hard wiring required to perform a complex task such as a web service call and expose it as something simple that we already know such as calling a component. This ease of use lets us focus on the actual business logic and not to be bothered with the underlying technology or mundane boilerplate code.

Working with Multiple Arguments

So far in our examples, we have seen functions with only one argument. But your real-world functions more likely will have more than one argument. And though the mechanism to call these functions as web services remains the same, there are a few details that you need to take care of.

When your function has more than one argument, you may want to make a few arguments required and the rest optional. However, the <cffunction> attribute Required is ignored when a CFC is called as a web service; for a web service, all arguments are required. ColdFusion doesn’t support method overloading, so in in cases in which you want to pass only a few arguments, you need to use either of two approaches:

  • You can make the function private and define different public methods for all parameter combinations. These methods will internally invoke this private function within the CFC, which performs the actual processing and also honors the defaults.
  • The second possible solution is to use a special value for arguments that you don’t want to pass: for example, NULL. Then within the function body, you can check IsNull() and place default values instead. If you use <cfinvoke>, then you can set the <cfinvokeargument> tag’s attribute omit as true. If you are using a proxy object created with <cfobject> or the CreateObject() method, you can simply pass NULL.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020