paint-brush
Build a Lightweight REST API with Salesforce and Postmanby@MichaelB
1,378 reads
1,378 reads

Build a Lightweight REST API with Salesforce and Postman

by MichaelNovember 19th, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Salesforce can expose custom-coded services to third-party applications, either as SOAP web services or REST APIs.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Build a Lightweight REST API with Salesforce and Postman
Michael HackerNoon profile picture

Introduction

Whether you’re a longtime Salesforce developer, new to the platform, or just need to integrate your system of choice to Salesforce, Postman brings you all the tools you need to make the process easier, faster, and more streamlined.


In this article, we’ll show how Postman can help you start building the core of your API-driven integration on both sides of the API—either as the provider or the consumer.

Developing Salesforce APIs

While Salesforce has several pre-built applications for key business tasks such as Sales, Service, and Marketing, in this post we’ll focus on the capability of Salesforce as a development platform, with its own programming language: Apex.


Salesforce can expose custom-coded services to third-party applications, either as SOAP web services or REST APIs. In our demo, we will develop a very lightweight REST API and demonstrate how Postman can speed up that process.

How Postman accelerates development

One of the most popular use cases for Postman is to explore the API of third-party apps, to better understand how to submit requests, and what to expect for responses. By seeing the requests and responses, developing your own code for handling these APIs becomes much easier. We can also develop a mock server implementation of our own API, one that generates expected responses. In this way, we don’t need to wait for a “real” implementation of the API before we can start developing for it. By using Postman’s tools for API development, we can rapidly prototype a Salesforce REST API before the API—and the code that uses it—has completed development.

Bringing it Together

As our first step, we'll use one of Postman’s most powerful features: mock servers.

Mock Servers

A mock server is a lightweight server interface that responds to your API requests realistically, allowing you to quickly and easily get a valid response without worrying too much about the details. With Postman, you can start a mock server that responds to HTTP requests of your design in a very short time, with no coding required. By pointing your code at this mock server, you can write and test your API consumer code.


We’ll be using the Desktop client for our examples, but everything here should be equally applicable with Postman’s web client. Mock Servers can be found within your Workspace in Postman.

Creating and Configuring the Mock Server

Click on Create Mock Server to get started.


Next, we can start defining the HTTP requests we’d like to mock. By specifying the HTTP request method, URL, response code, and response body, we can tell Postman how to respond to requests.

In this example, we’re mocking a request for a Salesforce Account record. Rather than hardcoding a Salesforce account id, we’re using Postman’s ability to use variables. By matching the variable in both the request and the response, we can return whatever value was supplied in the request.

We’ll use this feature in more detail later.


For now, we will just mock that one request and click the Next button to finalize our Mock Server setup with a few more parameters.


Besides naming the mock server, we’ll just stick to the defaults and click the Create Mock Server button. This will create our mock server instance with a unique URL for receiving requests, as illustrated below.


We selected the option to save the mock server URL as an environment variable, however, there is an easier way to reference this. If we expand the environment dropdown in the top-right of Postman, we will see that an environment was automatically created for us.



If we select this environment, the mock server URL is automatically populated for us in a parameter called {{url}}. The process of creating a new mock server also created a new Postman collection for us. That collection has our request, and the request is ready for us to populate with parameters where applicable.



When we select this request, we see the user interface for building our request. By replacing the {{accountId}} variable in the request with an example id and sending the request, we should receive a response from our Mock Server that repeats that id back to us.


Extending the Mock Response

Now that we have our basic mock server working, we can extend the responses to be more meaningful and realistic. Expand the example request in our collection from the Workspace tree view, and click on the example (currently called “Default”).


We’re going to make some changes to how the mock server responds to this request. The attributes field is not essential. We’re just simulating how Salesforce would respond.

In the response body tab in the bottom section, replace the contents with the following JSON:


{
  "attributes" : 
    {
      "type" : "Account",
      "url" : "/services/data/v53.0/sobjects/Account/accountId"
    },
  "Id" : "{{accountId}}",
  "Name" : "{{$randomCompanyName}}"
}


Note how we made use of Postman’s convenient $randomCompanyName variable. Many useful variables can be used to generate example data, documented here.


In the response headers tab in the bottom section, add a Content-Type key with the value application/json.


Click Save to update the example response. The mock server will now respond with the updated response to the request we made earlier.


At this point, we can add additional requests and examples to our collection. Click the ellipsis (...) icon next to our collection name and select Add request to generate a new one. Then, click the ellipsis icon next to the new request and select Add example. This adds a new example response that the mock server will serve to your request. You can build a new mock server response in the same way as previously—by specifying new paths, HTTP verbs, and responses—until you’ve drafted your API. At this point, we can even test the API from outside of Postman - one of the quickest ways to do this is via Postman’s code snippet functionality. This allows for equally rapid development of code to consume the API.

Snippets

Postman provides example code for calling your APIs, mock or otherwise, in several languages and libraries. With a request selected in your workspace, click the </> icon on the right to expand the code snippet menu. From here, you can select a suitable language/library combination and see the example code to call your API.


CORS is enabled for Postman mock servers. As a result, you can stub your web apps with mocked data using the mock endpoints. Development or production web apps can then make requests to your Postman mock endpoint and receive example responses.


The code snippet will resolve variables where it can. In our example, where we use the {{url}} variable to reference our Mock Server, this is expanded for us. This is shown in the JavaScript Fetch code example below.


Important note: this code snippet, as generated from Postman, has a small error. HTTP GET requests sent via Fetch should not set a body in the request. For our testing, we will need to remove line 5 in the example above. Below is the updated code, wrapped in a lightweight HTML page.


<html>
    <head>
        <script>
            var raw = "";

            var requestOptions = {
            method: 'GET',
            redirect: 'follow'
            };

            fetch("https://768bb73c-2824-49fa-8787-3967ce6ea0c1.mock.pstmn.io//Account/001000000WCFB8", requestOptions)
            .then(response => response.text())
            .then(result => console.log(result))
            .catch(error => console.log('error', error));
        </script>
    </head>
    <body>
        <p>Check the browser console to see the output from our mock server.</p>
    </body>
</html>

Summary

In this article, we’ve looked at the basics of setting up a Mock Server in Postman—from creating the mock server and a sample response to extending it with more meaningful JSON data and adding additional responses. We’ve also seen how simple it is to generate code snippets that show how to consume the API in the language/platform of your choice. Code snippets greatly aid the development of your own tools that utilize your API.


With the tools that Postman provides, we can provide a technical requirement to both our Salesforce developers implementing the API and our developers on other platforms communicating with Salesforce as part of an integration.


There is a wealth of further resources available for working with both Postman and Salesforce. Some of the ones relevant to what we’ve covered here can be found below: