Creating a Custom Salesforce REST API Endpoint

Sharing is Caring

Salesforce is a large application that can be used for Customer Relationship Management (CRM). This means that it should contain a complete view of a company’s customers. To get a complete view of a customer, we need to integrate processes and applications.

Apex classes and methods can be exposed to external applications as REST based endpoints. This means that there’s a very easy way to have an external application make a direct call into Salesforce to do a specific action.

Why would we setup a Custom Salesforce REST API Endpoint?

  • The standard API and the standard API queries will couple Salesforce and our external application directly. A change in Salesforce can cause the integration to fail, there’s a good chance that there’s no logging.
  • The external application doesn’t need to know the Salesforce data model. The Salesforce custom endpoint can accept JSON and map the file to the Salesforce data model.
  • This is a good way of getting around Salesforce governor limits when you need to do a lot of processing in a Visualforce or in Salesforce Lightning. Custom Salesforce REST API endpoints can be configured to use the Salesforce Session Id. I do this a lot from the Salesforce Community (Digital Experience).
  • It’s possible to avoid setting up a Connected App and going through the hassle of oAuth 2.0. To do this you would need to use a Public Site and then enable the class for the public site. It’s not ideal, but it’s possible.

How to Setup a Class for REST API

To expose a class to the Salesforce REST Architecture we need to annotate it with “@RestResource” and then annotate the methods we want to be accessible with “@HttpGet” or “@HttpPost”.

The @RestResource annotation is used at the class level and enables you to expose an Apex class as a REST resource. When annotating with @RestResource we need to pass a path which will then map to a URL from Salesforce that’s related to our instance.

Any method that we want to annotate for GET, PUT, POST, DELETE or etc needs to be global static.

Here’s an example of a class that has a PUT method at /accounts/activate.

A put to the endpoint in Postman would look something like this:

I typically use custom REST endpoints to do an action in Salesforce and require an API token which is really just a randomly generated string.

Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.