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.
Table of Contents
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.
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 PipelineLooking 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.
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:
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.
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.
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.
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.
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:
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.
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:
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.
The result you got earlier from soliciting a GET request from your browser:
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:
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. Mapresult = (Map) JSON.deserializeUntyped(response.getBody()); System.debug('>>>>>'+response.getBody()); animals = result.get('animal'); System.debug(animals); > if (animals != NULL ) < Mapresult1 = (Map) JSON.deserializeUntyped(JSON.serialize(animals)); returnValue =(String) result1.get('name'); > return returnValue; > >
Now execute the ‘getAnimalNameById’ method in the Developer Console. To do this the steps to be followed are:
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(''); 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.
Learn More About:
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.
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.
Suraj Poddar Principal Frontend Engineer, Hevo DataSuraj has over a decade of experience in the tech industry, with a significant focus on architecting and developing scalable front-end solutions. As a Principal Frontend Engineer at Hevo, he has played a key role in building core frontend modules, driving innovation, and contributing to the open-source community. Suraj's expertise includes creating reusable UI libraries, collaborating across teams, and enhancing user experience and interface design.