Vinod Sebastian – B.Tech, M.Com, PGCBM, PGCPM, PGDBIO

Hi I'm a Web Architect by Profession and an Artist by nature. I love empowering People, aligning to Processes and delivering Projects.

Advertisements




Salesforce: Creating REST Web Service

Define the REST Resource Class

To create a RESTful web service in Salesforce, you need to define a REST resource class. Here is an example:

@RestResource(urlMapping='/AccountService/*')
global with sharing class AccountRestService {
    // GET method: fetch account details
    @HttpGet
    global static Account doGet() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        
        // Extract accountId from the URL
        String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Account acc = [SELECT Id, Name, Phone FROM Account WHERE Id = :accountId LIMIT 1];
        
        return acc;
    }
    
    // POST method: create a new account
    @HttpPost
    global static Id doPost(String name, String phone) {
        Account acc = new Account(Name = name, Phone = phone);
        insert acc;
        
        return acc.Id;
    }
    
    // DELETE method: delete an account
    @HttpDelete
    global static String doDelete() {
        RestRequest req = RestContext.request;
        String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        delete [SELECT Id FROM Account WHERE Id = :accountId LIMIT 1];
        
        return 'Account deleted successfully';
    }
}

The @RestResource(urlMapping='/AccountService/*') defines the endpoint where external clients can call URLs like https://yourInstance.salesforce.com/services/apexrest/AccountService/{Id}.

The @HttpGet, @HttpPost, and @HttpDelete annotations map Apex methods to HTTP verbs. The RestRequest and RestResponse classes provide access to request parameters, headers, and response handling.

Salesforce automatically serializes Apex objects, like the Account object, into JSON for responses.

Example REST Calls

Here are examples of REST calls you can make to interact with the Salesforce REST web service:

  • GET Request:
GET https://yourInstance.salesforce.com/services/apexrest/AccountService/001XXXXXXXXXXXX
Authorization: Bearer

Response:

{
    "Id": "001XXXXXXXXXXXX",
    "Name": "Test Account",
    "Phone": "1234567890"
}
  • POST Request:
POST https://yourInstance.salesforce.com/services/apexrest/AccountService/
Authorization: Bearer 
Content-Type: application/json
{
    "name": "New Account",
    "phone": "9876543210"
}

Response:

“001YYYYYYYYYYYY”

Below is an example test class for the AccountRestService class:

@isTest
private class AccountRestServiceTest {
    @isTest static void testDoPostAndGet() {
        // Simulate POST
        RestRequest req = new RestRequest();
        RestResponse res = new RestResponse();
        req.requestURI = '/services/apexrest/AccountService/';
        req.httpMethod = 'POST';
        RestContext.request = req;
        RestContext.response = res;
        
        Id accId = AccountRestService.doPost('Unit Test Account', '111222333');
        
        // Verify account created
        Account acc = [SELECT Name, Phone FROM Account WHERE Id = :accId];
        System.assertEquals('Unit Test Account', acc.Name);
        
        // Simulate GET
        req.requestURI = '/services/apexrest/AccountService/' + accId;
        req.httpMethod = 'GET';
        RestContext.request = req;
        Account fetched = AccountRestService.doGet();
        System.assertEquals(accId, fetched.Id);
    }
    
    @isTest static void testDoDelete() {
        Account acc = new Account(Name='Delete Me');
        insert acc;
        
        RestRequest req = new RestRequest();
        RestResponse res = new RestResponse();
        req.requestURI = '/services/apexrest/AccountService/' + acc.Id;
        req.httpMethod = 'DELETE';
        RestContext.request = req;
        RestContext.response = res;
        
        String result = AccountRestService.doDelete();
        System.assertEquals('Account deleted successfully', result);
        System.assertEquals(0, [SELECT COUNT() FROM Account WHERE Id = :acc.Id]);
    }
}

Key Takeaways

  • REST services in Salesforce are built using Apex classes with @RestResource annotations.
  • Methods are exposed via HTTP verbs such as @HttpGet and @HttpPost.
  • Authentication is mandatory, with OAuth access token provided in the Authorization: Bearer header.
  • Salesforce automatically serializes Apex objects into JSON for responses.
  • Always write test classes to validate your REST logic and meet deployment requirements.