DEV Community

Cover image for Using Postman with dynamic bearer tokens the right way
Rhuaridh
Rhuaridh

Posted on

Using Postman with dynamic bearer tokens the right way

The challenge

This article will focus on Magento, but it can apply to any API that uses a bearer token for authentication.

Magento's API uses an expiring bearer token for authorization. This means that you will need to routinely pull down a new bearer token in order to keep using the API.

This is a great security feature, but adds a layer of complexity when it comes to debugging the API locally.

I will show you the best way to dynamically retrieve the bearer token inside your postman request so that you can debug your API properly and unhindered.

Magento's API auth can be defined in three steps:

  • Use admin login details to fetch bearer token
  • Use bearer token to access all other protected API calls
  • Refresh bearer token as needed

Create a Magento admin user

So for this rest api we will be using a standard magento 2 admin account. So create an admin account and give it the required role to access the resources needed.

In my case I created a demo user:

demo
SomeUniquePasswordFrogApple12
Enter fullscreen mode Exit fullscreen mode

And assigned the full Administrators role for simplicity. In a real world example you should give the API account the minimum access required.

Create new Environment called Magento2

Inside postman we need to create a new Environment. This is where we will configure all of our store specific variables.

| Variable         | Value                         |
| magento_token    |                               |
| magento_url      | https://your-store-url.com    |
| magento_username | demo                          |
| magento_password | SomeUniquePasswordFrogApple12 |
Enter fullscreen mode Exit fullscreen mode

Now remember to click "Save" so that these variables can be used.

Postman create environment

Create a postman request

Create a new Collection called Magento2, this is to organise our magento requests.

Within this collection we can create our first API request called "List Products"

Create a GET request with URL:

{{magento_url}}/rest/all/V1/products
Enter fullscreen mode Exit fullscreen mode

Note that it uses our magento_url environment variable we configured earlier.

Add environment to our request

Make sure you add the Magento2 environment to this request so it can access our newly created variables.

Postman set environment

Add query parameters

Since we are using the list product API call we need to add the required searchCriteria field.

Under Params, add:

| Variable                    | Value |
| searchCriteria[pageSize]    | 10    |
| searchCriteria[currentPage] | 1     |
Enter fullscreen mode Exit fullscreen mode

Postman params

Set up bearer token authorisation

Under Authorization, set type to Bearer Token

Then set the token value to:

{{magento_token}}
Enter fullscreen mode Exit fullscreen mode

Because the bearer token will change over time we are using our magento_token environment variable here. We will configure this in the next section.

Your setup should look like this:

Postman set bearer

Configure dynamic bearer token

Now this is where the magic happens. Before every request to the API we will fetch a fresh bearer token from Magento so that it will always work.

Inside our List Products api request, we can add a "Pre-request Script" that will be executed before each request.

function getQueryString (obj) {
    return Object.keys(obj).map((key) => `${key}=${obj[key]}`).join('&');
}

const qs = {
    'username': postman.getEnvironmentVariable("magento_username"),
    'password': postman.getEnvironmentVariable("magento_password")
};

pm.sendRequest({
    url: postman.getEnvironmentVariable("magento_url") + '/rest/all/V1/integration/admin/token?' + getQueryString(qs),
    method: 'POST',
    header: {
        'content-type': 'application/json',
    },
}, function (err, res) {
    var magento_token = res.json();
    postman.setEnvironmentVariable("magento_token", magento_token);
});
Enter fullscreen mode Exit fullscreen mode

If you read through the script you'll notice it uses our magento username and password env variables we configured earlier, then queries our Magento API's token endpoint and retrieves our bearer token and saves it as magento_token.

Your postman configuration should look like this:

Postman set pre request script

Send request

And that's it! We can now click "Send" and we should retrieve a json response containing the first 10 products in the store:

{
    "items": [
        {
            "id": 1,
            "sku": "24-MB01",
            "name": "Joust Duffle Bag",
            "attribute_set_id": 15,
            "price": 34,
            ...
        },
        ...
    ],
    "search_criteria": {
        "filter_groups": [],
        "page_size": 10,
        "current_page": 1
    },
    "total_count": 2046
}
Enter fullscreen mode Exit fullscreen mode

Postman response

Closing thoughts

This is quick to set up, and quick to adapt to other platforms that use bearer tokens in their API.

If you are like me and work across a number of Magento stores daily, then you can configure multiple environments in postman this way and switch between them seamlessly.

Top comments (0)