logo
shape

Apex REST service

Apex REST service allows you to expose your Apex classes and methods as REST endpoints that can be easily consumed by external systems.

REST serivce in Apex
Create an Apex REST service that returns an account and its contacts.
Create an Apex class named AccountManager. The class must have a method called getAccount and the Method must be annotated with @HttpGet and return an Account object. The Method must return the ID and Name for the requested record and all associated contacts with their ID and Name

@RestResource(urlMapping='/Accounts/*/contacts')
global class AccountManager {
    @HttpGet
    global static Account getAccount() {
        RestRequest req = RestContext.request;
        String accId = req.requestURI.substringBetween('Accounts/', '/contacts');
        Account acc = [SELECT Id, Name, (SELECT Id, Name FROM Contacts) 
                       FROM Account WHERE Id = :accId];
        return acc;
    }
}


                    

Create unit tests. The unit tests must be in a separate Apex class called AccountManagerTest. The unit tests must cover all lines of code included in the AccountManager class, resulting in 100% code coverage.

@isTest
private class AccountManagerTest {
    private static testMethod void getAccountTest1() {
        Id recordId = createTestRecord();
        // Set up a test request
        RestRequest request = new RestRequest();
        request.requestUri = 'https://na1.salesforce.com/services/apexrest/Accounts/'+ recordId +'/contacts' ;
        request.httpMethod = 'GET';
        RestContext.request = request;
        // Call the method to test
        Account thisAccount = AccountManager.getAccount();
        // Verify results
        System.assert(thisAccount != null);
        System.assertEquals('Test record', thisAccount.Name);
        System.assertEquals(1, thisAccount.Contacts.size(), 'Expected one contact for the account');
    }

    // Helper method
    static Id createTestRecord() {
        // Create test record
        Account TestAcc = new Account(
          Name='Test record');
        insert TestAcc;
        Contact TestCon= new Contact(
        LastName='Test', 
        AccountId = TestAcc.id);
        insert TestCon;
        return TestAcc.Id;
    } 
}


                    
Most Asked Questions about REST Service in Apex
Can Apex REST methods be overloaded?

Unlike Apex classes, Apex REST services do not support method overloading. This means you cannot have two methods with the same name, even if they have different parameters. You will need to give your methods unique names.

How does Salesforce handle NULL values in Apex REST service responses?

By default, if a field in an sObject is NULL, it will not be included in the serialized JSON response. This means that the receiving system must be able to handle missing fields. If it's crucial for the NULL fields to be present in the response, you might need to create a wrapper class and manually set the null fields.

Can you use governor limit statements (like LIMIT or OFFSET) in SOQL queries within an Apex REST service?

Yes, but you need to be cautious. Apex REST services, like any other Apex code, are subject to governor limits, including limits on the total number of records retrieved by SOQL queries. This means that if your query retrieves too many records, it could cause your service to exceed its governor limits and fail. To protect against this, you can use the LIMIT and OFFSET statements to control the number of records retrieved. However, OFFSET also counts toward the governor limits and it cannot exceed 2000 rows. So for larger data sets, you might need to implement a custom pagination solution.

© All rights Reserved. 2023