Being RESTful with SugarCRM

Tap into the new REST support with the SugarCRM Web services API

SugarCRM is the world's leading open source Customer Relationship Management (CRM) software provider, with over 5,000 customers and 500,000 downloads of the SugarCRM application all around the world. In December 2009, SugarCRM released version 5.5 of the application suite, which completely revitalized the Web Services platform. The changes include a faster, easier-to-use API, the ability to easily extend the API that is presented to a Web service client, and the addition of REST support. In this article, you'll take a look at what REST is and how to use the REST support in the Web Services API to interact with a SugarCRM instance.

Share:

John Mertic, Software Engineer, SugarCRM

Photo of John MerticJohn Mertic is a software engineer at SugarCRM, and has several years of experience with PHP Web applications. At SugarCRM, he has specialized in data integration, mobile and user interface architecture. An avid writer, he has been published in php|architect, IBM developerWorks, and in the Apple Developer Connector, and is the author of the book 'The Definitive Guide to SugarCRM: Better Business Applications'. He has also contributed to many open source projects, most notably the PHP project where he is the creator and maintainer of the PHP Windows Installer. He can be reached at jmertic@gmail.com.



02 February 2010 (First published 12 January 2010)

Also available in Chinese Russian Japanese Portuguese

02 Feb 2010 - Added Resource item for 02 Feb 2010 article about SugarCRM connectors by the author.

What is REST?

Frequently used acronyms

  • API: Application programming interface
  • CSS: Cascading stylesheets
  • DOM: Document Object Model
  • HTML: Hypertext Markup Language
  • HTTP: Hypertext Transfer Protocol
  • JSON: JavaScript Object Notation
  • REST: Representational State Transfer
  • RPC: Remote procedure call
  • URL: Uniform Resource Locator
  • XML: Extensible Markup Language

REST, which stands for REpresentational State Transfer, is designed to be a very mean, lean Web services protocol. It came into being as a response to heavyweight Web services protocols such as SOAP and XML-RPC, which rely on a predefined messaging format and methods to pass them back and forth between servers and clients. REST, on the other hand, specifies no such limitations; you can use any message format that you like (whether it be JSON, XML, HTML, serialized data, or even straight text), and operates on the standard HTTP verbs of GET, DELETE, and POST for its operations. The rules that exist for REST client/server interactions can be completely defined by the application requirements. So if you define a REST interface that is intended to be consumed by a JavaScript client, you probably want to have the data returned in a JSON format, while if you intend for the data to be consumed by a PHP client, then perhaps serialized data or XML is a better choice.

Each REST Web services call is just a simple HTTP request, using one of the standard HTTP verbs. Typically, you'll use the verb most appropriate for the action you are performing:

  • GET to retrieve data from a server
  • POST to send data from a server
  • DELETE to delete a resource on a server

Listing 1 shows how an example interaction with the Yahoo! search REST Web service with PHP works (see Downloads to have all of the examples in this article at your fingertips).

Listing 1. Example of interacting with a REST Web service in PHP
<?php 
// specify the REST web service to interact with 
$url = 'http://search.yahooapis.com/WebSearchService/V1/
     webSearch?appid=YahooDemo&query=sugarcrm'; 
// make the web services call; the results are returned in XML format 
$resultsXml = file_get_contents($url); 
// convert XML to a SimpleXML object 
$xmlObject = simplexml_load_string($resultsXml); 
// iterate over the object to get the title of each search result 
foreach ( $xmlObject->Result as $result ) 
    echo "{$result->Title}\n";

For this example in Listing 1, you are doing a search for sugarcrm using the Yahoo Web Search Service. You use the PHP function file_get_contents(), which performs a GET request using the URL specified. By default it returns the results of the query as an XML string, and the PHP SimpleXML library is used to parse it into a PHP object you can iterate over to get the desired data you are looking for.

Now that you understand how REST Web services work, see how you can interact with SugarCRM using their Web services interface.


Connecting to SugarCRM using REST

SugarCRM comes with the Web services interface ready to go out of the box, located at http://path_to_Sugar_instance/v2/rest.php. Calls are made using POST requests to this URL, passing the needed arguments to the Web services call as POST parameters. For each interaction with the Web service, the client first must authenticate with the service using the login method call, as in Listing 2.

Listing 2. Login to the SugarCRM instance through REST Web services interface
<?php 
// specify the REST web service to interact with 
$url = 'http://localhost/sugar/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_name' => 'user', 
    'password' => 'password', 
    ); 
$json = json_encode($parameters); 
$postArgs = '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($session); 
// Close the connection 
curl_close($session);  
// Convert the result from JSON format to a PHP array 
$result = json_decode($response); 
// Echo out the session id 
echo $result['id'];

Since you need to make a POST request to the Web service instead of a GET request, use the PHP curl library instead of file_get_contents() to make the call to the Sugar Web service. You then assemble the parameters for the Web services call as an array, which you encode as a JSON string. You specify the parameters for this Web service call, the method (which is login for this call), and the format you are using to pass the parameters to the service using the input_type POST parameter (which can be one of json or serialized). You also must specify the format you expect the results to be returned as for the response_type parameter (which can be one of json, rss, or serialized), and then specify the JSON encoded parameters string for the Web service method as rest_data. You then make the actual call, and decode the returned JSON string passed from the server. The main return value you are concerned with for this request is the id parameter, which is used as a parameter in subsequent requests to identify to the server that you have already authenticated to the service.


Creating a new record

You can now build upon the example from Listing 2 to actually make changes on the Sugar Web service. In Listing 3, you'll see how you can add a new record to the Accounts module using the interface.

Listing 3. Adding a new Account using the REST Web services interface
<?php 
// specify the REST web service to interact with 
$url = 'http://localhost/sugar/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_name' => 'user', 
    'password' => 'password', 
    ); 
$json = json_encode($parameters); 
$postArgs = '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($session); 
// Close the connection 
curl_close($session);  
// Convert the result from JSON format to a PHP array 
$result = json_decode($response); 
// Get the session id 
$sessionId = $result['id']; 
// Now, let's add a new Accounts record 
$parameters = array( 
    'session' => $session, 
    'module' => 'Accounts', 
    'name_value_list' => array( 
        array('name' => 'name', 'value' => 'New Account'), 
        array('name' => 'description', 'value' => 'This is an 
account created from a REST web services call'), 
        ), 
    ); 
$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($session); 
// Convert the result from JSON format to a PHP array 
$result = json_decode($response); 
// Get the newly created record id
$recordId = $result['id'];

After logging into the Web service, you make a second Web services call, this time to the set_entry Web service method. You specify the session id that was returned by the login method as the session parameter, and the module you are adding the record into as the module parameter. The name_value_list parameter is a name/value pair list of the field values you wish to set for the newly created record. You then make the Web services call, which returns the record id of the newly created record.

You can also update a record by calling the same set_entry method once again, being sure to pass the record id you want to update in the name_value_pair list, as in Listing 4.

Listing 4. Create and update a Contact using the REST Web services interface
<?php 
// specify the REST web service to interact with 
$url = 'http://localhost/sugar/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_name' => 'user', 
    'password' => 'password', 
    ); 
$json = json_encode($parameters); 
$postArgs = '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($session); 
// Close the connection 
curl_close($session);  
// Convert the result from JSON format to a PHP array 
$result = json_decode($response); 
// Get the session id 
$sessionId = $result['id']; 
// Now, let's add a new Contacts record 
$parameters = array( 
    'session' => $session, 
    'module' => 'Contacts', 
    'name_value_list' => array( 
        array('name' => 'first_name', 'value' => 'John'), 
        array('name' => 'last_name', 'value' => 'Mertic'), 
        ), 
    ); 
$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($session); 
// Convert the result from JSON format to a PHP array 
$result = json_decode($response); 
// Get the newly created record id 
$recordId = $result['id']; 
// Now let's update that record we just created 
$parameters = array( 
    'session' => $session, 
    'module' => 'Contacts', 
    'name_value_list' => array( 
        array('name' => 'id', 'value' => $recordId), 
        array('name' => 'title', 'value' => 'Engineer'), 
        ), 
    ); 
$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($session); 
// Convert the result from JSON format to a PHP array 
$result = json_decode($response); 
// Get the record id of the record we just updated 
$recordId = $result['id'];

In this Listing 4 example, you just make a second set_entry method call to update the newly created record. This time you specify the record id of the record you want to update as an entry in the name_value_list parameter to the Web services method call, and have an entry for each field you are updating as a part of the call (for this example, you are updating the title field to the value Engineer). You then make the request, and look for the record id to be returned to you as a sign of a successful result of the Web service method call.


Creating multiple records

If you are creating multiple records in a module, you can reduce the number of calls to the Web services API down to one by using the Web services method set_entries, instead of calling set_entry in a loop. Listing 5 shows how this is done.

Listing 5. Creating multiple records in a module in one method call
<?php 
// specify the REST web service to interact with 
$url = 'http://localhost/sugar/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_name' => 'user', 
    'password' => 'password', 
    ); 
$json = json_encode($parameters); 
$postArgs = '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($session); 
// Close the connection 
curl_close($session);  
// Convert the result from JSON format to a PHP array 
$result = json_decode($response); 
// Get the session id 
$sessionId = $result['id']; 
// Now, let's add a new Contacts record 
$parameters = array( 
    'session' => $session, 
    'module' => 'Contacts', 
    'name_value_lists' =>  
        array( 
            array('name' => 'first_name', 'value' => 'John'), 
            array('name' => 'last_name', 'value' => 'Mertic'), 
        ), 
        array( 
            array('name' => 'first_name', 'value' => 'Dominic'), 
            array('name' => 'last_name', 'value' => 'Mertic'), 
        ), 
        array( 
            array('name' => 'first_name', 'value' => 'Mallory'), 
            array('name' => 'last_name', 'value' => 'Mertic'), 
        ), 
    ); 
$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($session); 
// Convert the result from JSON format to a PHP array 
$result = json_decode($response); 
// Get the newly created record ids as an array 
$recordIds = $result['ids'];

The parameters for set_entries are nearly the same as set_entry, except instead of name_value_list, the parameter is name_value_lists, which is an associative array of the records you create using the Web services API. The record ids of the created records are returned back in the ids parameter as an array, and they are given back in the order in which they are passed in the parameter list.


Relating records together

One major concept in SugarCRM is the ability to relate records to one another. One example of this relationship is between an Account and a Contact; each Account in SugarCRM can have one or more Contacts related to it. You can build this relationship entirely using the Web services framework, as in Listing 6.

Listing 6. Relate an Account to a Contact using the REST Web services API
<?php 
// specify the REST web service to interact with 
$url = 'http://localhost/sugar/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_name' => 'user', 
    'password' => 'password', 
    ); 
$json = json_encode($parameters); 
$postArgs = '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($session); 
// Close the connection 
curl_close($session);  
// Convert the result from JSON format to a PHP array 
$result = json_decode($response); 
// Get the session id 
$sessionId = $result['id']; 
// Now, let's add a new Accounts record 
$parameters = array( 
    'session' => $session, 
    'module' => 'Accounts', 
    'name_value_list' => array( 
        array('name' => 'name', 'value' => 'New Account'), 
        array('name' => 'description', 'value' => 'This is an 
account created from a REST web services call'), 
        ), 
    ); 
$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($session); 
// Convert the result from JSON format to a PHP array 
$result = json_decode($response); 
// Get the newly created Account record id 
$accountId = $result['id']; 
// Now, let's add a new Contacts record 
$parameters = array( 
    'session' => $session, 
    'module' => 'Contacts', 
    'name_value_list' => array( 
        array('name' => 'first_name', 'value' => 'John'), 
        array('name' => 'last_name', 'value' => 'Mertic'), 
        ), 
    ); 
$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($session); 
// Convert the result from JSON format to a PHP array 
$result = json_decode($response); 
// Get the newly created Contact record id 
$contactId = $result['id']; 
// Now let's relate the records together 
$parameters = array( 
    'session' => $session, 
    'module_id' => $accountId 
    'module_name' => 'Accounts', 
    'link_field_name' => 'contacts', 
    'related_ids' => array($contactId), 
    ); 
$json = json_encode($parameters); 
$postArgs = 'method=set_relationship&input_type=json&
    response_type=json&rest_data=' . $json; 
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs); 
// Make the REST call 
$response = curl_exec($session);

After creating the Account and Contact you wish to relate together, you build the request made to the set_relationship Web services method call. You then pass the following:

  • session parameter for the session ID of the Web services session
  • module_name for the main module of the relationship
  • module_id for the ID of the record in that module that will be the base of the relationship
  • link_field_name for the name of the relationship in that module used to link to the other module (in this case, that relationship is named contacts)

Finally, you then specify a list of record ids that will relate to the module record specified. After making the call, the relationship will be set.

This is just the tip of the iceberg of the Web services methods that are available; be sure to check out the SugarCRM Developer Documentation for a full list of available Web services methods.


Summary

In this article, you learned about a new feature in SugarCRM 5.5, which is a REST interface into the Sugar Web Services framework. After learning a bit about how REST Web services work, you looked at some examples that took advantage of the REST interface to the Sugar Web services framework. You saw how to add a new record to a module, and then how to modify that record. You also saw how to add multiple records in one method call, saving the overhead of making several remote server calls in a row. Lastly, you saw how to relate two different records together using the set_relationship method of the Web services framework.


Download

DescriptionNameSize
Article examplesrest.php.samples.zip5KB

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into XML on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML, Open source
ArticleID=460758
ArticleTitle=Being RESTful with SugarCRM
publish-date=02022010