Codeception - POST raw JSON string

Carlton picture Carlton · Oct 31, 2014 · Viewed 8.4k times · Source

I am sending the following request using jQuery

var url = 'http://site.local/api/package/create';
var data = {
  "command": "package",
  "commandParameters": {
    "options": [
      {
        "a": true
      }
    ],
    "parameters": {
      "node_id": 1111,
      "node_name": "Node Name"
    }
  }
}
$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    contentType: "application/json",
    success: function (a, b, c) {
        // Do something with response
    }
});

Also doing something similar using Postman (Chrome plugin)

POST
Content-Type: application/json
Payload:
{
      "command": "package",
      "commandParameters": {
        "options": [
          {
            "a": true
          }
        ],
        "parameters": {
          "node_id": 1111,
          "node_name": "Node Name"
        }
      }
    }

It is intended that I send a raw JSON string to my server, rather than have Jquery convert it to post data. How do I perform the same in Codeception, I just can't see it in the documentation, I only see the following..

$I->sendAjaxPostRequest('/updateSettings', array('notifications' => true));

So I guess I want to make a POST request in Codeception, while attaching JSON in the body of the request?

Answer

Carlton picture Carlton · Oct 31, 2014

The encodeApplicationJson function in codeception/src/Codeception/Module/REST.php checks if the header "Content-Type" and value "application/json" exist.

If this is set it returns json_encode($parameters) which is a string which is what I want, so I end up doing something like this...

    $I->haveHttpHeader('Content-Type', 'application/json');
    $I->sendPOST('api/package/create', [
        'command' => 'package',
        'commandParameters' => [
            'options' => [],
            'arguments' => []
        ]
    ]);
    $I->canSeeResponseCodeIs(200);
    $I->seeResponseIsJson();

Some information on the difference between sendpost and sendajaxpostrequest

http://phptest.club/t/what-is-the-difference-between-sendpost-and-sendajaxpostrequest/212#post_2