Exposing your methods as a web service

It turns out that only one keyword is needed to convert a method on a class to a web service endpoint.

I’m writing a small article – an introduction to Apex – and so I’m of course learning a few things about Apex while doing so. I’ve just learned how to create web services.
I want to write some code in Apex that can be called from some external client. In other words, I want to write a web service end-point that other folk could invoke using their language of choice.
You might think this would be a lot of work – in a previous life I’ve set up a web services stack, hacking several XML configuration files, simply to expose one end-point. Here, the Force.com Platform does it for me, which is rather nice.
So here’s the code:

global class MyWebService {
webservice static void createEvent(String mName, Integer howFar){
Mileage__c m = new Mileage__c (name = mName, miles__c = howFar);
m.date__c = Date.today();
Database.insert(m);
}
}

That’s all there is to it! This exposes a web service method, createEvent(), which can be invoked from some external client. The method, in turn, creates and persists a Mileage sObject – which I grabbed from the workbook, populating some of the parameters from the incoming web service call.
The only important bits are:

  • the webservice keyword, used on the (static) method
  • the global access modifier, which declares that the class is visible to all Apex code, everywhere. All classes defining these types of web services are required to so annotated.

When you save the class, the platform generates a nice “Generate WSDL” button that you can use to generate the WSDL and give to the folk writing the client.
ws.jpg
Needless to say, the section about web services in my article is rather short!

Published
September 3, 2008
Topics:

Leave your comments...

Exposing your methods as a web service