Skip to content

Instantly share code, notes, and snippets.

@QasimTalkin
Last active November 19, 2021 13:50
Show Gist options
  • Select an option

  • Save QasimTalkin/0426a0fab698b55bbb08cc3522f5da9d to your computer and use it in GitHub Desktop.

Select an option

Save QasimTalkin/0426a0fab698b55bbb08cc3522f5da9d to your computer and use it in GitHub Desktop.
Automatically generate and set up access token and host in postman

Get postman to automatically generate an access token and set up your host and make any request

Changes based on request and response

  • Change host to your 'host'
  • Your access token key in response maybe different could vary from being acessToken, token, access_token and so on, read accordingly and change the conde where ever access_toekn is being called
  • Same for expires in
pm.collectionVariables.set("host", "https://reqbin.com/echo/post/json");
const authTokenReq = {
  url: 'https://reqbin.com/echo/post/json',
  method: 'POST',
  header: {
    "content-type": "application/json"
  },
  body: {
    mode: 'raw',
    raw: JSON.stringify({
      "username": "your user name",
      "password": "your password and other key valus pairs if needed"
    })
  }
};

const porcessResponse = (err, response) => {
  pm.collectionVariables.set("access_token", response.json().access_token);
  var expiryDate = new Date();
  expiryDate.setSeconds(expiryDate.getSeconds() + response.json().expires_in);
  pm.collectionVariables.set("expires_in", expiryDate.getTime());
};

if (!pm.collectionVariables.get('expires_in') || !pm.collectionVariables.get('access_token')) {
  pm.sendRequest(authTokenReq, (err, response) => porcessResponse(err, response));
} else if (pm.collectionVariables.get('expires_in') <= (new Date()).getTime()) {
  pm.sendRequest(authTokenReq, (err, response) => porcessResponse(err, response));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment