Salesforce api example

Salesforce api example DEFAULT

Step Two: Walk Through the Sample Code

Make a series of REST requests to try accessing different types of resources in Salesforce. Before you try these examples for yourself, make sure that you’ve completed the prerequisites and have obtained an access token in Step 1 of this quick start.

You can copy and paste these examples to send them with cURL. However, you must replace in the base URI with the domain for your Salesforce org. If you’re unfamiliar with the anatomy of a REST request, see REST Resources and Requests.

In this example, a series of REST requests is used in this scenario:

  1. Get the Salesforce version.
  2. Use the Salesforce version to get a list of the resources available.
  3. Use one of the resources to get a list of the available objects.
  4. Select one of the objects and get a description of its metadata.
  5. Get a list of fields on that same object.
  6. Execute a SOQL query to retrieve values from all fields on Account records.
  7. Update the Billing City for one of the Account objects.

Get the Salesforce Version

Begin by retrieving information about each available Salesforce version. Submit a Versions request. In this case, the request doesn’t require authentication.

Here’s the output from this request, including the response header. The output specifies all valid versions (your result can include more than one value).

Next, use one of these versions to discover the resources it contains.

Get a List of Resources

Retrieve a list of the resources available for Salesforce, in this example, for version 53.0. Submit a Resources by Version request.

Here’s the output from this request. You can see that is one of the available resources in Salesforce version 53.0.

Use this resource in the next request to retrieve the available objects.

Get a List of Available Objects

Now that you have the list of available resources, you can request a list of the available objects. Submit a Describe Global request.

Here’s the output from this request. You can see that the Account object is available.

You can get more information about the Account object in the next steps.

Get Basic Object Information

Now that you’ve identified the Account object as an available resource, you can retrieve some basic information about its metadata. Submit a sObject Basic Information request.

Here’s the output from this request. You can see some basic attributes of the Account object, such as its name and label, and a list of the most recently used accounts.

The next step retrieves more detailed information about the fields in the Account object, such as field lengths and default values.

Get a List of Fields

Retrieve more detailed information by submitting a sObject Describe request.

Here’s the output from this request. You can see much more detailed information about the Account object, such as its field attributes and child relationships.

Now you have enough information to construct useful queries and updates for the Account objects in your org, which you do in the next steps.

Execute a SOQL Query

Now that you know the field names on the Account object, you can execute a SOQL query, for example, to retrieve a list of all the Account name values. Submit a Query request.

The output lists the available Account names, and each name’s preceding attributes include the Account IDs.

In the next step, you use this information to update one of the accounts.

Update a Field on a Record

Retrieve one of the accounts and update its billing city by submitting an sObject Rows request. To update the object, create a text file called patchaccount.json containing the new billing city information.

Specify this JSON file in the REST request. The cURL notation requires the option when specifying data. For more information, see

Also, specify the method, which is used for updating a REST resource. The following cURL command retrieves the specified Account object using its ID field and updates its billing city.

No response body is returned, just the headers.

Refresh the page on the account to see that the billing address has changed to Fremont.



It’s time to get our feet wet. We’re going to use Workbench to make some API calls. Workbench is a suite of tools for interacting with your Salesforce org through the API. Because you can make REST requests from any HTTP sender, there are plenty of other tools available for you to use (for example, check out cURL or Postman). But because Workbench provides a friendly framework specifically for Salesforce APIs, it’s the perfect way to dig in before you’re ready to write a full-on integration.
The first step is to log in to Workbench.
  1. Log in to your Trailhead Playground and navigate to Workbench.
  2. For Environment, select Production.
  3. For API Version, select the highest available number.
  4. Make sure that you select I agree to the terms of service.
  5. Click Login with Salesforce.

You’ve arrived at the Workbench home page. For this module, we use only one of Workbench’s many tools, the REST Explorer.

In the top menu, select utilities | REST Explorer .

Workbench's REST Explorer

You can make REST API calls from the REST explorer just like you would from any other HTTP interface. The text in the text box represents a resource URI. For convenience, the top-level domain is omitted from the displayed URI. For example, the full URI of the resource that’s prepopulated in the URI text box is .

The radio buttons above the URI represent the standard HTTP methods. To make an API call, enter the resource URI, select the appropriate method, add headers as needed, and click Execute.

Let’s try out the SObject Describe resource. This resource, when combined with the GET method, returns metadata about an object and its fields.

We’ll try describing the Account object. Replace the existing text in the URI text box with /services/data/vXX.0/sobjects/account/describe, where XX maps to the API version you’re using.

URI for describing an account
Let’s take a minute to break down this resource’s URI.
  • /services/data—Specifies that we’re making a REST API request
  • /v36.0—API version number
  • /sobjects—Specifies that we’re accessing a resource under the sObject grouping
  • /account—sObject being actioned; in this case, account
  • /describe—Action; in this case, a describe request

Now make sure that the GET method is selected, and click Execute.

Response after we describe the account object

Good work, captain. The Account metadata appears on the screen. And Workbench has nicely formatted the response. To see the raw JSON response, click Show Raw Response.

JSON response after we describe the account object

The Account metadata is displayed in JSON below some HTTP response headers. Because REST API supports both JSON and XML, let’s change the request header to specify an XML response. Next to the HTTP methods, click Headers. For the Accept header value, replace application/json with application/xml. Your request headers look like this.

Request header specifying XML

Click Execute. The raw XML response is returned. Hurrah!

  1. Foldable utility table
  2. Florists in vernon bc
  3. Rescue heroes 1999
  4. Weaving loom needles

Get to Know the Salesforce Lightning Platform APIs

Choosing the right API for your integration needs is an important decision. Here’s some information on our most commonly used APIs, including supported protocols, data formats, communication paradigms, and use cases. Treat this section as a reference you can return to when you’re considering which API to use.

Note the four data APIs that we talked about already. We’ll be diving into each of them next.

API NameProtocolData FormatCommunication
Chatter REST APIRESTJSON, XMLSynchronous (photos are processed asynchronously)
User Interface APIRESTJSONSynchronous
Analytics REST APIRESTJSON, XMLSynchronous
Bulk APIRESTCSV, JSON, XMLAsynchronous
Metadata APISOAP (WSDL)XMLAsynchronous
Streaming APIBayeuxJSONAsynchronous (stream of data)
Apex REST APIRESTJSON, XML, CustomSynchronous
Tooling APIREST or SOAP (WSDL)JSON, XML, CustomSynchronous

When to Use REST API

REST API provides a powerful, convenient, and simple REST-based web services interface for interacting with Salesforce. Its advantages include ease of integration and development, and it’s an excellent choice of technology for use with mobile applications and web projects. For certain projects, you may want to use REST API with other Salesforce REST APIs. To build UI for creating, reading, updating, and deleting records, including building UI for list views, actions, and dependent picklists, use User Interface API. To build UI for Chatter, communities, or recommendations, use Chatter REST API. If you have many records to process, consider using Bulk API, which is based on REST principles and optimized for large sets of data.

When to Use SOAP API

SOAP API provides a powerful, convenient, and simple SOAP-based web services interface for interacting with Salesforce. You can use SOAP API to create, retrieve, update, or delete records. You can also use SOAP API to perform searches and much more. Use SOAP API in any language that supports web services.

For example, you can use SOAP API to integrate Salesforce with your org’s ERP and finance systems. You can also deliver real-time sales and support information to company portals and populate critical business systems with customer information.

When to Use Chatter REST API

Use Chatter REST API to display Chatter feeds, users, groups, and followers, especially in mobile applications. Chatter REST API also provides programmatic access to files, recommendations, topics, notifications, purchasing, and more. Chatter REST API is similar to APIs offered by other companies with feeds, such as Facebook and Twitter, but it also exposes Salesforce features beyond Chatter.

When to Use User Interface API

Build Salesforce UI for native mobile apps and custom web apps using the same API that Salesforce uses to build Lightning Experience and Salesforce for Android, iOS, and mobile web. Build user interfaces that let users work with records, list views, actions, favorites, and more. Not only do you get data and metadata in a single response, but the response matches metadata changes made to the org by Salesforce admins. You don’t have to worry about layouts, picklists, field-level security, or sharing—all you have to do is build an app that users love.

When to Use the Analytics REST API

You can access Analytics assets—such as datasets, lenses, and dashboards—programmatically using the Analytics REST API. Send queries directly to the Analytics Platform. Access datasets that have been imported into the Analytics Platform. Create and retrieve lenses. Access XMD information. Retrieve a list of dataset versions. Create and retrieve Analytics applications. Create, update, and retrieve Analytics dashboards. Retrieve a list of dependencies for an application. Determine what features are available to the user. Work with snapshots. Manipulate replicated datasets.

When to Use Bulk API

Bulk API is based on REST principles and is optimized for loading or deleting large sets of data. You can use it to query, queryAll, insert, update, upsert, or delete many records asynchronously by submitting batches. Salesforce processes batches in the background.

SOAP API, in contrast, is optimized for real-time client applications that update a few records at a time. You can use SOAP API for processing many records, but when the data sets contain hundreds of thousands of records, SOAP API is less practical.Bulk API is designed to make it simple to process data from a few thousand to millions of records.

The easiest way to use Bulk API is to enable it for processing records in Data Loader using CSV files. Using Data Loader avoids the need to write your own client application.

When to Use Metadata API

Use Metadata API to retrieve, deploy, create, update, or delete customizations for your org. The most common use is to migrate changes from a sandbox or testing org to your production environment. Metadata API is intended for managing customizations and for building tools that can manage the metadata model, not the data itself.

The easiest way to access the functionality in Metadata API is to use the Salesforce Extensions for Visual Studio Code or the Ant Migration Tool. Both tools are built on top of Metadata API and use the standard tools to simplify working with Metadata API. 
  • The Salesforce Extensions for Visual Studio Code includes tools for developing on the Salesforce platform in the lightweight, extensible VS Code editor. These tools provide features for working with development orgs (scratch orgs, sandboxes, and DE orgs), Apex, Aura components, and Visualforce.
  • The Ant Migration Tool is ideal if you use a script or the command line for moving metadata between a local directory and a Salesforce org.

When to Use Streaming API

Use Streaming API to receive real-time streams of data that are based on changes in Salesforce records or custom payloads. For Salesforce record changes, Salesforce publishes notifications when the changes occur. For custom notifications, you can publish event messages. Subscribers can receive notifications using CometD—an implementation of the Bayeux protocol that simulates push technology. Clients can also subscribe to some types of events with Apex triggers or declaratively with Process Builder and Flow Builder.

When to Use Apex REST API

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.

When to Use Apex SOAP API

Use Apex SOAP API when you want to expose Apex methods as SOAP web service APIs so that external applications can access your code through SOAP.

Apex SOAP API supports both OAuth 2.0 and Session ID for authorization.

When to Use Tooling API

Use Tooling API to build custom development tools or apps for Lightning Platform applications. For example, you can use Tooling API to add features and functionality to your existing Lightning Platform tools and build dynamic modules into your enterprise integration tools. You can also use Tooling API to build specialized development tools for a specific application or service.

Tooling API’s SOQL capabilities for many metadata types allow you to retrieve smaller pieces of metadata. Smaller retrieves improve performance, making Tooling API a good fit for developing interactive applications. Tooling API provides SOAP and REST interfaces.

Understanding REST APIs and Integrations Basics in Salesforce Development

A 60 Minutes Step-By-Step DIY Guide to Salesforce REST API for Non-Developers

Salesforce REST APINo kidding. Even if you are not a developer, you can still learn the basics of Salesforce REST API in just under 60 minutes. Here is a step-by-step do-it-yourself guide on how to make REST API calls and interact with Salesforce.

But first of all, what is Salesforce REST API? Here is a very simple explanation – Salesforce REST API allows you to interact with Salesforce from outside the Salesforce. That means that you can create/update/delete records in Salesforce from an external program. That means that you can issue a query to Salesforce and get the response.

Where are APIs used? APIs are used when you want to integrate Salesforce with other applications. Your other application can be in any language (Java, PHP, .Net, Ruby, Oracle, etc. etc.) and on any platform.

Here is an example. Say, you are using an ERP and whenever you create/update a customer in your ERP system, you want to create/update that record as an ‘Account’ in Salesforce. So what you need to do to accomplish this is to write an ‘AFTER INSERT’ trigger in your ERP database. The trigger will make a REST API call to Salesforce and will insert/update the record in the ‘Account’ object in Salesforce.

If you want to do something in Salesforce from outside Salesforce, you need to use an API. You need to make an API call. And here is a nice video explaining the concept of an API

So how do you get started with APIs in Salesforce? I created two blog posts earlier that contained step-by-step instructions on how to connect to Salesforce from Java using REST API and SOAP API. So if you are a programmer/developer it should be quite easy to follow these instructions and have a taste of how to work with Salesforce using APIs.

But what if you are from a non-programming background? Say you are an admin, functional consultant, solution architect, tester etc. If the term API sounds greek to you, stay with me for next 60 minutes or so and I assure you that by the end of it not only will you make your first API call, but also insert / update & delete records in Salesforce using APIs.

So how are we going to do this? Rather than writing a program using Java or PHP or .Net we will use one of the most popular tool to design, build and test APIs called “Postman“. So while in a real world you will make REST API calls using Java or PHP or .Net etc. in this case we will use the Postman app to make API calls to Salesforce and watch the response.

Here is your Step-By-Step DIY Guide on using Salesforce REST API. Enjoy it chilled with Vodka, lemon and a pinch of salt

Where can you use this guide?
    1. You can use it when you need to create a login in Salesforce for the middleware / 3rd party system to make REST calls. You will create a user, setup the profile and use Postman app to test and ensure that the user is able to connect to Salesforce using API
    2. You can will use it when you need to test API calls. For example, you can use it to create / update / delete records in Salesforce and make sure that there are no profile/permission issues
    3. You can use it to see the response structure. When you make a REST API call to Salesforce, Salesforce will return a response.
References & Useful URLs

Change Log

  • Feb 2016 – First Published
  • Jun 2019 – Replaced ARC (Advanced Rest Client) Chrome Extension with ARC Desktop Client
  • Nov 2020 – Replaced ARC with Postman

Api example salesforce

Building a Salesforce REST API integration

Being in the Software as a Service space, you have to admire what Salesforce has managed to accomplish. It would be hard to argue their success, particularly at the enterprise customer level.

While they have one of the most tuned and well-known sales approaches in software, there is almost a feeling that when a company gets to a certain size, they just decide it’s time to use Salesforce. It’s due to this that if you have a product that operates in the Sales and Marketing space, there is huge opportunity in tapping into the Salesforce community and ecosystem.

For example, we’ve built the GoSquared Salesforce integration to capture the on-site behaviour of leads when they’re browsing your website (E.g. when a lead views your pricing page or watches a webinar), and send this directly into Salesforce ready for your sales team to act on within their existing workflow.

Digging into the Salesforce developer ecosystem

With a company that has the breadth and depth of product that Salesforce offers, there will always be pros and cons to getting your head around their documentation and terminology.

They have an incredible developer community, including their own Stackoverflow-esque forums. If you hit a road block, it’s likely someone’s hit it before you and you can find a documented solution.

Similarly they have an extremely robust e-learning platform with tracks that you can complete across a plethora of different subjects to get up to speed on a lot of their terminology and principals.

There can, however, be an abundance of content to sift through and it can be an incredibly time consuming process – particularly if building and developing on the Salesforce Platform is not going to be the core responsibility of your job!

This blog post is really focused around communicating, at a very basic level, the key concepts needed to build a basic Salesforce REST API integration.

Salesforce API Integration vs Salesforce App

It’s important to highlight the difference between a Salesforce API Integration and a Salesforce App that you’d find on their AppExchange (essentially the Salesforce App Store.)

Listing an app within the Salesforce AppExchange will give you the ability to build your product directly into the Salesforce platform. For example, visualising your product’s data directly within a component in Salesforce. While there are clear benefits in having a presence within this ecosystem it’s important to note that there are some costs associated with doing so.

A Rest API integration is a lot simpler and is primarily focused around sending data from your application and fetching data from Salesforce. Currently there is no cost associated with this type of integration however it’s worth noting that REST integrations are only accessible to Salesforce users on their enterprise plans (there is scope to get REST API access on Professional and Group editions but involves getting your app whitelisted.)

For the purposes of this post, our example REST API integration is going to be super basic. Our app is going to have customer data that we want to send to Salesforce and there will be customer data in Salesforce that we want to retrieve.

Essentially then, our REST API integration is going to need to do 3 critical things:

  1. Allow a user of our application to authorise us to access and transfer their Salesforce data on their behalf.
  2. Allow a user to push data from our application to Salesforce.
  3. Allow a user to retrieve Salesforce data to be used within our app.

Getting set up with Salesforce

Create a free developer account

Start by getting yourself a free Salesforce Developer account.

The Salesforce developer accounts are awesome and pretty much give you a working Salesforce organisation (an organisation is Salesforce’s terminology for an account) so you can get a feel for the interface and even add and manage users.

Set up a Connected App

Once you have your developer account set up you’ll want to set up a Connected App. Connected Apps have the ability to offer a lot of functionality and sometimes that can make it a bit difficult to get your head around them.

For the purposes of this and how we’re going to use it, it’s easiest to think of a connected app as a small app that sits on Salesforce’s infrastructure that you point your integration to. It is responsible for managing the authentication and also the routing of requests to the relevant client instances.

Once you’ve set up your Salesforce developer account, you can set up a connected app by clicking the Setup icon in the top-right navigation menu and select Setup.

Enter App Manager in the Quick Find box and then select App Manager.

Screenshot of the Salesforce App Manager

1. Click New Connected App.

2. In the New Connected App form, fill in:

In the Basic Information section:

  1. Connect App Name: YourAppName.
  2. API Name: this will automatically become ‘YourAppName’.
  3. Contact Email: enter your email address.

In the API (Enable OAuth Settings) section:

  1. Check Enable OAuth Settings.
  2. Callback URL: enter your callback url, example:

This will be the URL which Salesforce POSTs to when the user has authorised your app to access their data. This will include the access and request token (we’ll explain a bit more on this below but they are essential to be able to send and receive data.) So if you don’t have one already, you’ll need to set up an endpoint who’s role it is to receive and handle this request.

Under Selected OAuth Scopes:

  1. Select Access and manage your data (API).
  2. Click Add.

Once you’ve set up your app, you’ll be given a Consumer Key and a Consumer Secret for you app.

The basic Salesforce Oauth data flow

Salesforce Oauth data flow diagram. by GoSquared

With the connected app set up, its handy to get an idea of how the data flow works.

To start, your user is directed to a authorisation endpoint, there they log in and approve access for your app to access their data.

After a successful authorisation Salesforce sends a response with an Access token and Refresh token.

The Access token is to be passed in the header of all API requests for data. This token has an expiry date and will always expire. By default the Connected Apps have an access token with an expiry of 15 minutes (inline with the sessions settings within your Salesforce settings).

The Refresh token is to be used to retrieve a valid access token (e.g. when the current access token expires). You can change the expiry settings on this but you can also set this never to expire, only when it revoked.

Example API calls:

To make the initial authorisation request for a user to grant your app access to their data (this is where your user is initially directed to a authorisation endpoint and logs in) you’d make the following request. The client_id in the below call will be your consumer ID from the connected app. The redirect_uri will be the Callback URL.

A successful response from this will redirect the page to a Salesforce login page where the user is able to login and authenticate. After Salesforce confirms that the client has authorised your app to access their data, the end-user’s browser is redirected to the callback URL you’ve specified by the redirect_uri parameter. Salesforce then appends an authorisation code to the redirect URL, their request will look similar to the below.

You’ll use this as the value for your code parameter when you make a request to Salesforce’s token endpoint to receive your Access and Refresh Token.

Example request:

Example Response:

Outside of the access and response token, the instance_url is import also. It’s what you’ll need to build the base of your future API calls.

Now we have the access token, we’re able to start making requests to send and receive data on our users behalf. Something to keep in mind though, as mentioned earlier, is that these access tokens will always expire at some point.

Due to that, you’ll want to keep your access token up to date by making a call to the token endpoint and changing the grant_type to ‘refresh_token’ along with including the refresh token you had received in the previous call.

Example call:

Example response:

Now we have a way to keep our access tokens valid and up to date, we’re set up and ready to start working with Salesforce objects.

Understanding Salesforce objects

Salesforce objects (sobjects) are effectively database tables that contain an organisation’s data. Examples of standard Salesforce objects will be “Accounts”, “Contacts”, “Leads”, and “Tasks.” You also have scope to create your own custom objects.

A Salesforce record describes a specific occurrence of an object (such as a specific contact like “Jonny Appleseed” that is represented by a Contact object). A basic comparison would be like a row in a database table.

For the following examples, we’re just going to focus on Contacts.

Send data from your app to Salesforce

Creating a contact in salesforce is really straightforward. You just need to build the API url using the instance from your access token response and use the access token value as your bearer token in the header.

One thing to keep an eye out for through is for characters that need to be escaped in your access token.

For example this access token should have the exclamation mark escaped

So this:

Becomes this:

you can then make the below call to create a contact.

Example request

(Your contact will need a last name as the minimum for an entry to be created.)

The response you get back will be the id of your contact

Which will also let you build a link directly to the contact.

Retrieving data from Salesforce to your app

If you want to retrieve a list of contacts there are a few ways you can do it. You can make a request to the contact endpoint and it will return a bunch of information about your contacts that I found a bit cumbersome to navigate.

I actually prefer to use a combination a contacts ‘describe’ endpoint, which will return all of the fields we can populate about our user.

Example request:

That will give a detailed response of all of the fields available. (I’ve just given an example of the ‘first name’ element for brevity)

Once you’ve got the fields you can then use them (or a selection) to build a custom query:

That will return all contacts with their associated properties.

That should now give you a way to retrieve contact data from Salesforce to use within your app.

Further resources

Hopefully that gives a good enough foundation to start exploring more of the Salesforce objects you can interact with through a REST API integration. Here are some additional resources to more in-depth information about the Salesforce REST endpoints.

Questions or Comments?

Feel free to reach out to the author Russell Vaughan on Twitter with any questions or feedback you have about this post!

Salesforce API Fundamentals


You will also like:


672 673 674 675 676