REST API Specification – Custom Models

REST API code is flexible, and it allows you to write API methods for custom models that should be accessible via API.

But this case is a bit specific, because you will need to develop a custom controller that will manage those requests. If you want to perform API actions on “SampleModel”, you need to create SampleModelApiController.php with the following code:

    class ApiSampleModelApiController extends ZurmoModuleApiController
    {
        public function actionCustomGet()
        {
            $params = Yii::app()->apiHelper->getRequestParams();
            if (!isset($params['id']))
            {
                $message = Yii::t('Default', 'The id specified was invalid.');
                throw new ApiException($message);
            }
            $result    =  $this->processRead((int)$params['id']);
            Yii::app()->apiHelper->sendResponse($result);
        }

        public function actionCustomList()
        {
            $params = Yii::app()->apiHelper->getRequestParams();
            $result    =  $this->processList($params);
            Yii::app()->apiHelper->sendResponse($result);
        }

        public function actionCustomPost()
        {
            $params = Yii::app()->apiHelper->getRequestParams();
            if (!isset($params['data']))
            {
                $message = Yii::t('Default', 'Please provide data.');
                throw new ApiException($message);
            }
            $result    =  $this->processCreate($params['data']);
            Yii::app()->apiHelper->sendResponse($result);
        }

        public function actionCustomUpdate()
        {
            $params = Yii::app()->apiHelper->getRequestParams();
            if (!isset($params['id']))
            {
                $message = Yii::t('Default', 'The id specified was invalid.');
                throw new ApiException($message);
            }
            $result    =  $this->processUpdate((int)$params['id'], $params['data']);
            Yii::app()->apiHelper->sendResponse($result);
        }

        public function actionCustomDelete()
        {
            $params = Yii::app()->apiHelper->getRequestParams();
            if (!isset($params['id']))
            {
                $message = Yii::t('Default', 'The id specified was invalid.');
                throw new ApiException($message);
            }
            $result    =  $this->processDelete((int)$params['id']);
            Yii::app()->apiHelper->sendResponse($result);
        }

        protected function getModelName()
        {
            return 'SampleModel';
        }

        protected function getSearchFormClassName()
        {
            return 'SampleModelSearchForm';
        }
    }
?>

You then need to create a search form for this model (if it does not already exist), and in the simplest case, SampleModelSearchForm can just extend SearchForm:

class ApiTestModelItem2SearchForm extends SearchForm
{
}
?>

Get Custom Model

$authenticationData = login('super','super');
//Add code to check if user is logged successfully

$id = 1; // Change this with value of model id

$headers = array(
    'Accept: application/json',
    'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'],
    'ZURMO_TOKEN: ' . $authenticationData['token'],
    'ZURMO_API_REQUEST_TYPE: REST',
);
$response = ApiRestHelper::createApiCall('http://zurmo_url/index.php/api/sampleModel/api/customGet/?id=' . $id, 'GET', $headers);
// Decode json data
$response = json_decode($response, true);
if ($response['status'] == 'SUCCESS')
{
    $model = $response['data'];
    //Do something with model
}
else
{
    // Error, for example if we provided invalid model id
    $errors = $response['errors'];
    // Do something with errors
}

Delete Custom Model

$id = 1; // Change this value to model id that you want to delete
$authenticationData = login('super','super');
//Add code to check if user is logged successfully

$headers = array(
    'Accept: application/json',
    'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'],
    'ZURMO_TOKEN: ' . $authenticationData['token'],
    'ZURMO_API_REQUEST_TYPE: REST',
);
$response = ApiRestHelper::createApiCall('http://zurmo_url/index.php/api/sampleModel/api/customDelete/?id=' . $testModels[0]->id, 'DELETE', $headers);
$response = json_decode($response, true);
if ($response['status'] == 'SUCCESS')
{
    // Inform user that model is deleted
}
else
{
    // Error, for example if we provided invalid model id
    $errors = $response['errors'];
    // Do something with errors
}

Create New Custom Model

$authenticationData = login('super','super');
//Add code to check if user is logged successfully

$headers = array(
    'Accept: application/json',
    'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'],
    'ZURMO_TOKEN: ' . $authenticationData['token'],
    'ZURMO_API_REQUEST_TYPE: REST',
);

// Add below elements depending on custom model
$data = Array
(
    'name' => 'Some name',
);

$response = ApiRestHelper::createApiCall('http://zurmo_url/index.php/api/sampleModel/api/customPost/', 'POST', $headers, array('data' => $data));
$response = json_decode($response, true);

if ($response['status'] == 'SUCCESS')
{
    $account = $response['data'];
    //Do something with model data
}
else
{
    // Error
    $errors = $response['errors'];
    // Do something with errors, show them to user
}

Update Existing Custom Model

$id = 1; // Change this value to model id that you want to change
$authenticationData = login('super','super');
//Add code to check if user is logged successfully

$headers = array(
    'Accept: application/json',
    'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'],
    'ZURMO_TOKEN: ' . $authenticationData['token'],
    'ZURMO_API_REQUEST_TYPE: REST',
);
// Change note description
$data['name']    = "Updated model name";

$response = ApiRestHelper::createApiCall('http://zurmo_url/index.php/api/sampleModel/api/customUpdate/?id=' . $id, 'PUT', $headers, array('data' => $data));
$response = json_decode($response, true);
if ($response['status'] == 'SUCCESS')
{
    $account = $response['data'];
    //Do something with model data
}
else
{
    // Error, for example if we provided invalid model id
    $errors = $response['errors'];
    // Do something with errors
}

List Custom Models

$authenticationData = login('super','super');
//Add code to check if user is logged successfully

$headers = array(
    'Accept: application/json',
    'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'],
    'ZURMO_TOKEN: ' . $authenticationData['token'],
    'ZURMO_API_REQUEST_TYPE: REST',
);
$response = ApiRestHelper::createApiCall('http://zurmo_url/index.php/api/sampleModel/api/customList/', 'GET', $headers);
$response = json_decode($response, true);
if ($response['status'] == 'SUCCESS')
{
    // Do something with results
    if ($response['data']['totalCount'] > 0)
    {
        foreach ($response['data']['items'] as $item)
        {
        // Print models
        }
    }
    else
    {
     // There are no models
    }
}
else
{
    $errors = $response['errors'];
    // Do something with errors
}

Finally, you will need to add a route into the perInstance.php file (replace ‘module_name’ with the name of the module that the API controller and model belong to):

$instanceConfig['components']['urlManager']['rules'] = array(
    array('module_name/<model>Api/<action>', 'pattern' => 'module_name/<model:\w+>/api/<action>/*'),
)

List Attributes Of Custom Models

Replace %sessionId% and %token% with ‘sessionId’ and ‘token’ variables returned by authentication process.

  • Description: List attributes of custom model.
  • URL structure: http://zurmo_url/index.php/api/sampleModel/api/listAttributes
  • Method: GET
  • HTTP header parameters:
    Accept: application/json
    ZURMO_API_REQUEST_TYPE: REST
    ZURMO_SESSION_ID: %sessionId%
    ZURMO_TOKEN: %token%
  • Parameters: None
  • PHP sample
    $authenticationData = login('super','super');
    //Add code to check if user is logged successfully
    
    $headers = array(
        'Accept: application/json',
        'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'],
        'ZURMO_TOKEN: ' . $authenticationData['token'],
        'ZURMO_API_REQUEST_TYPE: REST',
    );
    $response = ApiRestHelper::createApiCall('http://zurmo_url/index.php/api/sampleModel/api/listAttributes', 'GET', $headers);
    // Decode json data
    $response = json_decode($response, true);
    if ($response['status'] == 'SUCCESS')
    {
        $sampleModelAttributesAttributes = $response['data'];
        //Do something with attributes
    }
    else
    {
        // Error
        $errors = $response['errors'];
        // Do something with errors
    }
    
  • Return:
    Data contains custom model attributes info.

Leave a Comment

  • Haqeem Luqman

    [HELP]

    Sir i want call Oppurtunity files into project sir, i didnt know where i have to put the code sir, im a beginner sir. Thanks

    • Haqeem Luqman

      let me explain the flow is. the first is when we create an oppurtunity, the the general manager will decided to accept or ignore the oppurtunity, then if general manager accepted that oppurtunity will deleted on Opportunity LIst, then will be moved into Project List, what should i do first to calling the opprtunity API in project model sir ?

    • Haqeem Luqman

      Sir ????????????????? :’(

  • Haqeem Luqman

    where i have to put the code of Get Custom Model, Create Custom Model, etc sir ???