DEV Community

Domantas Jurkus
Domantas Jurkus

Posted on

Postman's pre-request scripts - quick authentication 🚀

In this post I'll share a setup that allows quickly authenticating with APIs that require credentials.

  1. Create a new Postman collection. Informative names always help:

  2. Inside the collection, set up a new request that requires you to have some sort of token. No surprise, the request should fail.

  3. Inside the Postman collection, create a set of variables and set up the authentication method for the whole collection.

Click on the collection name, go to the Variables tab and create two variables: username and password. Use a dashboard account as needed.

  1. In the Authorization tab, Select “Bearer Token“, and for the value, add {{users_api_token}}. We will generate this token next.

  2. Let’s name our new request something like “Set Login“. On the request, go to the “Pre-request Script“ tab and add the following script:

const postRequest = {
  url: 'https://api.com/endpoint',
  method: 'POST',
  header: {
    'Content-Type': 'application/json'
  },
  body: {
    mode: 'raw',
    raw: JSON.stringify({
        "username": pm.collectionVariables.get("username"),
        "password": pm.collectionVariables.get("password")
    })
  }
};

pm.sendRequest(postRequest, function (err, response) {
    if (response.code === 200) {
        pm.collectionVariables.set("users_api_token", response.json().token);
    } else {
        pm.collectionVariables.set("users_api_token", '');
    }
});
Enter fullscreen mode Exit fullscreen mode
  1. Run your request - if everything is good, you request should go through with results returned 🚀

  2. Best part: create a new request in the collection, The request should reuse the token saved in your collection. Just make sure that when you go to the Authorization tab for the request, the type is set to “Inherit from parent“ (which should be set by default):

  3. The token will expire after a day, but getting a new one will be as easy as going to your “Set Login“ request and pressing Send ⬇️

Top comments (0)