Published on

Setting environment variables

image
Authors
  • avatar
    Name
    David Jimenez
    Twitter

Let's imagine that we have imported a collection into Postman. One of its requests creates a customer account. A simplified version of that request may look like this:

Create API

This call, of course, needs to be authenticated. In this case, the API uses a bearer token. We can specify this in the collection so that all requests can use the same authentication method.

Collection Authentication

Note that in the Token text field we have the value {{access_token}}. This is an environment variable. These variables typically appear in orange between two curly brackets. We'll delve deeper into environment variables later on.

To authenticate the call we need to use a bearer token. The collection has a request to generate such tokens:

Token Api

A response from this request has this shape:

Token Shape

We would like to run the collection so that the token generated in the first request gets passed to the call for creating an account.

We accomplish this by first creating an environment in our workspace:

Create Environment

Then we populate it with four variables:

Environment

  • mock_url is the URL of the API we are testing.
  • client_id and client_secret store our credentials to generate bearer tokens. Because client_secret should not be shared we set its type to secret making its value appear masked.
  • access_token will be used to store the token generated for authentication.

To store the token generated in the request, we need to go to the Tests tab, and enter a couple of lines of JavaScript.

Set Environment Variable

In the first line, we parse the response returned from the server. In the next line, we update the environment variable with the value returned by the request.

Now when we generate a token, we ensure that it is stored in the environment, and can be used in other requests.