Testing the REST API Using Postman

This section provides some tips and guidelines you can use to get started with testing the REST API using the GUI REST client Postman.

You can download Postman from https://www.getpostman.com/ and install it on your computer. After you have installed Postman, you will be able to:

Note:

These guidelines are given for illustration purposes only. You can use any GUI REST client of your choosing. You can also use the curl command-line utility to execute HTTP requests. Refer to the relevant product documentation for detailed information about its setup and usage.

Defining and Saving Environment Variables in Postman

A Postman environment is a set of key-value pairs. The key represents the name of the variable, which you can then use in place of the value in your requests. You can set up multiple environments and switch between them. For example, you can have, the same set of environment variables with different values to use the same requests with your sandbox or production OpenAir accounts, or with different access tokens obtained for different users with different permissions and access rights. You can create copies of your environments, export them as JSON, or share them with other Postman users.

To define and save environment variables in Postman:

  1. Click the Manage Environments button in the top right corner of the main Postman window.

    Manage Environments buttons in Postman.

    The Manage Environments window appears.

  2. Click Add. The Add Environment window appears.

  3. Type a name for your environment.

  4. Type a variable name and initial value for each environment variables you want to add. You can use the following example as a model. replace the companyID value with your unique account domain identifier, and the clientID, clientSecret, and the callbackUrl values with the client ID, client secret and redirect URI for the application you registered with OpenAir.

    Manage Environments window in Postman.
  5. Click Add and close the Manage Environments window. The new environment is now available in the environment selection dropdown in the top right corner of the main Postman window.

Creating a Request Collection in Postman

A Postman collection is a set of HTTP requests. You can use collections to save your requests for later use, copy an entire set of requests, export them as JSON, or share them with other users.

To create a collection in Postman:

  1. In the left pane of the main Postman window, click the Collections tab and click New collection.

    The Create a new collection window appears.

  2. Type a name for your collection.

  3. (Optional) Add a description. You can also define a default authorization method for your requests and define collection variables, if required. These settings are not set at the collection level for the purpose of this document.

  4. Click Create. The new collection is listed in the left pane. You can save the requests you create to this collection.

    Collections management tab in Postman.

Creating and Sending API Requests Using Postman

Postman makes it simpler to create and send request and read responses. It spares you the need to get your curl syntax right and analyze requests and responses from the command line.

To create and send an API request using Postman:

  1. In the right pane of the main Postman window, click the + tab.

    A new untitled request tab appears. New requests use the GET method by default. You can select any other supported method from the dropdown on the left.

  2. Enter the request URL. You can use the environment variable for the base URL and add the relevant resource endpoint path. For example, enter {{baseUrl}}/expense-reports/

    Request method and URL fields in Postman.
  3. Click the Params tab and enter any query parameters as key-value pairs. Notice the query parameters are added to the request URL as you type.

    Query Pameters in Postman.
    Note:

    Postman URL-encodes query parameter values. The example above shows a URL-encoded value for the q parameter but it is not necessary to URL-encode the value in the Params tab.

  4. Click the Authorization tab. Click the Type dropdown and select OAuth 2.0. Enter the Access Token. You can use the relevant environment variable for the access token — {{accessToken}}. Enter the Header Prefix Bearer and ensure Add authorization data to is set to Request Headers.

    Request Authorization tab in Postman.
    Note:

    The first time you send a request or if the refresh token saved in your environment variables is no longer valid, you may need to get a new access token. See Getting Authorization and Obtaining a New Access Token Using Postman.

  5. If you are creating a POST or PUT request, click the Body tab. Select the raw option and select JSON from the type dropdown on the right of the radio buttons. Enter the JSON object for the resource you want to insert. The Postman editor indicates possible syntax errors with a red line on the right.

    Request body tab in Postman.
  6. Click Save, Enter or edit the request name, select the collection you want to save this request under, and click Save to <Collection Name>.

  7. Click Send to send the request.

    You can then analyze the response in the bottom pane, which includes the Body and the HTTP Status code.

    Response panel in Postman.

Getting Authorization and Obtaining a New Access Token Using Postman

Postman lets you use the user interface to obtain and access token using the OAuth 2.0 Authorization code flow. You can use this to simulate the OAuth 2.0 Authorization process and obtain an access token to authenticate your requests.

To get authorization and obtain a new access token using Postman:

  1. Open one of your API Requests and click the Authorization tab. The Authorization should be set as described in Creating and Sending API Requests Using Postman.

  2. Click Get a New Access Token. The Get new access token window appears.

    Get new access token window in Postman.
  3. Select the Grant type (Authorization Code), enter the Callback URL, Auth URL, Access Token URL, Client ID, Client Secret, and Scope (rest), and select the Client Authentication (Send as Basic Auth header). Except for the values specified, you can use environment variables as shown in the screenshot above.

  4. Click Request Token. The OpenAir or SSO sign-in page appears in a new window.

  5. Enter your sign-in details and submit.

    Note:

    If this is the first time you authorize the application, the Authorization screen will appear. Click Allow.

    The Manage Access Tokens window appears and shows the tokens obtained.

  6. Select the Access token value making sure you do not select the line break at the end (do not double click to select the entire string). Right click the selected value, point to Set:<Environment Name>, and click accessToken. Repeat for the Refresh Token value and set the refreshToken environment variable.

    You can now use the accessToken environment variable in your requests.

Refreshing Access Tokens Using Postman

Access token have a short validity period, you can refresh access tokens using a separate request or you can add a pre-request script to your API requests to refresh your access token if it has expired before you send a request.

Creating a Token Refresh Request Using Postman

You can create a request to refresh your access token. For more information about the request used to refresh tokens, see Refreshing an Access Token.

To create a token refresh request in Postman:

  1. Create a new request and use the following:

    • Method — POST

    • Request URL — {{accessTokenUrl}}

    • Body — Select form-data and enter the following key-values:

      • refresh_token{{refreshToken}}

      • access_token{{accessToken}}

      • grant_typerefresh_token

      • scoperest

    Token refresh request in Postman.
  2. Click the Tests tab and paste the following script. This test script will save the new access token and refresh token automatically to your environment variables.

                        pm.test("Status test", function (){pm.response.to.have.status(200)});
    if (pm.response.to.have.status(200)) {
        var data = pm.response.json();
        pm.environment.set("accessToken", data.access_token);
        pm.environment.set("refreshToken", data.refresh_token);
    } 
    
                      
  3. Click Save and save the request to your collection for later use. You can use this request to refresh your access token when it expires.

Refreshing Tokens Automatically Before Each API Request

You can add a pre-request script to your API requests to refresh your access token if it has expired before you send a request and save the new access token and refresh token automatically to your environment variables.

Open one your API requests, click the Pre-request Script tab, paste the following script, and click Save.

The first time the script runs, it will create the environment variable accessTokenExpires. The variable will be used to save the time the new access token is due to expire. The script compares the current time with the time the current access token is due to expire and only requests a new access token if the current access token has expired.

              var now = new Date().getTime();
var accessTokenExpires = pm.environment.get("accessTokenExpires");

if (accessTokenExpires === undefined) {
    accessTokenExpires = now;
}

if (accessTokenExpires && now >= accessTokenExpires) {
    var options = {
        method: 'POST',
        url: pm.environment.get("accessTokenUrl"),
        header: {
            "content-type": "application/json"
        },
        auth: {
            "type": "basic",
            "basic": [{
                "key": "username",
                "value": pm.environment.get("clientID")
            }, {
                "key": "password",
                "value": pm.environment.get("clientSecret")
            }]
        },
        body: {
            mode: 'formdata',
            formdata: [{
                key: "refresh_token",
                value: pm.environment.get("refreshToken"),
                disabled: false,
                description: {
                    content: "",
                    type: "text/plain"
                }
            }, {
                key: "redirect_uri",
                value: pm.environment.get("callbackUrl"),
                disabled: false,
                description: {
                    content: "",
                    type: "text/plain"
                }
            }, {
                key: "grant_type",
                value: "refresh_token",
                disabled: false,
                description: {
                    content: "",
                    type: "text/plain"
                }
            }, {
                key: "scope",
                value: "rest",
                disabled: false,
                description: {
                    content: "",
                    type: "text/plain"
                }
            }, ]
        }
    };
    console.log(options);
    pm.sendRequest(options, function(refreshError, refreshResponse) {
        if (refreshError) console.log(refreshError);
        var jsonRefreshResponse = refreshResponse.json();
        if (jsonRefreshResponse.access_token) {
            pm.test("Token refreshed and saved", () => {
                pm.expect(refreshResponse).to.have.property('code', 200)
            });
            pm.environment.set("accessToken", jsonRefreshResponse.access_token);
            pm.environment.set("refreshToken", jsonRefreshResponse.refresh_token);
            var t = new Date();
            t.setSeconds(t.getSeconds() + jsonRefreshResponse.expires_in);
            pm.environment.set("accessTokenExpires", t.getTime());

        } else {
            pm.test("Refresh token request failed - Get new access and refresh tokens by clicking \"Get New Access Token\" in the Authorization tab, save the values in the appropriate environment variables, and try sending the request again", () => {
                pm.expect(refreshResponse).to.have.property('code', 200)
            });
        };
    });
}