Blog: This article assumes you have at least a basic understanding of programming.
What is REST API and Why Should I Use It?
REST API is a beautiful architecture style of handling data between two systems. Its primary focus is simplicity with scalability. But what is REST API? If I pulled out the online dictionary for each acronym, it would be described as follows:
REST – “REST is an acronym for REpresentational State Transfer…”[1] or in other words, it’s a style of handling data between two systems.
API – “… an application programming interface (API) is a set of subroutine definitions, communication protocols, and tools for building software…”[2]. To put it simply, it’s summarizing code functions which may do complex things.
If you made it past the definitions without falling asleep, congrats! You’re doing better than I did my freshman year of college. That’s a lot of jargon, but there is a simpler way to put it. Think of your car’s gas pedal. It receives an input (foot pressing) and gives an output (vibrations from engine speed) between two systems; you and the car.
Keeping up with the car analogy, it’s generally operated the same way across multiple brands and models. It saves you a lot of effort in getting from point A to B. But behind the scenes, the API (or gas pedal) is doing a lot of complex things to make you move. Imagine being forced to reinvent the car on your own. You may have to earn a degree or two in mechanical engineering. That would be insane! APIs, specifically REST APIs, allow programmers to gain all the benefits of integrating two systems together without having to know all the details behind them.
I’ll use “REST,” “API,” and “REST API” interchangeably to mean the same thing for the rest of this article.
Using APIs is extremely helpful when you want to integrate two systems or perform massive amounts of computing. If you’ve spent any time programming in Salesforce, the first word you have engrained in your mind is “limits.” Salesforce is all about limits in order to protect its multi-tenant architecture. REST allows you to work with larger amounts of data in order to bypass these limits.
Tools Needed
You’ll need the following to get started. I won’t be covering how to install them. The sites related to each should have enough instructional material for their own products.
Think you could see any of the code before learning about Salesforce’s limits? Ha! Don’t think you’ll get off that easy. Salesforce details their limits here. To summarize it, you get at least 15,000 requests a day and most orgs I’ve dealt with have at least 350,000 call allocations per 24 hours. Salesforce describes, in length, their API reporting limits here, but if you want to quickly check your org’s limit, simply to go Setup > Quick Find type “Company Information” > “API Requests, Last 24 hours”.
If you want to be extra safe with your org, check out API Usage Notifications so you can stay on top of things long term. Everyone loves automation.
Setup: Connected Apps
Many systems call it by different names. Salesforce calls it a Connected App. All it does is provide a “hall pass” to authorized systems/applications to access the database. In this case, the database is Salesforce. You get to define where the requests can come from and how much data it has access to.
To start, you must go into the setup of your Salesforce org. In the quick find, type “App Manager” until the option shows up.
From there, the “New Connected App” button on the right.
The form requires a name and email. Make sure to “Enable OAuth Settings” in the API section. The callback URL can be anything you want, but if you want to go with a ‘default’, use “https://login.salesforce.com/services/oauth2/callback”. Use the “Full Access” option in the OAuth Scope for now. Ideally, stricter security would be used, but this is for learning purposes with the simplest setup possible.
When you click “save”, you will be greeted with this message. This would be a great time to get a Coffee.
Once you’ve clicked “Continue,” your screen will look like this. You’ll be using the Consumer Key and Secret Key later.
Before we move on, make sure to do this or else the following steps won’t work. Click “Manage” and then “Edit Policies.” Change “IP Relaxation” to Relax IP Restrictions and save.
Setup: Postman
Now we’re cooking with gas! Once your Postman is launched, create a collection which will house all the different queries we’re going to make. If you’re looking for a fast solution, all the examples shown below are here.
Within the Collection, create a Request:
The request type needs to be set to “POST” or else this won’t work.
The URL to get a token is as follows. Replace the bold parameters with their respective values from both your user and the Connected App.
Moment of truth, click the “Send” button and you should see information like this below:
The two pieces of data you will want to take out of this right now is the “access_token” and “instance_url” values. The access token is the special “hall pass” we discussed early. It lets you do whatever you want in the Salesforce system (barring security settings made in the Connected App). The instance URL helps point Salesforce to the right server when communicating with your programs.
Congratulations! You just connected with the system successfully, and now we can communicate with Salesforce from a third-party application. The next section will cover how to query Salesforce and implement advanced techniques for complex solutions with relatively little code.
Testing Queries in Postman
Now that we have a token, lets check out what we can do. To start, we’ll go with getting a record by Id.
Create another request but this time make it a “GET” type.
The structure of the URL used is as follows. Update the sections in bold to the appropriate values.
Next, you’ll have to copy the Access Token to the Authorization tab. Select “bearer token” and paste the token in the text field. Click “Send” and see the results.
Testing Apex REST Methods
Now that we have a successful connection to Salesforce through a Connected App, lets look at something more complex. Apex has a set of REST methods which allow you to define logic endpoints. This can be incredibly helpful to simplify and standardize your logic. I prefer Apex REST over writing large and complex SOQL queries in my “standard” REST requests. In addition to reducing overall complexity, I find it to be a best practice to keep as much logic centralized within Salesforce as possible.
In this example, we’re going to build the following requirements. This example is simple to fulfill in Apex but overly difficult in standard REST (or downright impossible). Salesforce provides documentation on how to implement REST methods in Apex but I’m going to provide a simplified explanation.
Get the name of Accounts with a predefined number of Contacts. No more, no less. For instance, if I pass a parameter of 3 (three), it should only return Accounts which have 3 Contacts associated with it.
This provides Salesforce with the knowledge that anytime someone makes a REST request with this path, its talking about this class.
global class ApexRestExample {
Anytime you make a class for REST, you must set it to global. This allows any other part of the system to access the methods inside.
@HttpPost
global static List<Account> getAccountCount(Integer contactCount)
@HttpPost is an annotation of Salesforce’s Apex REST Methods to signify anytime the REST request is of type “POST”, then use this method. You can only have one of each REST type in a class (e.g. GET, POST, PUT, etc)
In addition, we’re defining a name for the function and number of parameters (contactCount) and return type (List<Account>) desired for the function to work correctly.
Below is a full example of what the Apex class would like plus comments explaining each subsection.
global static List<Account> getAccountCount(Integer contactCount)
{
// List which will contain the final result
List<Account> listOfAccountsToReturn = new List<Account>();
// Query to get all Accounts with at least one Contact
List<Account> listOfAccounts = ([SELECT Id,
Name,
(SELECT Id
FROM Contacts)
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact)]);
// Cycle through all the Accounts and make sure the Contact
// Count matches the actual number of Contacts
for(Account tempAccount : listOfAccounts)
{
Integer count = 0;
for(Contact tempContact : tempAccount.Contacts)
{
count++;
}
if(count == contactCount)
{
listOfAccountsToReturn.add(tempAccount);
}
}
return listOfAccountsToReturn;
}
}
One of the big reasons why I prefer this methodology is so I can write simple Test Classes such as below. It increases my system’s coverage and ensure stability in the logic itself. The class provides both
100% code coverage and
three separate tests
(1) one Account with one Contact
(2) one Account with two Contacts
(3) a check to make sure no results if there isn’t an Account with three Contacts.
Now that we have a client (Postman) and an endpoint with specialized logic (Salesforce Apex), we can put it all together by creating a request.
First, we must make the type of request “POST” in order to match up with the Apex logic
Use the appropriate URL. In this instance, I’m using:
Then we must define the Content-Type. That’s basically just saying “I’m expecting the response to come back in a specific format”. In this case, we want JSON (JavaScript Object Notation). You make this change by going into the “Headers” tab and setting the key value “Content-Type” to “application/json”.
Lastly, we must define the parameter(s). under the “Body” tab, paste this into it
{
“contactCount” : “1”
}
Notice the name of the value matches the Apex parameter name. That’s intentional and what you need to do for the parameter to get passed along. For this example, I’m just looking for Accounts with a single Contact related to it, hence the value of “1”.
Click send and see the response below:
Apex natively provides their data in a JSON structure when its returned. In this case, we see both the Account data
And the underlying Contact found in the subquery we did in Apex
That’s it! Now you’re equipped with the knowledge to produce complex integrations between two different systems.
Source code
As with any code tutorial on the internet, I’ve created a Github repository containing all the different components built here. Feel free to download or Fork it for your own purposes.
Maintaining visibility is a cornerstone of efficient operations in the fast-paced world of warehousing and logistics. Visibility minimizes missteps, reduces costly errors, and ensures a seamless workflow, helping businesses stay competitive. Salesforce provides warehouse operators with the tools they need to achieve oversight mitigation effectively. A Salesforce integration partner can help you leverage advanced features […]
Salesforce can be a magical platform when used to its full potential. However, many of us aren’t using half of its powers. To unlock Salesforce’s sorcery, you need to know all the spells. Partnering with a company like Virtuoso which specializes in training for salesforce will help you unlock the magic. With the right salesforce […]
Ah, Salesforce—the tool that can keep your business organized and energized. It’s a potent platform with many capabilities, but let’s be real — exploring Salesforce’s ins and outs can sometimes feel like doing a puzzle without the picture. But don’t worry! Whether you’re just starting or trying to make sense of your current setup, I […]
Team Virtuoso is a privately held, women and veteran-owned LLC. Headquartered in Chicago with employees across the U.S., Team Virtuoso readily serves customers throughout North America.