Dear All,
I have a following requirement:
I have 2 POST requests, where first will give the access_token and I need to use this access_token in the next POST call.
- Call a POST request and fetch the access_token (this call should only be once, because the token is valid for next 30 mins and need not to be called again)
- Store it in a global variable
- Call another POST with the fetched access_token and run this request for multiple users
I am new to K6 and this might be like a very beginner code, please guide me how can I achieve this.
Thanks in advance!
import http from 'k6/http';
import { sleep } from 'k6';
let bearerToken;
export default function () {
const url = "https://xxxx.xxxx.com/xxxx/xxxx/v1/token?companyId=xxxx-xxxx";
const respToken = http.post(url, { 'grant_type': 'client_credentials', 'scope': 'xxxx'}, {
headers: { 'X-xxxx-Context': 'companyId', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'Authorization': 'Basic xxxx==' },
});
if (respToken.status === 200) {
console.log('Request succeeded!');
console.log(respToken.status);
const responseJson = JSON.parse(respToken.body);
bearerToken = "Bearer " + responseJson.access_token;
console.log("!!!!!bearerToken: " + bearerToken);
} else {
console.error('Request failed with status code: ' + respToken.status + ' ' + respToken.body);
}
sleep(1);
const urlService = "https://api-xxx.xxxx.com/xxxx/applications";
let headers = { headers: { "Accept": "application/json", "Content-Type": "application/json", "Authorization": bearerToken}}
let rawBody = JSON.stringify({
"countryCode": "ES",
"companyId": "xxxx",
"channel": "",
"onboardingProductType": "xxxx"
});
const resp = http.post(urlService, rawBody, headers);
if (resp.status === 201) {
console.log('Request succeeded!');
} else {
console.error('Request failed with status code: ' + resp.status);
}
sleep(1);
}