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.
- Salesforce Org – Developer Org Signup (if youdon’t already have one)
- Postman– Helps organize and simplify REST operations
- Code Editor –
- VSCode & ForceCode(my preference)
- Eclipse& Force.comPlugin (old school)
- SalesforceDeveloper Console(if you don’t feel like installing anything)
Limits
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 differentnames. Salesforce calls it a ConnectedApp. All it does is provide a “hall pass” to authorizedsystems/applications to access the database. In this case, the database isSalesforce. You get to define where the requests can come from and how muchdata it has access to.
To start, you must go into the setupof your Salesforce org. In the quick find, type “App Manager” until the optionshows up.

Fromthere, 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 dothis or else the following steps won’t work. Click “Manage” and then “EditPolicies.” Change “IP Relaxation” to RelaxIP 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.
- Production
- https://login.salesforce.com/services/oauth2/token?grant_type=password&client_id=ConsumerKey&client_secret=ConsumerSecret&username=SalesforceUserName&password=SalesforcePassword
- Sandbox (Full, Partial, Dev)
- https://test.salesforce.com/services/oauth2/token?grant_type=password&client_id=ConsumerKey&client_secret=ConsumerSecret&username=SalesforceUserName&password=SalesforcePassword
When you’re done, it should look a lot like this:

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.
- https://instanceurl/services/data/v43.0/sobjects/Objectname/Id
In this example, I’m going to getSMG3’s Account in our system. The text would be:
- https://smg3login–Dev.cs47.my.salesforce.com/services/data/v43.0/sobjects/Account/0012a00000ZR1YzAAL

Next, you’llhave 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 successfulconnection to Salesforce through a Connected App, lets look at something morecomplex. Apex has a set of REST methods which allow you to define logicendpoints. This can be incredibly helpful to simplify and standardize yourlogic. I prefer Apex REST over writing large and complex SOQL queries in my“standard” REST requests. In addition to reducing overall complexity, I find itto be a best practice to keep as much logic centralized within Salesforce aspossible.
In this example, we’re going tobuild the following requirements. This example is simple to fulfill in Apex butoverly difficult in standard REST (or downright impossible). Salesforceprovides documentationon how to implement REST methods in Apex but I’m going to provide a simplifiedexplanation.
- Get the name of Accounts with a predefinednumber 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 withit.
- @RestResource(urlMapping=’/AccountCountExample/*’)
- globalclassApexRestExample{
- @HttpPost
- globalstaticList<Account>getAccountCount(IntegercontactCount)
- {
- }
- }
Lets breakdown this skeleton.
- @RestResource(urlMapping=’/AccountCountExample/*’)
This provides Salesforce with theknowledge that anytime someone makes a REST request with this path, its talkingabout this class.
- globalclassApexRestExample{
Anytime you make a class for REST,you must set it to global. This allows any other part of the system toaccess the methods inside.
- @HttpPost
- globalstaticList<Account>getAccountCount(IntegercontactCount)
@HttpPost is anannotation of Salesforce’s Apex REST Methods to signify anytime the RESTrequest is of type “POST”, then use this method. You can only have one of eachREST type in a class (e.g. GET, POST, PUT, etc)
In addition, we’re defining a namefor 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 whatthe Apex class would like plus comments explaining each subsection.
- @RestResource(urlMapping=’/AccountCountExample/*’)
- globalclassApexRestExample{
- @HttpPost
- globalstaticList<Account>getAccountCount(IntegercontactCount)
- {
- //Listwhichwillcontainthefinalresult
- List<Account>listOfAccountsToReturn=newList<Account>();
- //QuerytogetallAccountswithatleastoneContact
- List<Account>listOfAccounts=([SELECTId,
- Name,
- (SELECTId
- FROMContacts)
- FROMAccount
- WHEREIdIN(SELECTAccountIdFROMContact)]);
- //CyclethroughalltheAccountsandmakesuretheContact
- //CountmatchestheactualnumberofContacts
- for(AccounttempAccount:listOfAccounts)
- {
- Integercount=0;
- for(ContacttempContact:tempAccount.Contacts)
- {
- count++;
- }
- if(count==contactCount)
- {
- listOfAccountsToReturn.add(tempAccount);
- }
- }
- returnlistOfAccountsToReturn;
- }
- }
One of the big reasons why Iprefer this methodology is so I can write simple Test Classes such as below. Itincreases my system’s coverage and ensure stability in the logic itself. Theclass 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 thereisn’t an Account with three Contacts.
- @isTest
- publicclassApexRestExampleTest{
- @TestSetup
- staticvoidmakeData()
- {
- //OneAccountwithasingleContact
- AccounttempAccount1=newAccount();
- tempAccount1.Name=‘ApexRestExampleTest1’;
- inserttempAccount1;
- ContacttempContact1=newContact();
- tempContact1.AccountId=tempAccount1.Id;
- tempContact1.LastName=‘ApexRestExampleTest1’;
- inserttempContact1;
- //OneAccountwithtwoContacts
- AccounttempAccount2=newAccount();
- tempAccount2.Name=‘ApexRestExampleTest2’;
- inserttempAccount2;
- ContacttempContact2=newContact();
- tempContact2.AccountId=tempAccount2.Id;
- tempContact2.LastName=‘ApexRestExampleTest2’;
- inserttempContact2;
- ContacttempContact3=newContact();
- tempContact3.AccountId=tempAccount2.Id;
- tempContact3.LastName=‘ApexRestExampleTest2’;
- inserttempContact3;
- }
- publicstaticTestMethodvoidtestEndpointSingleAccountOneContact()
- {
- Test.startTest();
- List<Account>returnedList=ApexRestExample.getAccountCount(1);
- System.assertEquals(1,returnedList.size());
- AccounttempAccount=returnedList.get(0);
- System.assertEquals(‘ApexRestExampleTest1’,tempAccount.Name);
- Test.stopTest();
- }
- publicstaticTestMethodvoidtestEndpointSingleAccountTwoContacts()
- {
- Test.startTest();
- List<Account>returnedList=ApexRestExample.getAccountCount(2);
- System.assertEquals(1,returnedList.size());
- AccounttempAccount=returnedList.get(0);
- System.assertEquals(‘ApexRestExampleTest2’,tempAccount.Name);
- Test.stopTest();
- }
- publicstaticTestMethodvoidtestEndpointSingleAccountThreeContactsZeroResults()
- {
- Test.startTest();
- List<Account>returnedList=ApexRestExample.getAccountCount(3);
- System.assertEquals(0,returnedList.size());
- Test.stopTest();
- }
- }
Putting It All Together
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 thisinstance, I’m using:
https://smg3login–Dev.cs47.my.salesforce.com/services/apexrest/AccountCountExample/
Then we must define theContent-Type. That’s basically just saying “I’m expecting the response to comeback in a specific format”. In this case, we want JSON (JavaScript Object Notation). You make this change by going into the “Headers” tab andsetting the key value “Content-Type” to “application/json”.

Lastly, we must define theparameter(s). under the “Body” tab, paste this into it
- {
- “contactCount”:“1”
- }
Notice the name of the valuematches the Apex parameter name. That’s intentional and what you need to do forthe parameter to get passed along. For this example, I’m just looking forAccounts with a single Contact related to it, hence the value of “1”.
Click send and see the responsebelow:

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.
[2] https://en.wikipedia.org/wiki/Application_programming_interface
FAQs
What is the difference between REST API and Apex REST API? ›
The REST API (Force.com REST API) is the generic API provided by Salesforce. On the other hand, the Apex REST API is an API written by yourself in apex to provide custom methods. The Force.com REST API is great for things such as CRUD operations.
What is the difference between apex SOAP API and apex REST API? ›The major difference between SOAP and REST API include:
SOAP API has official standards because it's a protocol. REST API has no official standards because it's an architectural style of coding and tags. REST API uses Web Application Description Language to describe service.
- Go with the SOQL query approach in the REST API call and keep it simple. ...
- Create a bunch of wrapper Apex classes that “hide” The SOQL and give us more flexibility – the downside here is then we're maintaining a bunch of custom code.
From Setup, in the Quick Find box, enter API Access Control , and then select API Access Control. Click Edit, and then select For admin-approved users, limit API access to only allowlisted connected apps.
How do I write REST API in Apex? ›by defining your Apex class with the @RestResource annotation to expose it as a REST resource. Similarly, add annotations to your methods to expose them through REST. For example, you can add the @HttpGet annotation to your method to expose it as a REST resource that can be called by an HTTP GET request.
Is there anything better than REST API? ›GraphQL is widely tagged as a better REST because it represents a better way of building APIs. Many developers believe that GraphQL will replace REST. Many more have already discovered that GraphQL helps solve some common challenges developers face while building REST APIs.
Which API is faster SOAP or REST? ›REST supports XML, JSON, plain text, HTML. SOAP messages are larger, which makes communication slower. REST has faster performance due to smaller messages and caching support.
Which API is best REST or SOAP? ›REST is a better choice for simple, CRUD-oriented services, because of the way REST repurposes HTTP methods (GET, POST, PUT, and DELETE). It is also popular because it's lightweight and has a smaller learning curve. SOAP, on the other hand, has standards for security, addressing, etc.
What is the difference between native API and REST API? ›Generally, APIs are lightweight architectures that are designed for gadgets constrained to devices like smartphones. In contrast, REST APIs communicate over systems, making it a complex architecture.
What are the 4 most common REST API operations? ›For REST APIs built on HTTP, the uniform interface includes using standard HTTP verbs to perform operations on resources. The most common operations are GET, POST, PUT, PATCH, and DELETE. REST APIs use a stateless request model.
What is the most common method of REST API? ›
The POST method is one of the most commonly used HTTP methods in REST APIs and is used to create a new resource on the server. Unlike the GET method, which is used to retrieve resources, the POST method is used to submit data to the server for processing.
What is the best authentication method for REST API? ›- #1 API Key (identification only) One of the easiest ways to identify an API client is by using an API key. ...
- #2 OAuth2 token. OAuth2 is a comprehensive industry standard that is widely used across API providers. ...
- #3 External token or assertion. ...
- #4 Token Exchange. ...
- #5 Identity facade for 3 legged OAuth.
To make a connected app inaccessible to your org's users, block the app. This action ends all current user sessions with the connected app and prevents all new sessions until you unblock the app. A start URL defines the page where users are directed to when they run the connected app.
What is the difference between remote site settings and connected app in Salesforce? ›Remote Site Settings: Whenever you want to access any external sites in your salesforce instance using webservices, callouts etc., you must have that in the Remote Site Settings. Connected App: Used for making the connection from outside to Salesforce. I hope you find the above solution helpful.
What is the use of connected app in REST API in Salesforce? ›These connected apps can send a request to Salesforce asking for access to data protected by the API gateways. Salesforce can then authorize the connected apps, granting them access to the data protected by the API gateways.
What is Apex REST API? ›Apex REST services are used to expose Salesforce data and functionality via RESTful APIs. They allow developers to create custom endpoints to access data and execute custom logic. In this blog, we will explore the various aspects of Apex REST services and provide some examples to illustrate their usage.
What is REST API in Oracle APEX? ›Representational State Transfer (REST) is a way of providing interoperability between computer systems over the Internet. You can define the RESTful services to allow the querying and manipulation of data without the need for direct access to the underlying data store.
What API is used in Apex? ›Use Apex REST API when you want to expose your Apex classes and methods so that external applications can access your code through REST architecture. Apex REST API supports both OAuth 2.0 and Session ID for authorization.
How many types of REST APIs are there? ›The main types of APIs include Open, Partner, Private, and Composite APIs. RESTful API is an architectural style characterized by client-server separation, HTTP interface, and statelessness. SOAP, XML-RPC, JSON-RPC, and Thrift are other popular API protocols with unique features and use cases.