Capturing a Login Bearer Token for Subsequent Calls - Postman

Overview

When working with Postman against APIs secured by a bearer token architecture, it is necessary to login first and submit the associated bearer token with the API call. This article presents a simple mechanism for doing so.

Acknowledgements

Thanks to Dan Williams for providing the code below!

Procedure

(1) Within a Postman Collection, create a request for your Login API. (The reason this is done within a Postman Collection is so Postman variables can be used to store the bearer token.)

(2) On the Tests tab, add the following code, which will capture the bearer token in the Postman variable "token".

pm.test("Extract Token", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.token).to.not.equal(null);
    pm.environment.set("token", jsonData.token);
});

(3) For the secured API request, navigate to the Authorization tab.

(4) For the type, select "Bearer Token".

(5) For the Token, specify

{{token}}