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. 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.