Skip to content

Instantly share code, notes, and snippets.

@franckweb
Last active October 5, 2021 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save franckweb/a3c5efc1d498c8df1b4b31c556f4bbaa to your computer and use it in GitHub Desktop.
Save franckweb/a3c5efc1d498c8df1b4b31c556f4bbaa to your computer and use it in GitHub Desktop.
Postman script to automatically get token and assign it to environment variable
/*
* Postman script to automatically get token and assign it to environment variable
* - Create new endpoint (GET, POST, etc)
* - Create an env variable called "access_token"
* - Add this script in Tests tab in Postman for your newly created endpoint
* - To debug you can use Postman Console (Alt + Ctrl + C)
*/
const tokenUrl = 'https://mywebsite.com/auth/token';
const apiKey = "123FJSKAHFSAJFHSAFKJSAFHASSAFA";
const apiKeySecret = "456FSAFLKAFAKFJLSFSAJFLKSAJFLKA";
const getTokenRequest = {
method: 'POST',
url: tokenUrl,
header: {
'MY-CUSTOMER-KEY': apiKey,
'MY-CUSTOMER-SECOND-KEY': apiKeySecret
},
body: {}
};
pm.sendRequest(getTokenRequest, (err, response) => {
const jsonResponse = response.json();
const newAccessToken = jsonResponse.token;
// create a postman environment variable called "access_token"
// and next code line will set it with retrieved token
pm.environment.set('access_token', newAccessToken);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment