In this post I'll share a setup that allows quickly authenticating with APIs that require credentials.
Create a new Postman collection. Informative names always help:
Inside the collection, set up a new request that requires you to have some sort of token. No surprise, the request should fail.
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.
In the Authorization tab, Select โBearer Tokenโ, and for the value, add
{{users_api_token}}
. We will generate this token next.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", '');
}
});
Run your request - if everything is good, you request should go through with results returned ๐
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):
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)