TrailForceTips

Complete Guide to Creating a REST API in Apex on Salesforce

REST APIs are an essential tool for system integration, enabling communication between different applications simply and efficiently. In Salesforce, you can create custom REST APIs using Apex, providing great flexibility to meet business needs.

This article will explore the main concepts and provide a step-by-step guide to creating a REST API in Apex.

1. What is a REST API?

REST (“Representational State Transfer”) is an architectural style that uses HTTP methods (GET, POST, PUT, DELETE) to perform CRUD (Create, Read, Update, Delete) operations. In the context of Salesforce, REST APIs allow:

  • Retrieving data from Salesforce objects.
  • Updating, creating, or deleting records.
  • Integrating Salesforce with external systems.

2. Benefits of Using Apex to Create REST APIs

  • Flexibility: Full control over the data returned and the business rules applied.
  • Security: Allows custom authentication and authorization controls.
  • Customization: Ability to create specific endpoints for business needs.

3. Step-by-Step Guide to Creating a REST API in Apex

3.1. Configure the Apex Class

To make a class accessible as a REST API, annotate it with @RestResource. Methods should be defined with @HttpGet, @HttpPost, @HttpPut, or @HttpDelete.

Basic Example:

@RestResource(urlMapping='/AccountAPI/*')
public class AccountAPI {

    // Method to fetch an account by ID
    @HttpGet
    public static Account getAccount() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;

        String accountId = req.requestURI.substringAfter('/AccountAPI/');
        if (String.isEmpty(accountId)) {
            res.statusCode = 400;
            res.responseBody = Blob.valueOf('{"error": "Account ID not provided"}');
            return null;
        }

        try {
            Account account = [SELECT Id, Name, Phone FROM Account WHERE Id = :accountId LIMIT 1];
            return account;
        } catch (Exception e) {
            res.statusCode = 500;
            res.responseBody = Blob.valueOf('{"error": "Error fetching account: ' + e.getMessage() + '"}');
            return null;
        }
    }
}

Code Explanation:

  • @RestResource: Defines the API endpoint.
  • @HttpGet: Defines the method called when a GET request is made.
  • RestContext: Allows access to the request and manipulation of the response.

3.2. Add Other HTTP Methods

In addition to GET, you can create methods for POST, PUT, and DELETE. See examples:

Create Account (POST):
@HttpPost
public static String createAccount(String name, String phone) {
    try {
        Account account = new Account(Name = name, Phone = phone);
        insert account;
        return '{"message": "Account successfully created", "id": "' + account.Id + '"}';
    } catch (Exception e) {
        RestContext.response.statusCode = 500;
        return '{"error": "Error creating account: ' + e.getMessage() + '"}';
    }
}
Update Account (PUT):
@HttpPut
public static String updateAccount(String id, String name, String phone) {
    try {
        Account account = [SELECT Id FROM Account WHERE Id = :id];
        account.Name = name;
        account.Phone = phone;
        update account;
        return '{"message": "Account successfully updated"}';
    } catch (Exception e) {
        RestContext.response.statusCode = 500;
        return '{"error": "Error updating account: ' + e.getMessage() + '"}';
    }
}
Delete Account (DELETE):
@HttpDelete
public static String deleteAccount(String id) {
    try {
        Account account = [SELECT Id FROM Account WHERE Id = :id];
        delete account;
        return '{"message": "Account successfully deleted"}';
    } catch (Exception e) {
        RestContext.response.statusCode = 500;
        return '{"error": "Error deleting account: ' + e.getMessage() + '"}';
    }
}

4. Writing Test Classes for Your REST API

In Salesforce, test classes are mandatory to deploy Apex code to production. Here’s how you can write tests for the above REST API:

Test Class Example:

@IsTest
public class AccountAPITest {
    @IsTest
    public static void testGetAccount() {
        // Create test data
        Account testAccount = new Account(Name = 'Test Account', Phone = '1234567890');
        insert testAccount;

        // Simulate a GET request
        RestRequest req = new RestRequest();
        RestResponse res = new RestResponse();
        req.requestURI = '/services/apexrest/AccountAPI/' + testAccount.Id;
        req.httpMethod = 'GET';
        RestContext.request = req;
        RestContext.response = res;

        // Call the method
        AccountAPI.getAccount();

        // Validate response
        System.assertEquals(200, RestContext.response.statusCode);
        System.assertNotNull(RestContext.response.responseBody);
    }

    @IsTest
    public static void testCreateAccount() {
        // Simulate a POST request
        RestRequest req = new RestRequest();
        RestResponse res = new RestResponse();
        req.requestURI = '/services/apexrest/AccountAPI';
        req.httpMethod = 'POST';
        req.addParameter('name', 'Test Account');
        req.addParameter('phone', '9876543210');
        RestContext.request = req;
        RestContext.response = res;

        // Call the method
        AccountAPI.createAccount('Test Account', '9876543210');

        // Validate response
        System.assertEquals(200, RestContext.response.statusCode);
        System.assertNotNull(RestContext.response.responseBody);
    }
}

Key Points for Test Classes:

  • Use @IsTest annotation to define test methods.
  • Create and clean up test data.
  • Simulate HTTP requests using RestRequest and RestResponse.
  • Validate the results using assertions.

5. Authentication for Your REST API

Salesforce APIs require OAuth 2.0 for authentication. Follow these steps for implementation:

5.1. Create a Connected App

  1. Navigate to Setup > App Manager > New Connected App.
  2. Fill in basic details (e.g., App Name, Email).
  3. Under API (Enable OAuth Settings), check Enable OAuth Settings and provide a callback URL (e.g., https://login.salesforce.com/services/oauth2/callback).
  4. Select OAuth scopes such as:
    • Access and manage your data (api)
    • Perform requests at any time (refresh_token)
  5. Save the app and note the Consumer Key and Consumer Secret.

5.2. Obtain Access Token

Make a POST request to the Salesforce token endpoint:

POST https://login.salesforce.com/services/oauth2/token

Request Body:

{
    "grant_type": "password",
    "client_id": "<YOUR_CONSUMER_KEY>",
    "client_secret": "<YOUR_CONSUMER_SECRET>",
    "username": "<YOUR_SALESFORCE_USERNAME>",
    "password": "<YOUR_PASSWORD_AND_SECURITY_TOKEN>"
}

5.3. Using the Access Token

Once you receive the access token, include it in the Authorization header of your requests:

Authorization: Bearer <ACCESS_TOKEN>

Example Using Postman:

  • Endpoint: https://<your_instance>.my.salesforce.com/services/apexrest/AccountAPI
  • Headers:
    • Authorization: Bearer <ACCESS_TOKEN>
    • Content-Type: application/json
  • Payload (for POST):
{
    "name": "Test Company",
    "phone": "123-456-7890"
}

6. Best Practices

  1. Security:
    • Use OAuth 2.0 for authentication.
    • Validate all input data to prevent injection attacks.
  2. Documentation:
    • Provide clear examples and descriptions for the endpoints.
  3. Error Handling:
    • Always return user-friendly and informative error messages.
  4. Usage Limits:
    • Implement limits to prevent API abuse.

Conclusion

Creating a REST API in Apex on Salesforce enables you to meet custom integration needs with full control over the system’s behavior. With the examples, testing methods, and authentication details described in this guide, you’ll be ready to develop robust, secure, and scalable APIs.

Leave a Reply

Your email address will not be published. Required fields are marked *