How to create a method to retrieve data using rest API from a database in CakePHP?


#1

I am new to CakePHP. I have a website API created with CakePHP. I need to retreive data from the database using a GET or POST request. The table is named testItem. the table has only three field: ID which is the PRIMARY KEY int with AUTOINCREMENT, name which is a varchar, and description (also a varchar).

I have created a model for the table in the Model folder of the website named TestItem which contains this data:

<?php

/**
 * Created by PhpStorm.
 * User: win 7
 * Date: 4/8/2017
 * Time: 3:23 PM
 */
App::uses('AppModel', 'Model');
App::uses('Security', 'Utility');
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
App::uses('AuthComponent', 'Controller/Component');

class TestItem extends AppModel {

    // public $hasMany = array(
    //     'Subcategory' => array(
    //         'className' => 'Subcategory',
    //     )
    // );

public $validate = array(
	'name' => array(
         'maxLength' => array(
            'rule' => array('maxLength', 30),
            'message' => 'Category name can not be more than 255 characters.'
          )
         
     ),
    'description' => array(
         'maxLength' => array(
            'rule' => array('maxLength', 30),
              'message' => 'Category name can not be more than 255 characters.'
          ),
         
     ),
 	
     );
}

What I want is to retrieve the data from these to field using a rest API.
here is the method I have writted so far in my ApisController.php named api_getTestItem :

 public function api_getTestItem() {

        $language = $_REQUEST['lang'];
		$this->TestItem->virtualFields['name'] = "name_$language";
		$cat_list= $this->TestItem->find('all',array('order'=>'TestItem.priority ASC'));
		
		if(!empty($cat_list)){
			$cat_list = Set::extract('/TestItem/.', $cat_list);
			$this->Basic->response(200,'get_data',$cat_list);
		}
		else
		{
			$this->Basic->response(404,'not_found');
		}
    }

But when I execute , I get this error:

Notice (8): Undefined variable: message [APP\View\Errors\error500.ctp,
line 6]

I have already connected the database to my CakePHP website using phpmyadmin.

I have already searched google and looked into these articles:
https://stackoverflow.com/questions/16264546/creating-a-cakephp-rest-api-from-an-existing-project

https://stackoverflow.com/questions/30014583/cakephp-retrieve-info-from-database

https://stackoverflow.com/questions/27592679/creating-rest-api-with-cakephp

They were not useful in my situation.
I would truly appreciate any help. Thanks a lot.


#2

Full code?

$this->Basic->response() What is that supposed to do?

Don’t use $_REQUEST.

The error you are getting tells that there is no message passed.

It looks like you are using Cake version 2.