Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (2023)

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”.

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (1)

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.

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (2)

Fromthere, the “New Connected App” button on the right.

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (3)

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 “”. 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.

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (4)

When you click “save”, you will be greeted with this message. This would be a great time to get a Coffee.

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (5)

Once you’ve clicked “Continue,” your screen will look like this. You’ll be using the Consumer Key and Secret Key later.

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (6)

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.

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (7)

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.

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (8)
Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (9)

Within the Collection, create a Request:

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (10)
Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (11)

The request type needs to be set to “POST” or else this won’t work.

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (12)

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
  • Sandbox (Full, Partial, Dev)

When you’re done, it should look a lot like this:

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (13)

Moment of truth,click the “Send” button and you should see information like this below:

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (14)

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.

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (15)

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–
Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (16)

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.

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (17)
Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (18)

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.
  1. @RestResource(urlMapping=’/AccountCountExample/*’)
  2. globalclassApexRestExample{
  3. @HttpPost
  4. globalstaticList<Account>getAccountCount(IntegercontactCount)
  5. {
  6. }
  7. }

Lets breakdown this skeleton.

  1. @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.

  1. @RestResource(urlMapping=’/AccountCountExample/*’)
  2. globalclassApexRestExample{
  3. @HttpPost
  4. globalstaticList<Account>getAccountCount(IntegercontactCount)
  5. {
  6. //Listwhichwillcontainthefinalresult
  7. List<Account>listOfAccountsToReturn=newList<Account>();
  8. //QuerytogetallAccountswithatleastoneContact
  9. List<Account>listOfAccounts=([SELECTId,
  10. Name,
  11. (SELECTId
  12. FROMContacts)
  13. FROMAccount
  14. WHEREIdIN(SELECTAccountIdFROMContact)]);
  15. //CyclethroughalltheAccountsandmakesuretheContact
  16. //CountmatchestheactualnumberofContacts
  17. for(AccounttempAccount:listOfAccounts)
  18. {
  19. Integercount=0;
  20. for(ContacttempContact:tempAccount.Contacts)
  21. {
  22. count++;
  23. }
  24. if(count==contactCount)
  25. {
  26. listOfAccountsToReturn.add(tempAccount);
  27. }
  28. }
  29. returnlistOfAccountsToReturn;
  30. }
  31. }

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.
  1. @isTest
  2. publicclassApexRestExampleTest{
  3. @TestSetup
  4. staticvoidmakeData()
  5. {
  6. //OneAccountwithasingleContact
  7. AccounttempAccount1=newAccount();
  8. tempAccount1.Name=‘ApexRestExampleTest1’;
  9. inserttempAccount1;
  10. ContacttempContact1=newContact();
  11. tempContact1.AccountId=tempAccount1.Id;
  12. tempContact1.LastName=‘ApexRestExampleTest1’;
  13. inserttempContact1;
  14. //OneAccountwithtwoContacts
  15. AccounttempAccount2=newAccount();
  16. tempAccount2.Name=‘ApexRestExampleTest2’;
  17. inserttempAccount2;
  18. ContacttempContact2=newContact();
  19. tempContact2.AccountId=tempAccount2.Id;
  20. tempContact2.LastName=‘ApexRestExampleTest2’;
  21. inserttempContact2;
  22. ContacttempContact3=newContact();
  23. tempContact3.AccountId=tempAccount2.Id;
  24. tempContact3.LastName=‘ApexRestExampleTest2’;
  25. inserttempContact3;
  26. }
  27. publicstaticTestMethodvoidtestEndpointSingleAccountOneContact()
  28. {
  29. Test.startTest();
  30. List<Account>returnedList=ApexRestExample.getAccountCount(1);
  31. System.assertEquals(1,returnedList.size());
  32. AccounttempAccount=returnedList.get(0);
  33. System.assertEquals(‘ApexRestExampleTest1’,tempAccount.Name);
  34. Test.stopTest();
  35. }
  36. publicstaticTestMethodvoidtestEndpointSingleAccountTwoContacts()
  37. {
  38. Test.startTest();
  39. List<Account>returnedList=ApexRestExample.getAccountCount(2);
  40. System.assertEquals(1,returnedList.size());
  41. AccounttempAccount=returnedList.get(0);
  42. System.assertEquals(‘ApexRestExampleTest2’,tempAccount.Name);
  43. Test.stopTest();
  44. }
  45. publicstaticTestMethodvoidtestEndpointSingleAccountThreeContactsZeroResults()
  46. {
  47. Test.startTest();
  48. List<Account>returnedList=ApexRestExample.getAccountCount(3);
  49. System.assertEquals(0,returnedList.size());
  50. Test.stopTest();
  51. }
  52. }

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

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (19)

Use the appropriate URL. In thisinstance, I’m using:


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”.

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (20)

Lastly, we must define theparameter(s). under the “Body” tab, paste this into it

  1. {
  2. “contactCount”:“1”
  3. }

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:

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (21)

Apex natively provides their data in a JSON structure when its returned. In this case, we see both the Account data

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (22)

And the underlying Contact found in the subquery we did in Apex

Salesforce REST API: Connected Apps & Apex REST Methods | Virtuoso (23)

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.




What is the difference between REST API and Apex REST API? ›

The REST API ( 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 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.

What is the best practice for Salesforce REST API? ›

Salesforce REST API Best Practice
  • 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.
May 18, 2016

How do I control API access for connected apps in Salesforce? ›

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.
Feb 9, 2023

What happens when an admin blocks a connected app in Salesforce? ›

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.

Top Articles
Latest Posts
Article information

Author: Trent Wehner

Last Updated: 07/11/2023

Views: 6334

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Trent Wehner

Birthday: 1993-03-14

Address: 872 Kevin Squares, New Codyville, AK 01785-0416

Phone: +18698800304764

Job: Senior Farming Developer

Hobby: Paintball, Calligraphy, Hunting, Flying disc, Lapidary, Rafting, Inline skating

Introduction: My name is Trent Wehner, I am a talented, brainy, zealous, light, funny, gleaming, attractive person who loves writing and wants to share my knowledge and understanding with you.