Send POST request with JSON payload

Hello k6 community!

Trying to figure out how to send POST request with JSON payload using k6. Example of a working curl request:

curl --location --request POST 'http://localhost/api/v4/projects/51/repository/commits' \
--header 'PRIVATE-TOKEN: ********' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data-raw '{
  "branch": "branch_name",
  "commit_message": "commit message",
  "start_branch": "test",
  "actions": [
      "action": "create",
      "file_path": "",
      "content": "#some content"

Code I was trying to use:

let params = { headers: { "Accept": "application/json", "PRIVATE-TOKEN": `${__ENV.ACCESS_TOKEN}` } };
    let body = {
      branch: 'test',
      commit_message: "test-commit",
      actions: [
          action: "create",
          file_path: "",
          content: "#Test commit"
    };`${__ENV.ENVIRONMENT_URL}/api/v4/projects/${data.projectId}/repository/commits`, body, params);

I’m getting 400 response error - actions array is being interpreted as invalid. Could you please clarify if there is a way to send such request using k6?

Worth noting that also tried to send the payload as a JSON file, still not successful.


You are 99% there, you just have to use JSON.stringify() on the body, so something like:`${__ENV.ENVIRONMENT_URL}/api/v4/projects/${data.projectId}/repository/commits`, JSON.stringify(body), params);

Docs and examples:

Thank you for looking into it! Apologies for not mentioning it above, I’ve tried to use JSON.stringify(body) as well before and the response was worse - server didn’t process the whole body - “‘branch is missing, branch is empty, commit_message is missing, actions is missing’” while when sending the body as it is, it processes at least branch and commit message. I assumed that the problem related to the fact that all objects sent in body are being x-www-form-urlencoded per docs and that it affects how the request will be processed, not sure how to bypass this

Try adding 'Content-Type': 'application/json' to the headers object, since that’s the only difference from the curl command you posted at this point. I assume whatever is processing the request on the backend doesn’t know to expect JSON without it.

1 Like

Oh my, how did I miss it! Thank you so much for noticing it :pray: It works now :tada: