Using SugarCRM’s New RESTful API With Guzzle

Today I saw a post from Mr. John Mertic that described how to interact with the new API via cURL. While it’s a great piece of information, I find working with the Guzzle library to be much more efficient due to Guzzle’s support for event listeners. That and I hate working directly with cURL.

That said, lets get down to business and start working with the new API.

First, lets update composer.json to install Guzzle

{
    "require": {
        "guzzle/guzzle": "~3.1.1"
    }
}

Next, install the library via composer

$ composer install

Now with Guzzle auto loaded we can start to have our fun with the new API.

<?php
use Guzzle\Common\Event;
use Guzzle\Http\Client;

// specify the REST web service to interact with
$url = 'http://sugarinstance/rest/v10';

// And admin username/password
$username = 'username';
$password = 'password';

$client = new Client($url);

//Authenticate and retrieve an OAuth2 Token
$request = $client->post('oauth2/token', null, array(
  'grant_type' => 'password',
  'client_id' => 'sugar',
  'username' => $username,
  'password' => $password,
));

$results = $request->send()->json();

$token = $results['access_token'];

//Register an Event Listener to automatically include 
//the OAuth2 token on all requests to the REST web service
$client->getEventDispatcher()->addListener(
  'request.before_send', function(Event $event) {
    $event['request']->setHeader('OAuth-Token', $token);
  }
);

//Retrieve all documents related to the specified account
$request = $client->get('/Accounts/' . $account_id . '/link/documents');
$result = $request->send()->json();

var_dump($result);

As you can see, using Guzzle makes interacting with the new API a breeze and has an added bonus of making the code much easier to understand.

Stay tuned, on my next post I’ll show how you can use the SugarCRM 7 API Wrapper Class to accomplish the same task in just a few lines of code.

This entry was posted in Uncategorized. Bookmark the permalink.

4 thoughts on “Using SugarCRM’s New RESTful API With Guzzle

      • Sean,
        That’s a nifty info! thanks :)
        Please can you tell if the Guzzle client is compatible with the bundled RESTful api bundled in version 6.6 & 6.7 in SugarCRM? For instance, I am using RESTful api v4_1 (4.1) in my SugarCRM instance… can I use the Guzzle client there?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current day month ye@r *