CakePHP, PHP

Simple JSON response with CakePHP 3

CakePHP 3 Book – Chapter JSON and XML views

Controller code:

namespace App\Controller;
 
class MyJsonController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('RequestHandler');
    }
 
    public function index()
    {
        $customers['id'] = '123';
        $this->set('customers', $customers);
        $this->set('_serialize', ['customers']);
    }
}

This is the response:

{
    "customers": {
        "id": "123"
    }
}

To get this response and not a ‘500 Internal Error’ for a missing template-view file, in the request you make, set Content-Type and Accept headers:

Content-Type: “application/json; charset=utf-8”;
Accept: “application/json”;

for ex. in C#

HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(url);
hwr.ContentType = "application/json; charset=utf-8";
hwr.Method = "POST";
hwr.ContentLength = data.Length;
hwr.Accept = "application/json";