Using Postman with dynamic bearer tokens the right way
Tags: api, postman, magento, webdev
Published: 2021-11-28 16:11:46

---
title: Using Postman with dynamic bearer tokens the right way
published: true
description: 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.
tags: api, postman, magento, webdev
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oe3f1etsvfsndajv861n.png
---

##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

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 |
```

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

![Postman create environment](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jgrw1jdhlahnqualaori.png)

##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
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mztn14hqwt9z3cqkhc4n.png)

##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     |
```

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

##Set up bearer token authorisation

Under **Authorization**, set type to **Bearer Token**

Then set the token value to:

```
{{magento_token}}
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qk0ep8rg8gr446phhp67.png)

## 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);
});
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kpmxtq2lw1khxjohedx2.png)

##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
}
```

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

##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.