Share this article...
There comes a point for any Salesforce Developer… you find yourself needing to integrate an external system with Salesforce. While you could look for an AppExchange solution that meets your requirements, there are many scenarios where you need to access this data programmatically from a different system. It’s times like these when the Salesforce REST API can save the day, providing powerful programmatic access to data and metadata contained within your org, all while being flexible enough to support applications of any scale.
But what exactly is a REST API? A Representational State Transfer Application Programming Interface (REST API for short) is a type of web service that exposes access to different resources in which a client can interact through the use of unique URLs and HTTP methods to indicate the requested action. Looking at it from a Salesforce perspective, this could be having endpoints to perform actions such as retrieving record details, updating a record, or creating a new record.
What Can We Do With the Rest API?
The REST API offered by Salesforce can be broken down into different sections based on their functionality. At its simplest, it can perform simple CRUD operations, allowing you to create, read, update, and delete records within an org.
However, the fun really starts when you step outside of these simple operations and dig a little deeper to begin utilizing the more complex available endpoints. Doing so unlocks a wealth of additional functionality which can really take your integration to the next level.
- Invocable Actions: Allows you to invoke custom and standard invocable actions, which includes invoicing Apex, sending email alerts and triggering quick actions.
- Analytics: Access reports and dashboards; for example, running reports and refreshing dashboards.
- Chatter/Connect API: Lets you perform chatter actions, such as making posts and attaching and sharing files.
- Compact Layouts: Get the details of compact layouts for sObject types.
- Composite: A special API that allows you to combine multiple requests into a single request.
- sObject Tree: A special data structure for creating records, which contains a set of parent/child records and their relationships.
- Connect: Specialized for building external/mobile apps that need to integrate into salesforce. Its data responses are structured in a way more suited for these scenarios.
- Jobs: Despite its name, this is related to Bulk API v2 jobs, such as adding records to jobs and checking their status.
- Limits: Provides information about current limits within an org, such as API calls, data storage, and many more.
- Metadata: Arguably the most used API (you’ve probably used it many times even if you didn’t realise it!) which provides access to all the different types of metadata within an org, allowing you to add, update, and delete pieces of metadata.
- Query: Perform SOQL queries against the org.
- Quick Actions: Get information about, and invoke, quick actions.
- Recently Viewed Item: get details about the most recently viewed/referenced records for the running user.
- Search: Perform a SOQL query against the org.
- Lightning Metrics: Get different metrics about how Lightning is used within an org, including details about page usage and switches to Classic.
- sObject Describe: Get details about sObject types, including fields, layouts and relationships.
- List Views: Get descriptions (e.g. columns and the query for) about list views. Can also be used to execute the list view query and get the results.
- sObject Get Update: Does exactly what it says on the tin: gets the updated records (created or changed) for a time period.
- sObject Rows: Despite its name, this one works on an individual record, allowing you to get the record details, or perform updates/delete the record.
- sObject Relationships: Similar to sObject Rows, however this lets us perform actions on related records based on a relationship name.
- Streaming API: Used to enable streaming of events, and the subscriptions of those events through a Publisher/Subscriber (pub/sub) model. These could be platform events or change data capture events.
- Tooling API: Another big and commonly used API, intended to allow developers to build custom development tools and apps, and allowing you to use SOQL to query different pieces of metadata. In some cases, you can even perform actions on them that aren’t enabled via the Metadata API.
- UI API: Another big one, and one that developers and end users are likely using on a daily basis without even realizing it. This API excels in allowing developers to build UIs for mobiles and web apps, including retrieving data related to records, all while respecting permissions. In fact many of the standard wire adapters for LWC are actually powered by this API.
READ MORE: Salesforce DX Packaging and Metadata API Overview
As you can see from the list above, there’s a huge number of different services available via the REST API, ranging from ones allowing programmatic access to information already accessible within an org, to others allowing you to shape the org to your requires, or simply use an orgs metadata to drive a different app, without having to hard code things. This isn’t even a complete and exhaustive list, as for brevity, I’ve condensed it down into what I believe to be the most useful and likely to be used. For the complete list, please refer to here.
How Can We Use It?
The very first and most important step to using any of these APIs is authentication. It’s not as simple as using your username and password to log in, but with very good reason – since these APIs can do a whole lot of stuff and are always coming from an external integration, authentication needs to be taken very seriously. If your credentials were to become compromised, imagine the havoc a bad actor could wreak!
Instead, for authentication we use OAuth 2.0, with which we can define a scope for our specific app. This allows us to limit what a specific integration can do with a set of credentials, allowing you further security beyond simple permissions. But how exactly do we do this?
A connected app is the entry point for any calls to the REST API, and is thankfully something we can easily create by going to App Manager in Setup and clicking the “New Connected App” button in the top right.
On the next page, you can enter basic information about the connect app to help you more easily identify it. There is also a section called API (Enabled OAuth Settings) that you’ll want to tick. This will enable us to use OAuth authentication flows, which will then provide more required items.
The specifics of what we fill out really depends on how we are intending to interact with the APIs. It’s always very important to give an app only the bare minimum that is required for it to function, because while it may be tempting to give it full access and make it available everywhere, this would pose a massive security threat as it would be very easy for anyone who gets authenticated via this app to do pretty much what they want. Always design and build your integrations with security in mind, and that starts with the principle of least privilege.
You can read more about the different types of authentication flows and decide which one is best for you here, however if you’re looking to experiment in a Developer Org, it makes more sense to instead use one that’s already been made for you. Also, use a tool which can help you easily test and prod your Developer Org’s API without having to do a lot of the leg work yourself – in this instance Postman is highly recommended! There are even some Trailhead modules you can follow to get set up in a jiffy.
A Request’s Structure
The specifics of a request really depends upon what it is supposed to do, however all requests follow the same basic structure, with differences to indicate your intent. Since we’re using a REST API, this is also true of other REST APIs and not just Salesforce’s.
- URL: The URL of the service or resource we are requesting an action against. This follows the basic structure of “https://MyDomainName.my.salesforce.com/services/data/vXX.X/resource/”
- MyDomainName is the subdomain of the Salesforce instance you’re trying to interact with.
- vXX.X is the API version you wish to use, which unless you have a specific reason to not, should always be the latest version.
- Resource is the unique identifier for the resource you’re interacting with, and this could include parameters such as record Ids or SOQL queries depending on the resource in question.
- HTTP Method: REST uses standard HTTP methods, and for Salesforce’s API it will likely be one of the following depending on the resource in question:
- GET – Retrieving information about/from a resource, such as getting record details.
- POST – Submitting a request with contents to be added to Salesforcee, such as creating a record.
- PATCH – Updating a resource, such as updating a record.
- DELETE – Deleting a resource, such as deleting a record.
- HTTP Headers: These are used to pass additional information about a request, such as customising the request/return data structure (XML/JSON) and for including the authorisation token for OAuth 2.0.
- Request Body: The well formatted structure of a request, in either JSON or XML form, which gives details on the request, such as records and their fields to be updated/created. This will usually be used for all requests which are using a HTTP method that isn’t GET.
By building a request tailored to your specific use case, you can very easily get the required information you’re after, in a format that can be easily parsed and processed in whatever manner the calling system does.
Don’t forget: you’re not limited to doing a single request, so by using the composite API, we can perform multiple requests at once.
Example Use Cases
Now that we know what a request looks like and about the different resources available in the API, let’s take a look at some example use cases and how we can utilise Salesforce’s API to achieve our goals.
Exposing and Creating Records Externally
Your company runs events which people can register to attend, and these are managed and run through Salesforce. We wish to display these events on our website and allow attendees to easily register, and for that information to end up within Salesforce in real-time. To do this, we need to allow the website to be able to get the list of events which are available for registration, and then to create new attendance records when somebody registers. We can achieve both of these easily with two different parts of the REST API:
- Getting Events: We can use the Query resource to perform a SOQL query against the object which stores these events, and because we’re running a SOQL query, we can customize the fields returned to return the information we wish to display on the website (e.g. start time and remaining places). We can also further customize our query with a WHERE clause to limit our results to just those that should be visible.
- Register Attendance: We can use the sObject rows resource here to easily create an attendance record based on a JSON payload created from the register’s provided details.
Automating Org Setup
You’re a developer who utilizes scratch orgs for both development and QA of new and changed features before they go to QA. Part of this involves manually setting up certain aspects of an org, such as enabling geocoding of accounts which aren’t exposed or can’t be set via the metadata API. We also wish to insert some test data, however this has proved tricky to automated due to record types and relationships.
Your task is to reduce the manual overhead by automating as many of these tasks as possible during the currently automated setup process. We can achieve this by utilising the Tooling API to extend our capabilities.
- Geocoding Rule ID: We can perform a query utilizing the Query resource against a Tooling API object – in this case the CleanRule object.
- Activate the CleanRule: Perform an PATCH request against the CleanRule we queried previously, setting its status to Active.
- Execute Anonymous Apex: We can provide some anonymous Apex which will be run which can create the test records in the correct sequence and also get the correct record type IDs for that org.
READ MORE: Salesforce Apex Glossary
Mobile App Record Layouts
You have a custom mobile app that your end users can use to quickly update details about opportunities. Any changes to the fields which need to be captured have to go through a long and lengthy process of getting the app developers to update the layouts. We can use the User Interface API to streamline this process, by allowing the app to request page layouts directly from Salesforce.
- Getting Page Layout: We can call the Layout resource of the UI API, providing it the object we wish to get the layout for, the mode (e.g. view/edit) and the record type Id. This will then return us with the layout that should be used, all while respecting the end user’s permissions.
- Retrieve Picklist Options: Some fields will be picklist options, and we also wish to sync these with Salesforce. To do this we can use the Picklist Values resource, providing it the record type and field. This will return the valid options for this scenario, including any controlling field values.
- Updating the Record: Still using the UI API, we perform a PATCH request against the edited record. This request will respect permissions and perform validations as expected.
The above is just a drop in the ocean as to what the Salesforce REST API can achieve; if you have an external system or app that you wish to be able to access Salesforce data, or to be dynamically driven from Salesforce’s metadata, the REST API is there to help you out. With its consistent formatting and plethora of documentation, you can really extend the benefits of your Salesforce org far outside of it.
Additionally, it has a great ability to scale and handle bulk requests, so the only real limitation is your imagination and willingness to experiment. Just don’t forget the most important thing of all: ensuring your apps are fully secured.