Simon Fell > Its just code > Apex Web Services

Thursday, January 18, 2007

I was at Apex day in San Francisco yesterday, there was an impressive turn-out, I saw lots of new faces, along with a few familiar faces from Dreamforce. Developer's at the event were lucky enough to be able to signup for the developer prerelease of Apex Code. In addition to the support for triggers that Apex Code brings, Apex Code also supports exposing your code as a fully fledged web service, complete with WSDL, and powered by the same high performance, highly interoperable web services implementation that drives the primary salesforce.com API. In Apex code the private/public specifier has an additional option, its actually private/public/webService. Simply create your code in a package, and mark the method as webService, e.g.

package wsDemo {
    webService String sayHello(String name) {
        return 'Hello ' + name;
    }
}
and you'll have a complete WSDL for calling this code. Of course, no one needs a web service to do string concatenation, where this really comes into its own is build your own transactional units for doing integrations. Anyone who's built a complex data integration with salesforce (or any other distributed system) knows the pain of trying to manage transactional units that are different at the both ends, and having to build compensating transactions etc. Simple examples like creating an opportunity and all its line items in a single transactional unit could of been achieved by evolving the existing API, however more complex uses cases, where the developer needs to update 5 objects, delete 3 and create 1 new object all in a single transaction, just can't be handled by evolving the existing API. But, now you can build your own API's that have exactly the transactional boundaries you want. In Apex Code, you the developer control the transactions, so you can write a method that receives all the data needed as inputs, it can do a number of data operations, including create, update, delete, using data from both the request, and existing data in the system, then at the end only commit if everything went ok. Using Apex Code with its Web Services support I think will be a really powerful and easy way to do complex data integrations. Here's an Opportunity / LineItem sample, as the calls to insert will throw an exception if there's an error, and if the exception leaves your code, your transaction is rolled back, the entire call will either fully succeed or fail.
webService ID createOrder(Opportunity o, OpportunityLineItem [] items) {
   insert(o);
   for (OpportunityLineItem i : items) {
      i.opportunityId = o.Id;
   }
   insert(items);
   return o.Id;
}