PHP code example of pejonic / cakephp-3-rest-api

1. Go to this page and download the library: Download pejonic/cakephp-3-rest-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pejonic / cakephp-3-rest-api example snippets


Plugin::load('RestApi', ['bootstrap' => true]);

namespace App\Controller;

use RestApi\Controller\ApiController;

/**
 * Foo Controller
 */
class FooController extends ApiController
{

    /**
     * bar method
     *
     */
    public function bar()
    {
		// your action logic

		// Set the HTTP status code. By default, it is set to 200
		$this->httpStatusCode = 200;

		// Set the response
		$this->apiResponse['you_response'] = 'your response data';
    }
}


return [
    'ApiRequest' => [
        'cors' => [
            'enabled' => true,
            'origin' => '*'
        ]
    ]
];


return [
    'ApiRequest' => [
        'cors' => [
            'enabled' => true,
            'origin' => ['localhost', 'www.example.com', '*.example.com']
        ]
    ]
];



namespace App\Controller;

use RestApi\Controller\ApiController;

/**
 * Articles Controller
 *
 * @property \App\Model\Table\ArticlesTable $Articles
 */
class ArticlesController extends ApiController
{

    /**
     * index method
     *
     */
    public function index()
    {
        $articles = $this->Articles->find('all')
            ->select(['id', 'title'])
            ->toArray();

        $this->apiResponse['articles'] = $articles;
    }
}



namespace App\Controller;

use RestApi\Controller\ApiController;

/**
 * Foo Controller
 *
 */
class FooController extends ApiController
{

    /**
     * bar method
     *
     */
    public function restricted()
    {
        $this->request->allowMethod('post');
        // your other logic will be here
        // and finally set your response
        // $this->apiResponse['you_response'] = 'your response data';
    }
}



namespace App\Controller;

use Cake\Network\Exception\NotFoundException;
use RestApi\Controller\ApiController;

/**
 * Foo Controller
 *
 */
class FooController extends ApiController
{

    /**
     * error method
     *
     */
    public function error()
    {
        $throwException = true;

        if ($throwException) {
            throw new NotFoundException();
        }

        // your other logic will be here
        // and finally set your response
        // $this->apiResponse['you_response'] = 'your response data';
    }
}