Quick Tip – Public RESTful Web Services on Force.com Sites

A little while ago, Paul McGurn blogged how to create a public (SOAP-based) web service via a Force.com Site. As Paul explains, you add your web service class to the Enabled Apex Classes in the Site’s Public Access Settings. You’ll also need to add the appropriate object and field-level permissions for any data you will be exposing; remembering, of course, that this web service will be accessible without any authentication!

As I was setting up a WebHook the other day, I realized that the same principle applies to Apex REST Methods – add the class and any relevant objects/fields to your Site’s Public Access Settings, and you can access the REST methods via the Site URL. Let’s code up a simple example; here’s my Apex class:

@RestResource(urlMapping='/myservice')
global class MyService {
    @HttpGet
    global static String doGet() {
        String name = RestContext.request.params.get('name');
        return 'Hello '+name;
    }
}

I’m not manipulating any standard or custom objects, so I just need to add MyService to the Enabled Apex Classes in the Site’s Public Access Settings:

The public URL for an Apex REST method has the format {Site_URL}/services/apexrest{URL_mapping}. In my example, this will be https://patdevorg-developer-edition.na9.force.com/services/apexrest/myservice. I can easily test my service from the command line with cURL:

$ curl https://patdevorg-developer-edition.na9.force.com/services/apexrest/myservice?name=Pat
"Hello Pat"

Bonus tip: Wondering why those double quotes are there, and how to get rid of them? Well, by default, Apex REST Methods return JSON-formatted data, and a JSON-formatted String has quotes. You can get more control over your method’s output via RestResponse‘s responseBody property:

@RestResource(urlMapping='/myservice')
global class MyService {
    @HttpGet
    global static void doGet() {
        RestContext.response.addHeader('Content-Type', 'text/plain');
        String name = RestContext.request.params.get('name');
        RestContext.response.responseBody = Blob.valueOf('Hello '+name);
    }
}

Calling the service with cURL:

$ curl https://patdevorg-developer-edition.na9.force.com/services/apexrest/myservice?name=Pat
Hello Pat

As you can see, it’s easy to set up publicly accessible endpoints in your org. Just remember the security implications, and consider carefully what objects and fields you expose.

Published
February 22, 2012
Topics:

Leave your comments...

Quick Tip – Public RESTful Web Services on Force.com Sites