Capture response body from POST for my GET endpoint

Hi team,

I have two API endpoints that I wanted to run sequentially. I’d like to pass the response body “id” from POST and include the Id in the GET endpoint. I have a sample one below:

  group('POST API', (_) => {
    // Story request
    let response = http.post(`${env.baseUrl}/api/`, body, params);
    check(response, {
      'is status 201': (r) => r.status === 201
    });
    let postId = r.body.id;
  });

  group('GET API', (_) => {
    // Story request
    let response = http.post(`${env.baseUrl}/api/${postId}`, body, params);
    check(response, {
      'is status 200': (r) => r.status === 200
    });
  });

It should be let postId = response.body.id;

Hi @poponuts,

As @aakash.gupta mentions, there seems to be an issue with how postId is assigned. In addition to that, you need to move the declaration of postId outside of the group due to how JavaScript scopes variables, otherwise it will either be null or error out once it’s being accessed in the next group.

Best,
Simme

Thanks @aakash.gupta I changed the variable but as @simme said, I need to declare this outside the POST group as it displays undefined when called by GET endpoint.

@simme However, when I put it outside the POST group, the error below appears:

ReferenceError: response is not defined

Only workaround I can think of is not use group and put those tests together in a single group.

@poponuts, I think you just moved the whole thing out, while you need to move just the definition of the variable

  let postId; // move just the definition
  group('POST API', (_) => {
    // Story request
    let response = http.post(`${env.baseUrl}/api/`, body, params);
    check(response, {
      'is status 201': (r) => r.status === 201
    });
    postId = response.body.id; // still set it in the group
  });

  group('GET API', (_) => {
    // Story request
    let response = http.post(`${env.baseUrl}/api/${postId}`, body, params);
    check(response, {
      'is status 200': (r) => r.status === 200
    });
  });
2 Likes