Salesforce is one of the fastest-growing Enterprise SaaS platforms. Marc Benioff founded Salesforce.com in 1999, and today, Salesforce is one of the most dominant software on the planet. Salesforce is a Cloud-Based “Customer Relationship Management” (CRM) software. It provides a full-fledged Customer Relationship Management solution to businesses without spending much effort on building one. Salesforce’s services allow businesses to use Cloud Technology to better connect with clients, customers, and partners.
By integrating your Salesforce org with third-party applications, you get to unlock functionalities that are streamlined towards 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, the methids used to call the REST interface directly. Read along to find out in-depth information about Salesforce Apex REST APIs.
Table of Contents
Introduction to Salesforce
Image Source
Salesforce is a Cloud-based Customer Relationship Management Platform that offers easy-to-use business applications that can help build an amazing customer experience. Salesforce is a tool that you can use to stay connected with Customers, Prospects, Partners, Sales, and Market Services worldwide. Salesforce Cloud CRM software and applications are used for Sales, Services, Finance, Marketing, Business Development, Supply Chain Management, and other business verticals that involve external and internal relationships.
It allows the user to store information of existing customers and prospects under a single platform. In addition, it enables the user to monitor Sales and Marketing Campaigns using the valuable insights available. It is a complete solution for companies that want to easily manage customer data from various platforms such as Email, Chat, and Social Media.
For further information on Salesforce, you can follow the Official Documentation.
Key Features of Salesforce
Some of the key features of Salesforce are as follows:
1) Simplified Account Management
Salesforce enables companies to have a holistic view of their customers. It allows you to always have access to the Activity History, Customer Communication, Important Contacts, Internal Account Discussions, etc.
2) Lead Management
Salesforce enables companies to track their Leads and continuously optimize their Campaigns across all channels so that they can make data-driven decisions.
3) Sales Data
With Salesforce, companies can get easy access to the Sales Data in real-time which can be used to connect with Leads and increase Marketing productivity.
4) Reports and Dashboards
Salesforce Dashboards provide a real-time and intuitive view of your business performance. It enables companies to view detailed reports that can be seamlessly accessed by any of the team members.
5) File Sync and Sharing
Salesforce gives companies the ability to easily share files, discuss them with the entire team, and track its content in real-time. Users can also use the Quick Search option to search a specific section of the content.
6) Workflow and Approvals
With Salesforce Visual Workflow, companies can quickly design and automate all business processes by leveraging the drag-and-drop functionality that can be used to drive success with flexible approval processes for Expenses, Customer Discounts, Trial Periods, and more.
Introduction to API
Image Source
API stands for Application Programming Interface. An API is the programmatic code that enables two applications to communicate over the internet. REST on the other hand is an acronym for Representational State Transfer. It is the architectural framework that provides unified standards that allow for communication between computer systems on the internet. Most REST APIs mainly send and receive information using any data format but all the cool kids favor JSON or XML.
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.
A fully managed No-code Data Pipeline platform like Hevo Data helps you integrate and load data from 100+ different sources (including 30+ free sources such as Salesforce) to a Data Warehouse or Destination of your choice in real-time in an effortless manner. Hevo with its minimal learning curve can be set up in just a few minutes allowing the users to load data without having to compromise performance. Its strong integration with umpteenth sources allows users to bring in data of different kinds in a smooth fashion without having to code a single line.
Get Started with Hevo for Free
Check out some of the cool features of Hevo:
- Completely Automated: The Hevo platform can be set up in just a few minutes and requires minimal maintenance.
- Transformations: Hevo provides preload transformations through Python code. It also allows you to run transformation code for each event in the Data Pipelines you set up. You need to edit the event object’s properties received in the transform method as a parameter to carry out the transformation. Hevo also offers drag and drop transformations like Date and Control Functions, JSON, and Event Manipulation to name a few. These can be configured and tested before putting them to use.
- Connectors: Hevo supports 100+ integrations to SaaS platforms, files, Databases, analytics, and BI tools. It supports various destinations including Google BigQuery, Amazon Redshift, Snowflake Data Warehouses; Amazon S3 Data Lakes; and MySQL, SQL Server, TokuDB, DynamoDB, PostgreSQL Databases to name a few.
- Real-Time Data Transfer: Hevo provides real-time data migration, so you can have analysis-ready data always.
- 100% Complete & Accurate Data Transfer: Hevo’s robust infrastructure ensures reliable data transfer with zero data loss.
- Scalable Infrastructure: Hevo has in-built integrations for 100+ sources (including 30+ free sources such as Salesforce) that can help you scale your data infrastructure as required.
- 24/7 Live Support: The Hevo team is available round the clock to extend exceptional support to you through chat, email, and support calls.
- Schema Management: Hevo takes away the tedious task of schema management & automatically detects the schema of incoming data and maps it to the destination schema.
- Live Monitoring: Hevo allows you to monitor the data flow so you can check where your data is at a particular point in time.
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“.
Image Source
Examples
Let’s now look at some examples 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 ibasics of using the Salesforce Apex REST API to write custom codes.
Hevo Data, a No-code Data Pipeline provides you with a consistent and reliable solution to manage data transfer between a variety of sources and a wide variety of Desired Destinations with a few clicks.
Visit our Website to Explore Hevo
Hevo Data with its strong integration with 100+ data sources (including 40+ free sources such as Salesforce) allows you to not only export data from your desired data sources & load it to the destination of your choice but also transform & enrich your data to make it analysis-ready so that you can focus on your key business needs and perform insightful analysis using BI tools.
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 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.