Hi All, body response capturing only few details and missing some of the details from response body

This is the response getting from postman post request

{
    "response": {
        "appInternalClientId": 122222222222222,
        "appNumber": "6565765656",
        "copyParams": {},
        "taskStatusLabel": "Completed",
        "applicationId": 564654545465,
        "taskStatus": 30,
        "status": 201
    },
    "id": 1305854,
    "message": null,
    "taskStatus": "Running",
    "processingTime": 1000,
    "status": 202
}
// k6 response after post request submit
{"id":1305882,"message":null,"taskStatus":"Running","processingTime":19212,"status":202}

It has to print “response”: information but k6 is not printing. how to get the response to be printed.

if I print resp1.body.id getting undefined actually it should give above id information.

K6 - it is restricting the wherever response tag is there in the body and unable to print content from the body. do i need to add any imports. How to make it to get the complete response from post request as im getting from postman.

My Script

import http from "k6/http";
import { check, sleep } from "k6";
import { htmlReport } from "https://raw.githubusercontent.com/benc-uk/k6-reporter/main/dist/bundle.js";
import { textSummary } from "https://jslib.k6.io/k6-summary/0.0.1/index.js";
import papaparse from "https://jslib.k6.io/papaparse/5.1.1/index.js";
import { SharedArray } from "k6/data";

const loginCredentials = new SharedArray('users', function () {
  return papaparse.parse(open('./testData/abc_login_credentials.csv'), { header: true }).data;
});

const applicantsInfo = new SharedArray('userInfo', function () {
  return papaparse.parse(open('./testData/submit_application_test_data_with_epoch_time.csv'), { header: true }).data;
});

export const options = {
  stages: [{ duration: "10s", target: 1 }],
};

export default function () {
  const baseURL = "https://abc/api/";
  const xapikey =
    "1gYaVyIbjwyclgmMpC1gYaVyIbjwyclgmMpC1gYaVyIbjwyclgmMpC1gYaVyIbjwyclgmMpC";

  const randomUser = loginCredentials[Math.floor(Math.random() * loginCredentials.length)];

  const primaryApplicantInfo = applicantsInfo[Math.floor(Math.random() * applicantsInfo.length)];
  const coApplicantInfo = applicantsInfo[Math.floor(Math.random() * applicantsInfo.length)];

  const payLoad = {
    clientId: randomUser.companyID,
    userId: randomUser.username,
    password: randomUser.pwd,
  };

  //console.log("testData" + testData);

  let res = http.get(baseURL + "about");
  let cookieData = res.cookies;

  //console.log(cookieData);
  let AWSALB = cookieData.AWSALB[0].value;
  let AWSALBCORS = cookieData.AWSALBCORS[0].value;
  let JSESSIONID = cookieData.JSESSIONID[0].value;
  let XSRFTOKENDEMO = cookieData["XSRF-TOKEN-DEMO"][0].value;
  let XSRFTOKEN = cookieData["XSRF-TOKEN"][0].value;

  const params = {
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "X-XSRF-TOKEN": XSRFTOKEN,
      "x-api-key": xapikey,
      JSESSIONID: JSESSIONID,
    },
  };

  const resp_post = http.post(baseURL + "auth/login", payLoad, params);
  check(resp_post, {
    "is status 200": (r) => r.status === 200,
  });

  let res_about = http.get(baseURL + "about");
  let cookieData_app_submit = res_about.cookies;
  //console.log(cookieData_app_submit);

  const params1 = {
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Accept-Encoding": "gzip, deflate",
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36",
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36",
      "Accept": "application/json",
      "AWSALB": cookieData_app_submit.AWSALB[0].value,
      "AWSALBCORS": cookieData_app_submit.AWSALBCORS[0].value,
      "X-XSRF-TOKEN": cookieData_app_submit["XSRF-TOKEN"][0].value,
      "XSRF-TOKEN-DEMO": cookieData_app_submit["XSRF-TOKEN-DEMO"][0].value,
      "x-api-key": xapikey,

    },
    body: {
      async: true,
      content: testData,
      loanType: 1448155676576571,
    }
  };

  var response = http.post(
    baseURL + "portal/abc/submit",
    params1.body,
    params1.headers
  );

  console.log(response.body);

  var taskid = parseInt(JSON.stringify(response.body).substring(9, 16));

    let getResponse = http.get(
      baseURL + "portal/status/" + taskid,
      params1.headers
    );
    //console.log(baseURL+"portal/status/"+taskid)
    console.log(getResponse.body);

  
  
  console.log(getResponse.status_text);
  console.log(getResponse.status);

  check(response, {
    "is status 200": (r) => r.status === 200,
  });
}

export function handleSummary(data) {
  return {
    "summary.html": htmlReport(data),
    stdout: textSummary(data, { indent: " ", enableColors: true }),
  };
}

Hi @bikshamar,

resp1.body is a string, and so you cannot use it as if it were a JSON object - you would need to parse the response as JSON first, or use resp1.json() instead:

let resp1 = ...

// parse the response string as JSON:
const jObj = JSON.parse(resp1.body);
const taskId = jObj.id;

// OR use the built-in .json() function:
// const taskId = resp1.json().id;

console.log("id " + taskId);

Ideally, you would also add some error handling in case the response is not JSON which could happen if, for example, the server is overloaded and instead returns an error page (which may not be JSON):

let resp1 = ...

if (resp1.json()) {
  // same code as above
} else {
  console.warn("Response is not JSON. Received:\n" + resp1.body);
}
1 Like

Thank you @Tom for your help, i have used response.json() and getting response now.
one issue is after submitting post request need to wait for another post request get the response and currently handling with sleep, is there any way to loop to wait until get the another post request response because with sleep some time it taking much time for test

//1st request
sleep(1);

var response = http.post(
baseURL + “portal/abc/submit”,
params1.body,
params1.headers
);
console.log(response.json());
//2nd request
sleep(5);
let grp = http.get(
baseURL + “portal/status/” + response.json().id,
params1.headers
);

let getrpData = grp.json();

Your VUs execute requests synchronously, meaning that by the time you call the 2nd request, you will already have received the response to the 1st request. In other words, you don’t need to use sleep.

What is the error you are seeing with the above?

@Tom thank you.
The problem is if i dont give sleep(5) second request is not giving response. Same payload works fine with postman and jmeter but K6 im getting the api error. I dont know how to resolve the issue. K6 is sending one json variable as null thats why getting null pointer exception.

//1st request response is
INFO[0024] {“id”:1311384,“message”:null,“taskStatus”:“Running”,“processingTime”:19143,“status”:202} source=console
INFO[0030] ============================================after status ==================== source=console

//2nd request reponse
{“success”:true,“response”:{“status”:500,“appInternalClientId”:14079356576656,“ex”:“App Submitted with post processing failure:
com.abc.dr1.reqlib.ServiceException: ApplicationImpl.saveWorksheet Exception:java.lang.NullPointerException”,“appNumber”:“44896640”,“taskStatusLabel”:“Completed”,“applicationId”:3393828595540,“taskStatus”:30},“message”:“Submitted”}

Hi @bikshamar, the second response is with status 500 which is internal server error with the server and the message states that there is a NullPointerException in some Java app(given the logs provided). (This might not be an error in the system you are directly hitting it might be in something else that then bubbles up).

This plus the fact that it works when you sleep for 5 seconds likely means that the application can’t handle the load … for some reason.

Given the NullPointerException I would expect something else internally couldn’t handle the load and did application did not correctly handle that. This is clearly a bug in the system under test.

I would recommend looking through the logs of the systems and try to find what the exception actually is (it’s truncated here) and figure fix that.

Hope this helps you!

p.s. Just noticed you have an API key in “My Script”. You seem to not have provided us the endpoint being hit so hopefully nobody will be able to misuse it. But, please, make certain that if this is publicly available endpoint to revoke this particular API key soon.

Thank you @mstoykov. I have changed the somepart in api key and , endpoint urls to not to call from others.

App is getting submit from Postman and Jmeter with same payload but in K6 getting the null pointers exception. I have checked with developers and they are saying if api has the issue with payload it should not work in postman and JMeter.

Nullpointer exception getting for only with K6 script. I have been facing this issue since few days.

Given that the issue dissapears if you slow down(which is waht sleep does) I would argue that this is a problem with the API not being able to handle the load. Postman and/or Jmeter might just not make it fast enough - possibly because of sleep like behaviour with them as well.

@mstoykov thank you for your help. i will check with api issue again.