Postman Collection for Salesforce: Mock Servers and Code Snippets
Tags: webdev, architecture
Published: 2021-10-18 15:06:28

## Postman power tools for your Salesforce Integrations



### Introduction

Whether you’re a longtime Salesforce developer or you’re new to the platform, Postman brings you all the tools you need to streamline the Salesforce API integration process to be easier and faster.

In this article, we’ll show how mock servers and code snippets in Postman can help you build the core of your API-driven integration with Salesforce.


### About the Salesforce API

If you’re unfamiliar with Salesforce, think of it as a cloud-based development platform. It has several pre-built applications for key Salesforce-related business tasks. However, for this article, we’ll focus on its capabilities as a development platform.

There are several Salesforce APIs available, many of which are specialized for key use cases or Salesforce products. The [documentation](https://developer.salesforce.com/docs/apis) for all the APIs is extensive. Salesforce can also present your own developed code as a REST or SOAP APIs for use by other applications and services.

There is also a [Postman collection](https://github.com/forcedotcom/postman-salesforce-apis) for exploring the various APIs that Salesforce exposes.  We’ll look at this collection and build a mock server within Postman to simulate responses from Salesforce.


### About Postman

Postman is like a powerful Swiss army knife for all things API-related—developing your own APIs, developing code that uses other APIs, or a mixture of both.

One of the most practical use cases for Postman is to explore third-party APIs, to better understand how to submit requests and work with the subsequent responses. By seeing the requests and responses, it becomes much easier to develop your own code for handling these APIs.


### Bringing it together

By using Postman’s tools for API development, we can rapidly prototype the use of the Salesforce APIs ahead of the full development of the production code that will use them. To achieve this, we'll use one of Postman’s most powerful features—mock servers. For this article, we’ll use the Desktop client, but everything here is equally applicable within the Web client, with one additional step. In order to meet the requirements of Salesforce CORS (Cross-Origin Resource Sharing) security requirements when using the Web client, you must add Postman to the list of Allowed Origins in Salesforce. You can find details on how to do this step [here](https://github.com/forcedotcom/postman-salesforce-apis/blob/master/install-with-web.md#enable-cors-in-salesforce).


### Installing the Salesforce API Collection

The easiest way to install the collection is to click on the _Search Postman_ box at the top of the app and enter `Salesforce`. You’ll see many results, but the one we’re interested in is `Salesforce APIs` by `Salesforce Developers.` Click on its name on this list, as shown below:

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hcon8ioclgg5t3af4g8k.png)


On the next screen, we need to fork the collection to our own local workspace. Simply click the Fork button and, when prompted, give your copy a name to use locally.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ysznzbth236pfq6n2sr0.png)

Once installed, you should see the collection appear in your workspace, and you can expand it to see the various API requests contained in the collection.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fbionwj0o09vz8p76oaq.png)

## Configuring the collection

While it is perfectly possible to develop API code and mock servers against Salesforce without access to Salesforce, it is **much** easier if we have a real Salesforce org to work with.

In your browser, [sign up for a Developer Edition account and org](https://developer.salesforce.com/signup) of your own. We’ll be working within the Salesforce development environment. (In Salesforce terminology, this is called a “sandbox” or a “scratch org”.)

Once you have a Salesforce org to work with, switch back to Postman and select the Salesforce API Collection again. In the Variables tab, ensure the URL parameter has the `Current Value` set to **[https://login.salesforce.com](https://login.salesforce.com)**. In the Authorization tab, click on _Get New Access Token_. Log in to Salesforce with the username and password you created when setting up your account. When prompted, allow access for Postman.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s6izp4109ni81rmgbbmp.png)

Once you are redirected back to Postman, copy the `instance_url` parameter to your clipboard before clicking the _Use Token_ button.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d487y9cwvhvw2xkabx33.png)

Return to the Variables tab and populate the `_endpoint` variable’s `Current Value` with the instance URL from your clipboard. Click _Save_. Your collection is now configured!


### Mock servers

A mock server is a lightweight server interface that responds to your API requests realistically so that you can quickly and easily get a valid response without worrying about the details. With Postman, you can start a mock server that responds to HTTP requests of your design—quickly and without any coding required. By pointing your code to this mock server, you can write and test an API consumer even without having a full API implementation ready. Mock servers can be found within your Workspace view in Postman.


#### Creating and configuring the mock server

While Postman allows us to create a mock server from scratch—and there are many use cases when this makes sense—we will create a mock server from the Salesforce API collection for now. Click the ellipsis icon (`...`) next to your newly-forked collection and select `Mock collection`.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/av0r15swfsygzarrr5y6.png)

Give the mock server a name, and stick with the defaults for all other options. Click the _Create Mock Server_ button. This creates our mock server instance with a unique URL for our requests’ destination:

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nsebe52nz1ao0zkkubxw.png)

Since we selected the option to save the mock server URL as an environment variable, however, there is a convenient way to reference this URL. When we expand the environment dropdown in the top-right of Postman, we see that Postman automatically created an environment for us.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i7ea70oam0z2g96h1ty5.png)

If we select this environment, the mock server URL is automatically populated for us in a parameter called `{{url}}`. Next, we need to handle some other config variables we’ll soon need.

As we’ve created a mock server from the existing Salesforce collection, there are several mock responses already in place. Postman calls these “examples” because they serve as an example of how to call a particular API method, along with the response it returns.  Our mock server uses these to provide responses that match the requests. For example, if we expand the **OAuth Username Password** request under the **Auth** section, we see an example that has been pre-created for a successful login.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/btgejl2kyq91amm5d3vi.png)


![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t9k6ku4z8wguwgi8redm.png)

### Variables and Parameters in Postman

When constructing requests in Postman, it’s useful to substitute various settings and parameters with variables. We already saw this in action when Postman created the `{{url}}` parameter automatically for us. There are several key types of variables that can be used in Postman to simplify our requests, and these can be categorized by **scope**.

Scope defines where a variable is available, much like the concept of scope in programming languages. Variable scope can be (in order of narrowing breadth):

* Global: visible across an entire workspace, and so visible across all collections in your workspace
* Collection: visible to all requests in a collection, regardless of the environment
* Environment: visible only to a particular environment. For our purposes, this will be particularly useful for differentiating between our Mock Server endpoint versus a real Salesforce Org (whether that is a Sandbox or a Production instance).
* Data: variables sourced from external CSV or JSON files
* Local: visible only to a specific request and only at runtime. The variable is no longer available when the request is complete.

It’s important to note that these are prioritized by **narrowest scope first**: For example, if you had a collection-level variable `{{url}}` and an environment-level variable `{{url}}`, then the environment variable would be used.

In addition to the variables, there are different ways to specify parameters for our requests:

* Query parameters: these are appended to the end of the URL (for example, `?id=1&type=new`).
* Path parameters: these form part of the URL itself and are referenced by putting a colon in front of them (for example, `/contact/:id`).

The Salesforce API collection, by default, uses the collection-level variable `{{_endpoint}}` to specify where the API requests should be sent to. It also uses the `{{url}}` collection-level variable to handle authentication, as it allows us to differentiate between a production or sandbox instance. However, our mock server auto-created an environment-level variable also called `{{url}}` for the address of our mock server.

You’ll recall that the narrowest scope “wins”. Therefore, in these scenarios, if we’re running in the environment that the mock server created for us, `{{url}}` would represent that mock server address. If we were running requests from the Salesforce API collection in any other environment, then the collection-level variable would be used.

With this information, we can easily update the requests in the Salesforce API collection to use `{{url}}` instead of `{{_endpoint}}` when we want to work in our Mock Server environment.

### Adding mock responses

Now that we have our basic mock server working, we can extend the responses to cover more of the Salesforce API calls. Let’s look at the REST Sobject Rows call and create a valid response mock for the call. In the Salesforce API collection, we see an **Sobject Rows** request under **REST -> SObject**. This call is documented [here](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_get_field_values.htm).

When we click on the ellipsis icon alongside the request in the list, there’s an option to _Add example_. Click on this, and we can build up our mock request/response.

We’ll replicate the example from the documentation. In the request section, we need to add some parameter values to match that example, as shown below:

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vyg8ih47kqd8c1f818i5.png)

This demonstrates the difference between query parameters and path variables, which we covered earlier. Next, we need to define how the mock server should respond when given a request that matches those parameters. In the Response Body section in the lower half of the screen, we can use the example response given in the documentation, as follows:

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h39jsnn1kn3utdiqqwe2.png)

Notice that we’ve also specified the HTTP status code to be returned—in this case, a `200`.  Finally, to make this a more accurate response, we click on the Headers tab of the response section and set a `Content-Type` header to `application/json.` This ensures that the response is interpreted correctly as JSON and not just plain text. We save our example response.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/54db5u36z6ybl10m9cqt.png)

Our example server response is nearly ready to test; there’s just one more important change to make. To ensure our response comes from our mock server instead of our Salesforce org, we need to replace the `{{_endpoint}}` in the URL to `{{url}}`. With this change, Postman will use the address of our mock server. Note that we need to do this in both the example and the request above it, so be sure to check that they match, and then save the changes.

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ifq2tj7rzve0k1r1d1h.png)

Now, we’re ready to test our request. Click Send, and you'll get a response from your mock server!

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/taqlxk7nnugi5b59u8ea.png)

## Code snippets

Postman also provides example code for calling your APIs—mock or otherwise—with support for 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 use for calling your API.

Postman’s code snippets will resolve variables where they can. In our example, when we use the `{{url}}` variable to reference our mock server, this is expanded for us. The following example shows this with a C# code snippet:

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ajq2q8fxflpwlhbkh7b.png)

In some cases, you can even copy the URL from that code request and paste it into your browser to see the mock response.  Since this particular request is a GET request and we’re not checking the auth headers in our Mock Server implementation, the response is returned as shown below:

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/76bns2zd2poyqrs24va2.png)

## Summary

In this article, we 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 of your choice, aiding the development of your own tools that use 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 additional resources for working with both Postman and Salesforce. Some of the resources relevant to what we’ve covered here include:



* Building a mock API - [https://youtu.be/kZOwHyCl9sY](https://youtu.be/kZOwHyCl9sY)
* Mock Servers: The Exploratory - [https://youtu.be/n_7UUghLpco](https://youtu.be/n_7UUghLpco)
* Integrating With a Custom Salesforce App in Postman - [https://youtu.be/7NA-7TGqsNc](https://youtu.be/7NA-7TGqsNc)
* Exposing Apex Classes as REST WebServices - [https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_rest.htm](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_rest.htm)
* Salesforce Trailhead: Postman API Client - [https://trailhead.salesforce.com/en/content/learn/modules/postman-api-client](https://trailhead.salesforce.com/en/content/learn/modules/postman-api-client)