Spring ’12: Updates to Apex REST

The ability to enable Apex classes to be exposed via the REST is great tool in any Force.com developer’s toolkit.  With Spring ’12, we’re making it even easier to use by streamlining some of the aspects of building out your Apex methods associated with your endpoint.

Here’s an example of how an Apex class might work with Spring ’12:

@RestResource(urlMapping='/FieldCase/*')
global class ApexRESTUpdate {

//Note we no longer need to include RestRequest and RestResponse as incoming parameters
//The static RestContext has request and response properties instead
  @HttpGet
  global static List<Case> getOpenCases() {
    String companyName = RestContext.request.params.get('companyName');
    Account company = [ Select ID, Name, BillingState from Account where Name = :companyName];
    List<Case> cases = [SELECT Id, Subject, Status, OwnerId, Owner.Name from Case WHERE AccountId =: company.Id];
    return cases;

  }

//Here we are using CaseSummary as an incoming parameter, which is an Apex class not an SObject.
//Previously, you could not use user defined params
  @HttpPost
  global static String createCase(CaseSummary cs) {
		Case c = new Case();
		c.Subject = cs.CaseExternalID + cs.CaseDescription;
		insert c;

		return c.Subject;
	}
}

Let’s call out a few specific things here.

A RestContext object means we no longer need RestResponse and RestRequest.  Notice how in the first method we don’t require RestResponse and RestRequest as incoming parameters to define out GET based endpoint.  There is now a static RestContext object which will be available to the class to provide access to the same information.

CaseSummary is an Apex class, not an SObject.  In the second method, we’re using an Apex class to define a data structure, rather than having to rely on an SObject to provide us with one.  In previous versions of the API – this would have resulted in an error on compiling.  This should offer a lot more flexibility to developers for designing their endpoints.

Two other things to call out: Apex REST can be offered in both managed and unmanaged packages now, and you no longer need to have your JSON data order match your incoming parameter order in the Apex method.  So no more having to flip in between windows to remember if your string was supposed to be before your integer.

For even more detailed information, checkout the preview of the Apex Documentation for Spring ’12.

What are you building with Apex REST?  Will these changes help you down the way?  Let us know in the comments below, or you can ping me via twitter @joshbirk.

Published
January 9, 2012
Topics:

Leave your comments...

Spring ’12: Updates to Apex REST