2

I'm building a REST-full API in Yii2 framework. I'm sending the data in JSON format and returning response in JSON response as well.

I'm making the test request with the call via cmd:

C:\Windows\system32>curl -v -H "Content-Type: application/json" -X POST http://<path_to_host>/www/users/register -d "{\"user_firstname\":\"Name\", \"user_lastname\":\"LastName\",\"user_email\":\"test@email.com\",\"user_username\":\"usernameTest\",\"user_password\":\"123456\",\"user_is_eighteen\":\"true\"}

with this call the corresponding action is called and my code is executed. Then at the end of the logic in the called controller I'm trying to send the response as the following:

.
.
creating variables $model and $error_msg
.
.
header('HTTP/1.1 200 OK '); 
header('Content-type: application/json'); 

$response = Yii::$app->response;
$response->format = Response::FORMAT_JSON; 
$response->statusCode = $200; 
$response->data = [ 
                    'data' => $model,
                    'errors' => $error_msg, 
                  ];        

Yii::$app->end(); 

so as said before, this I'm testing the call via cmd:

enter image description here

Later this request will be created (and responses will be received) by mobile application. This is what I got as a result from the cmd, and I'm wondering will this be enough for receiving the JSON response at the mobile side? (since I'm not sure how to test it)

delux
  • 1,694
  • 10
  • 33
  • 64
  • 1
    Yes, it should be. No idea why you are both setting the header 2 times though. 1 time with the header function the other with $response->format = Response::FORMAT_JSON; – Mihai P. Oct 22 '15 at 00:07
  • So that means that I can remove the line: **header('Content-type: application/json');** is that correct? – delux Oct 22 '15 at 16:24
  • Correct, use $response to format header responses. It'll save you from headache. – David J Eddy Nov 27 '15 at 23:29

0 Answers0