Expose a Class as a REST Service

Making your Apex class available as a REST web service is straightforward. Define your class as global, and define methods as global static. Add annotations to the class and methods. For example, this sample Apex REST class uses one method. The getRecord  method is a custom REST API call. It’s annotated with @HttpGet  and is invoked for a GET request.

@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {
    @HttpGet
    global static Account getRecord() {
        // Add your code
    }
}

As you can see, the class is annotated with @RestResource(urlMapping='/Account/*) . The base endpoint for Apex REST is [<https://yourInstance.salesforce.com/services/apexrest/>](<https://yourinstance.salesforce.com/services/apexrest/>) . The URL mapping is appended to the base endpoint to form the endpoint for your REST service. The URL mapping is case-sensitive and can contain a wildcard character (*).

Define each exposed method as global static and add an annotation to associate it with an HTTP method. The following annotations are available (You can use each annotation only once in each Apex class):

Examples of using cURL to access the SF data here.

Test your REST Class

Testing your Apex REST class is similar to testing any other Apex class—just call the class methods by passing in parameter values and then verify the results. For methods that don’t take parameters or that rely on information in the REST request, create a test REST request.

In general, here’s how you test Apex REST services. To simulate a REST request, create a RestRequest in the test method, and then set properties on the request as follows. You can also add params that you “pass” in the request to simulate URI parameters.

// Set up a test request
RestRequest request = new RestRequest();

// Set request properties
request.requestUri =
    '<https://yourInstance.salesforce.com/services/apexrest/Cases/>'
    + recordId;
request.httpMethod = 'GET';

// Set other properties, such as parameters
request.params.put('status', 'Working');

// more awesome code here....
// Finally, assign the request to RestContext if used
RestContext.request = request;

If the method you’re testing accesses request values through RestContext, assign the request to RestContext to populate it (RestContext.request = request; ).

Expose a Class as a SOAP Service

Making your Apex class available as a SOAP web service is as easy as with REST. Define your class as global. Add the webservice keyword and the static definition modifier to each method you want to expose. The webservicekeyword provides global access to the method it is added to.

For example, here’s a sample class with one method. The getRecord method is a custom SOAP API call that returns an Account record.

global with sharing class MySOAPWebService {
    webservice static Account getRecord(String id) {
        // Add your code
    }
}