Creating Rest API without views using cakePHP 3.5

1.5k views Asked by At

I'm trying to create Rest API without view and planning to use these api's in angular 2 application. does have any idea about it?

3

There are 3 answers

0
styks On

Cake makes this incredibly easy. A few things I have learned building without views.

Set the _serialize variable

$data = ['cheeses' => ['gouda', 'pepper jack', 'cheddar']];
$this->set('responseData', $data);
$this->set('_serialize', 'responseData');

Throw bad request exceptions and other network related exceptions

Cake will render nice json views for you.

Set your accept header when issuing and ajax request to be application/json

You can use cake prefixes for api versions

Look at Stateless Authentication for your api

0
eclaude On

In your AppController.php, with these parameters, all of your controllers will be render in json

public function beforeRender(Event $event)
{
     $this->RequestHandler->renderAs($this, 'json');
     $this->response->type('application/json');
     $this->set('_serialize', true);
}
0
Boni On

CakePHP will render json easily.

In your Controller,look like something.

protected   $responseBody   =   [];

public function beforeRender(Event $event){

    foreach($this->responseBody as $responseKey=>$response){

       $this->set($responseKey, $response);
    }
    $this->set('_serialize', array_keys($this->responseBody));
}

public function initialize()
{
    parent::initialize();

    $this->RequestHandler->renderAs($this, 'json');
}

public function index(){

    $this->request->allowMethod(['get']);  // Method like post,get..

    $this->responseBody["statusCode"]       =   200;

    $this->responseBody["statusDescription"]        =   ''; //You send any text in json.

    $this->responseBody["data"]  =  []; // All data that you can send.

}

For further informations , You can see CakePHP Cookbook REST API to click here