Anda di halaman 1dari 7

Being RESTful with SugarCRM

1 de 7

http://www.ibm.com/developerworks/library/x-sugarcrmrest/#l3

IBM Bluemix Develop in the cloud at the click of a button!

developerWorks

Technical topics

XML

Technical library

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 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?
REST, which stands for REpresentational State Transfer, is designed to be a

Develop and deploy your


next
app on the IBM Bluemix
cloud platform.

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

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

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

06/08/2015 20:03

Being RESTful with SugarCRM

2 de 7

http://www.ibm.com/developerworks/library/x-sugarcrmrest/#l3

(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.

06/08/2015 20:03

Being RESTful with SugarCRM

3 de 7

http://www.ibm.com/developerworks/library/x-sugarcrmrest/#l3

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'),

06/08/2015 20:03

Being RESTful with SugarCRM

4 de 7

http://www.ibm.com/developerworks/library/x-sugarcrmrest/#l3

),
);
$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);

06/08/2015 20:03

Being RESTful with SugarCRM

5 de 7

http://www.ibm.com/developerworks/library/x-sugarcrmrest/#l3

// 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),
);

06/08/2015 20:03

Being RESTful with SugarCRM

6 de 7

http://www.ibm.com/developerworks/library/x-sugarcrmrest/#l3

$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
Description

Name

Size

Article examples

rest.php.samples.zip

5KB

Resources
Learn
Sugar Developer Documentation: Check out the detailed guides to the various
SugarCRM APIs.

Dig deeper into XML on


developerWorks
Overview
New to XML
Technical library (tutorials and more)

The Sugar Developer Zone: Find content for all SugarCRM developers.

Forums

The Definitive Guide to SugarCRM: Better Business Applications: Explore an

Downloads and products

excellent guide to developing application based upon SugarCRM.

Open source projects

Connect your data to the outside world with SugarCRM connectors: Build a

Standards

Google News connector using the Google AJAX Search API (John Mertic,
developerWorks, February 2010): Build an example connector with the

Events

connectors framework in Sugar 5.2. The sample connector allows users to


see recent Google News items about companies in their SugarCRM instance.
Build a RESTful Web service (Andrew Glover, developerWorks, July 2008): In
this tutorial, walk step-by-step through the fundamental concepts of REST
and building applications with Restlets.
Learning PHP series: Learn to program with PHP with these tutorials on

Bluemix Developers
Community
Get samples, articles, product
docs, and community resources
to help build, deploy, and manage
your cloud apps.

developerWorks Weekly
Newsletter

06/08/2015 20:03

Being RESTful with SugarCRM

7 de 7

http://www.ibm.com/developerworks/library/x-sugarcrmrest/#l3

developerWorks.
PHP.net: Find PHP documentation and put this general-purpose scripting
language to work in your Web development and HTML.
the Recommended PHP reading list: Check out this PHP reading list compiled
for programmers and administrators by IBM Web application developers.
PHP content: Browse PHP-related articles, tutorials, and more on
developerWorks.
PHP project resources IBM developerWorks: Expand your PHP skills.

Keep up with the best and latest


technical info to help you tackle
your development challenges.

DevOps Services
Software development in the
cloud. Register today to create a
project.

IBM evaluation software


Evaluate IBM software and
solutions, and transform
challenges into opportunities.

XML 1.0 Specification (W3C Recommendation, 26 November 2008): Check


out this source for specific details about XML features such as the CDATA
section.
The XML FAQ: Explore another excellent source of XML information, the XML
FAQ edited by Peter Flynn.
XML DOM tutorial from W3schools.com: Find out what XML-based interfaces
are available to the browser (and which browsers support them).
XHTML 1.0: The Extensible HyperText Markup Language (World Wide Web
Consortium Recommendation, 26 January 2000): Read more about XHTML
1.0, a reformulation of HTML 4 as an XML 1.0 application and provides the
foundation for future extensibility of XHTML.
XML area on developerWorks: Get the resources you need to advance your
skills in the XML arena.
The developerWorks Open source zone: Find extensive how-to information,
tools, and project updates to help you develop with open source technologies
and use them with IBM's products.
IBM XML certification: Find out how you can become an IBM-Certified
Developer in XML and related technologies.
XML technical library: See the developerWorks XML Zone for a wide range of
technical articles and tips, tutorials, standards, and IBM Redbooks.
developerWorks technical events and webcasts: Stay current with technology
in these sessions.
developerWorks podcasts: Listen to interesting interviews and discussions for
software developers.
Get products and technologies
IBM product evaluation versions: Download or explore the online trials in the
IBM SOA Sandbox and get your hands on application development tools and
middleware products from DB2, Lotus, Rational, Tivoli, and
WebSphere.
Discuss
XML zone discussion forums: Participate in any of several XML-related
discussions.
developerWorks blogs: Check out these blogs and get involved.

06/08/2015 20:03