By integrating your Salesforce org with third-party applications, you can unlock functionalities that are streamlined toward your business use case. That’s where the Salesforce Apex REST API comes in. It allows for end-to-end compatibility between your Salesforce org and external web services such APIs, databases, etc.

In this article, you will gain information about Salesforce APEX REST APIs. You will also gain a holistic understanding of API, REST API, Salesforce, its key features, and the methods used to call the REST interface directly.

Understanding Salesforce Apex REST API

Image Source

There are tens of APIs available on the Salesforce platform that enable developers to programmatically interact with the platform. The Salesforce Apex REST API, in particular, exposes Apex methods via REST and it makes it possible for developers to create REST-based web services using Apex code. Third-party services/applications that are external to Salesforce.com can use the Apex REST API to connect to Salesforce and retrieve data (records, field values), or to update data on a client’s Salesforce.com account. 

The Salesforce Apex API opens up the root Salesforce Apex code and architecture to outside developers through a RESTful interface. It provides the ability to define custom logic. Developers can use this API to define custom logic and build new features on top of Salesforce.com’s customer relationship management (CRM) functionality.

They can achieve this by exposing some Apex classes and methods and implementing them as web services (in the form of API endpoints which can be called by external services and applications). 

Normally, the Salesforce Apex REST API is typically used when the standard Salesforce REST API is not sufficient for particular integrations. To use the Salesforce Apex REST API, you should first familiarize yourself with the basics of RESTful web services and JSON representations.

Simplify Salesforce ETL and Analysis with Hevo’s No-code Data Pipeline

Looking for an easy way to replicate data from Salesforce? A fully managed No-code Data Pipeline platform like Hevo Data helps you integrate and load data from 150+ different sources (including 40+ free sources such as Salesforce) to a Data Warehouse or Destination of your choice in real-time in an effortless manner.

Sign up here for a 14-Day Free Trial!

Salesforce Apex REST API Key Methods

Apex code has several built-in methods that you can leverage when creating standard HTTP request-response protocols between a client and the Salesforce platform. These include standard methods such as GET, POST, PUT, and DELETE.

The REST callouts in Apex are associated with HTTP methods and endpoints. The HTTP method request that you callout will dictate the type of action that is desired for a given resource. You can call out these API methods to receive data from an external service or send data from Apex code to an external service.

REST guidelines recommend using a specific HTTP method on a particular type of call made to the server. These HTTP methods are as follows:

1) GET

You can use the HTTP GET method to read (or retrieve) a resource representation. GET returns a representation in JSON or XML format in the safe path and an HTTP response code of 200 (OK). It most often returns a 400 (BAD REQUEST) or 404 (NOT FOUND) in an error case. 

2) POST

The POST verb is most often used for creating new resources. In particular, developers use it to create subordinate resources. On successful creation, POST returns HTTP status 201, returning a Location header with a link to the newly created resource.

3) PUT

PUT method can be used for updating the capabilities. However, you can also use PUT to create a resource where a client chooses the resource ID instead of the server.

4) PATCH

You can use the PATCH method to modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource. This resembles PUT, but the body has a set of instructions describing how you should modify a resource currently residing on the server to produce a new version.

5) DELETE

You can use the DELETE method to delete a resource identified by a URL. 

Further information:

From the above classification, you can see that the least difficult and most commonly used Apex REST API method that you can call out is a GET request. A GET request signifies that a client (sender) wants to retrieve data about a specific resource from the server. Once the server receives a GET request, it will process the request and return the requested information to the client.

You often use a lot of GET requests when browsing the internet. For example, let’s say you want to access your Facebook account on your phone. You fire up your browser and click on the Facebook bookmark. Your browser then performs a GET request soliciting for Facebook’s home page. The HTML page displayed on your screen is the response object.

To better understand how a GET request works, you can visit here.

On clicking the link, you will get the following result:

{"animals":["majestic badger","fluffy bunny","scary bear","chicken"]}

Your browser is displaying a list of animals in JSON key-value format. This data on display is the GET response from the web service.

The anatomy of a HTTP request dictates that apart from declaring the HTTP method, you should also specify the set a URL endpoint address that points to where the service is hosted. In the above example, the following endpoint is used: https://th-apex-http-callout.herokuapp.com/animals

It is in the format: “http://www.example.com/api/resource

Once the server completes processing the API request, it will send a HTTP status code in the response body. Depending on the status code that is returned, you can establish whether the request was successful or whether your request ran into some errors. For a successful request, you will receive the 200 status code. A 404 status code indicates that a file was not found and a 500 status code indicates that there was an internal server error.

You can browse through the various HTTP response status codes from this resource: For further information about HTTP response status code, you can visit here.

In addition to the URL endpoint and the HTTP method, you can set extra properties in a HTTP request. For instance, an HTTP request can include headers with additional information about the request, e.g. content type. In the case of POST requests, you can even include the data to be sent to the service.

Overview of the Apex REST API Callout Architecture 

Before diving into the examples let’s first look at the anatomy of a Salesforce APEX REST API callout. Apex provides mainly three built-in classes to work with HTTP services and create HTTP requests:

  • Http Class: It is used when initiating an HTTP request and response.
  • HttpRequest Class: It is used when initiating HTTP requests such as GET, DELETE, POST, PUT, and PATCH.
  • HttpResponse Class: It is used when handling the HTTP response returned by HTTP.

Prerequisites

  • To follow along, you will need access to Salesforce Classic or Lightning Experience. If you already have any of these, then you canmove forward.
  • Next, you will need to authorize the external site in the Remote Site Settings. This step is necessary because Salesforce prevents API calls to unauthorized network addresses.
To add a remote site you can follow these steps:
  • Step 1: From Setup, select “Remote site settings” in the Quick Find box. This will take you to the Remote site details page.
  • Step 2: Enter animals_http as the descriptive name for the Remote Site.
  • Step 3: Enter the Remote Site URL. In this case, the URL is https://th-apex-http-callout.herokuapp.com.
  • Step 4: For the description of the site, enter Salesforce HTTP Animal Service
  • Step 5: Click “Save & New“.
Create an Apex class that calls a REST endpoint
Image Source

Examples

Let’s now look at some Apex REST API example of how we can use the Salesforce Apex API to perform some basic REST API callouts.

A) Get Data from an External Service Using the Apex REST API

The result you got earlier from soliciting a GET request from your browser:

{"animals":["majestic badger","fluffy bunny","scary bear","chicken"]}

Let’s write an Apex Class that sends a GET request to the same endpoint to retrieve the value of the ‘name’ property (i.e., the animal name). 

The external web service will send back the response in JSON format. Since JSON is essentially a string, you will be using the built-in Apex JSONParser class to convert it to an object.

The steps to be followed are:

  • Step 1: In your Salesforce org, click the photo icon next to your username on the upper right corner of the screen. 
  • Step 2: A dropdown menu will appear. Select “Developer Console“.
  • Step 3: In the Developer Console, click the “File” option, select “New” and then click on “Apex Class“.
  • Enter the name AnimalLocator as the Apex Class name.
  • Implement the class as follows:
public class AnimalLocator {
    public static String getAnimalNameById(Integer id){
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+id);
        request.setMethod('GET');
        System.debug('>>>>>>>'+id);
        HttpResponse response = http.send(request);
      Object animals;
        String returnValue;
       
        // If the request is successful, parse the JSON response
        if (response.getStatusCode() == 200) {
            // Deserialize the JSON string into collections of primitive data types.
            Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            System.debug('>>>>>'+response.getBody());
            animals = result.get('animal');
            System.debug(animals);
        }
        if (animals != NULL  ) {
            Map<String, Object> result1 = (Map<String, Object>) JSON.deserializeUntyped(JSON.serialize(animals));
            returnValue =(String) result1.get('name');
        }
        return returnValue;
    }
}
  • Step 6: Click on “File” and then click the “Save” button to save the file.

Now execute the ‘getAnimalNameById’ method in the Developer Console. To do this the steps to be followed are:

  • Step 1: Go to “Debug” and then click on “Open“.
  • Step 2: Use the “CTRL + E” shortcut to open a window to execute the Apex code.
  • Step 3: Enter the method with the parameters. For example: getAnimalNameById.
  • Step 4: Click on “Execute“.
  • Step 5: This should return the string “scary bear“.

B) Send Data to an External Service Using the Apex REST API

Let’s now look at how you can execute an HTTP POST request to send data to an external web service. The data packet again will be in JSON format.

public class AnimalUpdater {
    public static String sendAnimalName(){

        Http http = new Http();
        HttpRequest request = new HttpRequest();
   
      request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        // Set the body as a JSON object
        request.setBody('{"name":"savage crocodile"}');
        HttpResponse response = http.send(request);
        // Parse the JSON response
        if (response.getStatusCode() != 201) {
            System.debug('The status code returned was not expected: ' +
    response.getStatusCode() + ' ' + response.getStatus());
        } else {
            System.debug(response.getBody());
        }
    }
}

Now you can execute the ‘sendAnimalName’ method in the Developer Console.

From our external endpoint, you will see that we have successfully appended the name “savage crocodile” to the list of animals.

Limitations

  • Before making any Apex REST API request to an external web service, that service should first be registered and authorized on the Remote Site Settings page, otherwise, the request will fail.
  • There is a limit of 100 HTTP requests for a single Apex API request.
  • There is an execution limit on long-running requests that take more than 5 seconds to process.
  • An HTTP request cannot be made if there are pending operations within the same transaction.
  • A timeout will occur when the header Expect: 100-Continue is added to an HTTP request and an HTTP/1.1 100 Continue response isn’t returned by the external service, a timeout will occur.

Conclusion

In this article, you have learned about implementing Salesforce Apex REST APIs. This article also provided information on Salesforce, its key features, APIs, and the basics of using the Salesforce Apex REST API to write custom codes.

Hevo is the only real-time ELT No-code Data Pipeline platform that cost-effectively automates data pipelines that are flexible to your needs. With integration with 150+ Data Sources (40+ free sources), we help you not only export data from sources & load data to the destinations but also transform & enrich your data, & make it analysis-ready.

Visit our Website to Explore Hevo

Want to give Hevo a try?

Sign Up for a 14-day free trial and experience the feature-rich Hevo suite first hand. You may also have a look at the amazing Hevo price, which will assist you in selecting the best plan for your requirements.

Share your experience of understanding Salesforce Apex REST APIs in the comment section below! We would love to hear your thoughts.

mm
Principal Frontend Engineer, Hevo Data

With over a decade of experience, Suraj has played a crucial role in architecting and developing core frontend modules for Hevo. His expertise lies in building scalable UI solutions, collaborating across teams, and contributing to the open-source community, showcasing a deep commitment to innovation in the tech industry.

No-code Data Pipeline for Google BigQuery

Get Started with Hevo