Skip navigation
All Places > Developer > Blog > 2016 > October

Post originally written by mrussellsugarcrm.



Sugar REST PHP Client


A new open source library for working with Sugar 7's powerful REST API has just been published! You can view the library in our GitHub account here:


Full instructions for installation, usage, current included API Endpoints, and ways to contribute can all be found in the GitHub Wiki on the repository.


Who should use it?


The Sugar REST PHP Client was built initially to make working with Sugar instances easier for some of our internal tools. I wanted to provide a quick, easy, and object oriented, way to access Sugar 7's REST API that could be used by all PHP developers. Any developer who is developing PHP applications that integrate with Sugar 7 should be interested in using the new library. The simplified architecture takes away the hassle of setting up and managing Curl connections, and allows the developer to focus on what matters most, which is working with the data in their Sugar application.


How to use it?


The REST PHP Client is setup as a composer package, and can be easily added to your existing project by adding it to your required packages in your projects composer.json file.


Once it's installed via composer, you can access the Client in the SugarAPI\SDK namespace.


A quick example of how much easier to use this new library is, can be shown by reviewing the latest documentation on using the REST API to get a filtered list of records from a module in the Support Developer Guide, and comparing it to the following snippet of code that does the exact same API request.

$server = 'https://localhost/sugarcrm/rest/v10/';


$credentials = array(


    'username' => 'admin',


    'password' => 'asdf'




$SugarAPI = new \SugarAPI\SDK\SugarAPI($server, $credentials);




$requestData = array(


    "filter" => array(




        '$or' => array(




                //name starts with 'a'


                "name" => array(










                //name starts with 'b'


                "name" => array(














    "max_num" => 2,


    "offset" => 0,


    "fields" => "id",


    "order_by" => "date_entered",


    "favorites" => false,


    "my_items" => false,




$response = $SugarAPI->filterRecords('Accounts')






if ($response->getStatus()=='200'){


    $records = $response->getBody();






Each API Endpoint in the Sugar 7 REST API is defined by an Endpoint Class in the REST PHP Client library, which is then dynamically mapped to a method on the REST PHP Client Object. This dynamic method, generates the Endpoint Object, configures the Curl Request, and returns the Endpoint Object for manipulation, such as loading in data and finally executing the actual request.



Calling filterRecords() dynamic method, returns a


SugarAPI\SDK\Endpoint\POST\ModuleFilter Object




$SugarAPI = new \SugarAPI\SDK\SugarAPI($server, $credentials);




$FilterEndpoint = $SugarAPI->filterRecords();


These Endpoint Objects manage the Request and Response to the API, as well as manage the data sent to the API. As shown above the execute() method on the Endpoint Object takes the request data that is to be sent to the Sugar API, and submits the Request the server. In the Filter Record example above, the passed in data matches what is shown in the API Endpoints documentation, however this is not always the case. The Endpoint Classes allow for manipulation of the data before being added to the Request, which means that the REST PHP Client can shorten the needed payload to allow integrated systems to quickly build requests.


One such example of this is the Bulk API Endpoint Object included in the REST PHP Client. As the documentation shows, the API request payload can be quite complicated, so to simplify it, it seemed intuitive to make the execute() method on the Bulk Endpoint Class, accept an array of REST PHP Client Endpoints objects, as they contain all the data needed for the Bulk request, saving the developer time by not having to build out the complex payload manually.

$SugarAPI = new \SugarAPI\SDK\SugarAPI($server,$creds);




$Accounts = $SugarAPI->filterRecords('Accounts')


                     ->setData(array('max_num'=> 5));


$Contacts = $SugarAPI->filterRecords('Contacts')


                     ->setData(array('max_num'=> 1));


$Notes = $SugarAPI->filterRecords('Notes')


                  ->setData(array('max_num'=> 3));


$Leads = $SugarAPI->filterRecords('Leads')


                  ->setData(array('max_num'=> 2));


$BulkCall = $SugarAPI->bulk()->execute(array(












$response = $BulkCall->getResponse();


if ($response->getStatus()==‘200’){






As of right now, not all Endpoints have been added to the REST PHP Client library, however the major Endpoints used for manipulating data have been added, and more will be added in continued releases. Check out the current Endpoints that can be used here which also includes a short code snippet showcasing how to use each one.


What's Next?


I would love to see more PHP developers using the library, which is why it is being released as an Open Source community project. Any issues that are found can be added to the GitHub repository under the Issues tab. Likewise, if you have features you would like added you can add them to the Issues tab on the repository as well. More detailed contribution guidelines can be found in the CONTRIBUTING doc, and in the Wiki.

This post originally appeared on the SynoLab blog hosted by Synolia, an Elite SugarCRM Partner. This post describes how to extend the new Sugar CLI framework to add commands that allow Sugar Administrators to monitor the Sugar e-mail queue.


Since the Sugar version, SugarCRM introduced a Sugar CLI tool based on Symfony Console. This Sugar CLI tool is under beta version at this moment (August 2016) and can be changed in the future.


We will see in this article how to use this new Sugar CLI to add a command which provides some statistics from the Email Manager Queue. We want to display how many emails by campaign by module are waiting to be sent.


The first step is to define the Command itself


To perform this operation we implementSugarcrm\Sugarcrm\Console\CommandRegistry\Mode\InstanceModeInterface because our command must be executed only on an installed Sugar instance. The only required things to do is to provide the command name, the description, and the help text on the configure() method and then to implement our logic in the execute() method. We are using a SugarQuery to retrieve the data and display the result on a table. We can imagine externalizing this part and using it in an API and creating unit tests.

//File: custom/Synolia/EmailMan/Console/Command/ListQueueCommand.phpnamespace Synolia\EmailMan\Console\Command;use Sugarcrm\Sugarcrm\Console\CommandRegistry\Mode\InstanceModeInterface;use Symfony\Component\Console\Command\Command;use Symfony\Component\Console\Input\InputInterface;use Symfony\Component\Console\Output\OutputInterface;use Symfony\Component\Console\Helper\Table;use Symfony\Component\Console\Helper\TableSeparator;/**




* Email Manager Queue statistics





class ListQueueCommand extends Command implements InstanceModeInterface






     * {inheritdoc}




    protected function configure()








            ->setDescription('Show Email Manager Queue statistics')


            ->setHelp('This command displays statistics from Email Manager Queue.')








     * {inheritdoc}




    protected function execute(InputInterface $input, OutputInterface $output)




        $result = $this->getSugarQuery()->execute();


        $nbEmailsToSent = 0;


        $table = new Table($output);


        $table->setHeaders(array('Campaign', 'Module', 'Count'));


        foreach ($result as $row) {


            $table->addRow(array($row['name'], $row['related_type'], $row['record_count']));


            $nbEmailsToSent += $row['record_count'];




        $table->addRow(new TableSeparator());


        $table->addRow(array('# Emails to send', '', $nbEmailsToSent));








     * @return \SugarQuery


     * @throws \SugarQueryException




    protected function getSugarQuery()




        $sq = new \SugarQuery();




            ->joinTable('campaigns', array(


                    'alias' => 'campaigns',


                    'joinType' => 'LEFT',


                    'linkingTable' => true)


            )->on()->equalsField('', 'emailman.campaign_id');


        $sq->select(array('', 'emailman.related_type'))->setCountQuery();






        return $sq;






Declare the Command


Now we need to make this command available by using the application/Ext/Console framework:

//File: custom/Extension/application/Ext/Console/SynoliaEmailManListQueueCommand.phpSugarcrm\Sugarcrm\Console\CommandRegistry\CommandRegistry::getInstance()->addCommand(new Synolia\EmailMan\Console\Command\ListQueueCommand());


Add our namespace


To use our own namespace we can follow one of the way described in our previous article by using theapplication/Ext/Utils framework:

//File: custom/Extension/application/Ext/Utils/SynoliaEmailManConsoleCommandNamespace.phpSugarAutoLoader::addNamespace('Synolia\\EmailMan\\Console\\Command', 'custom/Synolia/EmailMan/Console/Command', 'psr4');


Perform a Quick Repair and Rebuild et voilà!


Thanks to Jelle Vink about his presentation of this new Sugar CLI tools at UnCon 2016!


You can find more information about Sugar CLI on the Sugar Developer Guide.

We are half way through the SugarCRM Solution Architect Webinar Series and we have had a great turn-out so far with over 400 people coming to our first 4 webinars. Even if you miss the live webinars, you can still go back and watch the recordings on your own time.


For more information on what you can expect, you should read our recent blog post on the webinar series.


Accessing the Recordings


Visit Sugar University's webinar library for all previous recordings. Recordings are posted usually one or two business days after the live event.


Webinars with recordings are as follows:


1. (Sep 6th) - Introduction to Solution Architecture for Sugar & CRM Project Fundamentals


2. (Sep 7th) - The Sugar Platform


3. (Sep 20th) - Design


4. (Sep 21st) - Integration


Upcoming Live Webinars


If you have not already, you can still register and join us for remainder of the live SugarCRM Solution Architect Webinar Series. It is completely free and a great training resource for anyone considering trying for their Sugar Solution Architect Professional certification.


5. (Oct 11th) - Sugar Implementation


· Implementing Sugar to satisfy customer requirements


· Applying the Sugar extension framework


· The Sugar development methodology


6. (Oct 12th) - Performance and Quality Assurance


· Testing methodologies for Sugar


· Optimizing Sugar deployments


7. (Oct 25th) - Deployment


· Components of a Sugar deployment


· Sugar deployment configurations


· Methods for migrating code changes from development through production


· Solution sizing based on customer requirements


8. (Oct 26th) - Security


· Handling common compliance policies


· Customizing the Sugar visibility model


· Using Sugar authentication