Friday, 15 February 2013

REST api Example



At times developers find it so difficult to find simple and running example of REST API to perform CRUD operations on SugarCRM.. There are plenty of tutorials, blogs, developer guides explaining same thing. Still for an ease for ourselves and to the hunters of same, writing the same thing all over again. 

REST Example

This blog post explains how to login to SugarCRM instance with admin user.


<?php

// specify the REST web service to interact with

$url = '<SITE_URL_OF_SUGAR>/service/v2/rest.php';

// Open a curl session for making the call
$curl = curl_init($url);

// Tell curl to use HTTP POST

curl_setopt($curl, CURLOPT_POST, true);

// Tell curl not to return headers, but do return the response

curl_setopt($curl, CURLOPT_HEADER, false);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);



// Set the POST arguments to pass to the Sugar server

$parameters = array(

    'user_auth' => array(

        'user_name' => 'admin',

        'password' => md5('<ADMIN_PASSWORD>'),

        ),

    );

$json = json_encode($parameters);
$postArgs = array(
    'method' => 'login',
    'input_type' => 'JSON',
    'response_type' => 'JSON',
    'rest_data' => $json,
    );
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);

// Make the REST call, returning the result
$response = curl_exec($curl);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
if ( !is_object($result) ) {
    die("Error handling result.\n");
}
if ( !isset($result->id) ) {
    die("Error: {$result->name} - {$result->description}\n.");
}
// Echo out the session id
echo $result->id."<br />";

$session = $result->id;

Create a new record in Lead module
 As we have session id, we are logged-in!, we will use that session id to create a new record.
Here we used set_entry method for that we need three parameters

1) session : pass current session id
2) module : module name to create a record
3) name_value_list : name value list combination

Let's see that in below code snippets


$parameters = array(
    'session' => $session, //Session ID
    'module' => 'Leads',  //Module name
    'name_value_list' => array (
            array('name' => 'first_name', 'value' => 'David'),
            array('name' => 'last_name', 'value' => 'Boris'),
            array('name' => 'status', 'value' => 'New'),
            array('name' => 'lead_source', 'value' => 'Web Site')
        ),
    );
$json = json_encode($parameters);
$postArgs = 'method=set_entry&input_type=JSON&response_type=JSON&rest_data=' . $json;

curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);

// Make the REST call, returning the result
$response = curl_exec($curl);


// Convert the result from JSON format to a PHP array
$result = json_decode($response,true);

// Get the newly created record id
$recordId = $result['id'];


print "New Record Created with ID ".$recordId;



Read detail of top 5 leads having work phone, as an example.


// Let us fetch detail of a Lead

$fields_array = array('first_name','last_name','phone_work');

$parameters = array(

    'session' => $
session,                                 //Session ID
    'module_name' => 'Leads',                             //Module name
    'query' => " leads.phone_work IS NOT NULL ",   //Where condition without "where" keyword
    'order_by' => " leads.last_name ",                 //$order_by
    'offset'  => 0,                                               //offset
    'select_fields' => $fields_array,                      //select_fields
    'link_name_to_fields_array' => array(array()),//optional
    'max_results' => 5,                                        //max results                 
    'deleted' => 'false',                                        //deleted
);

$json = json_encode($parameters);

$postArgs = array(
    'method' => 'get_entry_list',
    'input_type' => 'JSON',
    'response_type' => 'JSON',
    'rest_data' => $json,
    );

curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);

$response = curl_exec($curl);

// Convert the result from JSON format to a PHP array

$result = json_decode($response);


print "<pre>";
print_r($result);
die;

Update a lead status "New" to "Assigned" for lead which we have just created. We can use set_entry method with specified record id to update a value.


$recordId = "<Your 36 character record id>";

$parameters = array(
    'session' => $session,
    'module' => 'Leads',
    'name_value_list' => array(
            array('name' => 'id', 'value' => $recordId),  //Record id to update
            array('name' => 'status', 'value' => 'Assigned'),
        ),
    );
$json = json_encode($parameters);
$postArgs = 'method=set_entry&input_type=JSON&response_type=JSON&rest_data=' . $json;

curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);

// Make the REST call, returning the result
$response = curl_exec($curl);
// Convert the result from JSON format to a PHP array
$result = json_decode($response,true);

// Get the newly created record id
$recordId = $result['id'];
print "Record Updated, Updated id ".$recordId;

Delete a record via web-service.  It is as simple as we update record with id. Here we need to provide id and deleted equal 1.


$recordId = "<Your 36 character record id>";

$parameters = array(
    'session' => $session,
    'module' => 'Leads',
    'name_value_list' => array(
            array('name' => 'id', 'value' => $recordId),
            array('name' => 'deleted', 'value' => '1')        //Deleted flag
        ),
    );
$json = json_encode($parameters);
$postArgs = 'method=set_entry&input_type=JSON&response_type=JSON&rest_data=' . $json;

curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);

// Make the REST call, returning the result
$response = curl_exec($curl);
// Convert the result from JSON format to a PHP array
$result = json_decode($response,true);

// Get the newly created record id
$recordId = $result['id'];

print "Record Deleted!, Deleted record id is ".$recordId;

6 comments:

  1. Thank you for your insightful example. I have followed your tutorial and it works pefectly. But i have a tiny question: when Read detail of top 5 leads, i want to show only information of lead (first_name, last_name, work_phone) not the whole array, how to do that?

    ReplyDelete
  2. It should already show you only those 3 fields, as we have given select fields in request by,

    $fields_array = array('first_name','last_name','phone_work');

    ReplyDelete
  3. Hi Urdhva Tech, i see, but this is what i get:
    stdClass Object
    (
    ....
    [entry_list] => Array
    (
    [0] => stdClass Object
    (
    [id] => 492eddc6-d79a-6791-46c9-50d929e03b62
    [module_name] => Leads
    [name_value_list] => stdClass Object
    (
    [first_name] => stdClass Object
    (
    [name] => first_name
    [value] => Olivia
    )

    [last_name] => stdClass Object
    (
    [name] => last_name
    [value] => Amey
    )

    [phone_work] => stdClass Object
    (
    [name] => phone_work
    [value] => (834) 802-2910
    )

    )

    )

    [1] => stdClass Object
    (
    [id] => b41ed553-7d1c-16f6-34f1-50d9296c74d0
    [module_name] => Leads
    [name_value_list] => stdClass Object
    (
    [first_name] => stdClass Object
    (
    [name] => first_name
    [value] => Lenora
    )

    [last_name] => stdClass Object
    (
    [name] => last_name
    [value] => Archer
    )

    [phone_work] => stdClass Object
    (
    [name] => phone_work
    [value] => (716) 892-0264
    )

    )

    )

    [2] => stdClass Object
    (
    [id] => 5fbf0333-34cc-e0b8-5f94-50d929eb3c6a
    [module_name] => Leads
    [name_value_list] => stdClass Object
    (
    [first_name] => stdClass Object
    (
    [name] => first_name
    [value] => Lorraine
    )

    [last_name] => stdClass Object
    (
    [name] => last_name
    [value] => Arney
    )

    [phone_work] => stdClass Object
    (
    [name] => phone_work
    [value] => (130) 650-2756
    )

    )

    )


    ....
    )
    And i want it only shows a list of 'first_name','last_name','phone_work'. Can you help me.Thank you very much! :D

    ReplyDelete
  4. You need to create function to loop through your result set to create an array.

    ReplyDelete
    Replies
    1. no need to loop through. in php use the array_map function. I did not write this originally, it has been knocking around for some time:

      function objectToArray($d) {
      if (is_object($d)) {
      // Gets the properties of the given object
      // with get_object_vars function
      $d = get_object_vars($d);
      }

      if (is_array($d)) {
      /*
      * Return array converted to object
      * Using __FUNCTION__ (Magic constant)
      * for recursive call
      */
      return array_map(__FUNCTION__, $d);
      }
      else {
      // Return array
      return $d;
      }
      }

      Then the return data from "call()" gets converted like this:
      $result = call('set_relationship',$argments,$url);
      $fres=objectToArray($result);

      I use this all the time.

      Delete

Urdhva Tech Pvt. Ltd. Powered by Blogger.

Urdhva Tech

My photo
SugarCRM Consultants Contact us at contact@urdhva-tech.com Skype : urdhvatech

Search This Blog

Stay connected Socially

     

Total Pageviews

Popular Posts