SugarCRM SOAP API Examples

By popular request, here are some examples that worked for me when using the SOAP API offered by SugarCRM. Its nice that there is an interface, but it isn't brilliantly documented or nearly as widely used as it should be!

SugarCRM can't talk to PHP 5 native SOAP libraries in WSDL mode, so connect without it. Find below a series of queries that each worked for me, all just dumped here in succession, don't try to run this whole piece of code - it is intended as a series of examples. Use each line and then var_dump($response) to see what's happening.

// set up options array
$options = array(
        "location" => 'http://192.168.1.129/aeat/spm/crm/soap.php',
        "uri" => 'http://www.sugarcrm.com/sugarcrm',
        "trace" => 1
        );
// connect to soap server
$client = new SoapClient(NULL, $options);
 
// look what modules sugar exposes
$response = $client->get_available_modules($session_id);
 
// look in more detail at the fields in the Accounts module
$response = $client->get_module_fields($session_id, 'Accounts');
 
// look for a particular account name and then get its ID
$response = $client->get_entry_list($session_id, 'Accounts', 'name like "%LornaJane%"');
$account_id = $response->entry_list[0]->id;
 
// create a new account record and grab its ID
$response = $client->set_entry($session_id, 'Accounts', array(
            array("name" => 'name', "value" => 'New Company')
            ));
$account_id = $response->id;
 
// create a new contact record, assigned to this account, and grab the contact ID
$response = $client->set_entry($session_id, 'Contacts', array(
            array("name" => 'first_name',"value" => 'Geek'),
            array("name" => 'last_name',"value" => 'Smith'),
            array("name" => 'email1',"value" => 'a@b.com'),
            array("name" => 'account_id',"value" => $account_id)
            ));
$contact_id = $response->id;

I hope this helps - if you have anything to add, or would like to post some examples, please do :)

33 thoughts on “SugarCRM SOAP API Examples

  1. Since SugarCRM only works with PHP5 in non-WSDL mode, I had to create all my calls from scratch. The SugarCRM documentation is somewhat minimal, as I may have mentioned, and I found I was mostly reading the WSDL to figure out how to format my SOAP calls.

  2. Jeremy, thanks for dropping by - I will certainly be adding things as I find them. I don't work with sugarcrm all the time but when I do, I'll be posting :)

  3. Darcy: Next time I am working with sugarcrm and SOAP, I'll see what I can add to this. There is nothing like a working code example when you're just getting to grips with something, I know!

  4. Wow! Thank you for this sample. It's exactly what I've been looking for. It' a shame that Sugar doesn't have simple, clear examples like this.

  5. Josh: I'm very happy to hear these examples helped - once I'd managed to get mine working it seemed important to share! I know sugarcrm are doing more with their services though so watch for better things coming from them in the future

  6. I'm just commenting 'cause you told me to, not 'cause I'm brilliant or anything.

    You often have to fully qualify fields for Sugar SOAPiness to work, e.g.

    $query = " username_c like '%$keyword%' or first_name like '%$keyword%' "; //fails unhelpfully saying "Looks like we got no XML document.. "

    $query = " username_c like '%$keyword%' or `contacts`.first_name like '%$keyword%' "; //works!

  7. mwic: If only brilliant people were allowed to comment, it would be *much* quieter around here!! Thanks for adding your findings, hopefully they'll be helpful to the next person who comes here looking for info.

  8. your examples are great, and i've got my soap connection working remotely with my server here in house--that is, i get a response from my query, so i know it's making some connection to sugar, but i'm getting an invalid session ID error. it seems this is caused by not logging in or something... any thoughts? i didn't see an authentication example using regular soap... all of sugar's use nusoap... boo...

    thanks!

    • Hi Dean, came across this post last night and had your problem. I lazily copy/pasted the above code and dropped a var_dump in to inspect the results of the SOAP call. You need to log into sugar first before you can make these calls, and you can do so with:

      $session_id = $client->login(array(
      'user_name'=>'bob',
      'password'=>'password'
      ),__FILE__)->id;

      Then (assuming your credentials are correct) you have a $session_id to pass into other calls.

  9. I'm writing more examples for the community based off of what you have here.

    Check out
    http://deanhaddock.com/mercury/2009/04/10/sugarcrm-soap-examples/

  10. Ritesh: to consume a soap service, you will need a soap client of some kind. Until the new sugarcrm version is out with rest services, a browser can't talk to the services. Hope that helps

  11. If you get this error:
    Fatal error: Cannot use object of type stdClass as array
    when trying to read the result as an array, use this function.

    function objectToArray( $object )
    {
    if( !is_object( $object ) && !is_array( $object ) )
    {
    return $object;
    }
    if( is_object( $object ) )
    {
    $object = get_object_vars( $object );
    }
    return array_map( 'objectToArray', $object );
    }
    this will convert the object returned by soap api to an array.

  12. Great blog!

    I'm trying to update a custom value on an existing Account in sugar but without progress. This is what I try:

    set_entry($sess, 'Accounts', array(
    array("name" => 'id',"value" => $TheId),
    array("name" => 'customfield',"value" => $updatedvalue)
    ));

    Could you please help!

    Thank you!
    Mike

  13. Mike: do you get an error message or does the field just not update? I'm not sure if I've tried custom fields with the services; can you update a "normal" field?

    • Thanks for your answer!
      Yes I can update normal fields and one of my custom fields... Well, maybe it's better to take a look at the command retrieving the data first. It looks like this:

      $result = $this->proxy->get_entry_list(
      $this->sess,
      'Accounts',
      $query,
      $orderby,
      0,
      array(
      'openx_c',
      'customfield_c',
      'id',
      'name'
      ),
      $maxnum,
      false
      );

      I'm trying to retrieve two custom fields: customfield_c and openx_c. The mystery is that I can retrieve customfield_c, but not openx_c.

      Any ideas?
      Regards,
      Mike

  14. I don't know if this is still monitored, but I could really use some help - this stuff is driving me NUTS! I am not getting back any info and I know that there are 3 records that would match. Also, when I put in information - it's not entering the email address. Here's my code:

    require_once('inc/nusoap/nusoap.php');

    class SugarSoap{
    var $proxy;
    var $sess;

    function SugarSoap($soap_url,$login=true){
    $soapclient = new soapclient($soap_url,true);
    $this->proxy = $soapclient->getProxy();
    if($login) $this->login();
    }

    function login(){
    $params = array(
    'user_name' => 'uname',
    'password' => md5('password'),
    'version' => '.01'
    );
    $result = $this->proxy->login($params,'MyApp');
    $this->sess= $result['error']['number']==0 ? $result['id'] : null;
    return $this->sess;
    }
    function getContacts($query='',$maxnum=5,$orderby=' last_name asc'){

    $result = $this->proxy->get_entry_list(
    $this->sess,
    'Contacts',
    $query,
    "",
    0,
    array(
    'id',
    'first_name',
    'last_name',
    'email1'
    ),
    $maxnum,
    false
    );
    return $result;
    }
    function nameValuePairToSimpleArray($array){
    $my_array=array();
    while(list($name,$value)=each($array)){
    $my_array[$value['name']]=$value['value'];
    }
    return $my_array;
    }
    function setEntry($module,$array){
    $data_array=array();
    while(list($name,$value)=each($array)){
    $data_array[]= array(
    'name' => $name,
    'value' => $value );
    }
    $result = $this->proxy->set_entry(
    $this->sess,
    $module,
    $data_array );
    return $result;
    }
    function setContact($array){
    return $this->setEntry("Contacts",$array);
    }
    function createUser($email,$lname,$fname,$utype,$school,$leadsrc){
    return $this->setContact(array(
    "email1" => $email,
    "last_name" => $lname,
    "first_name" => $fname,
    "usertype_c" => $utype,
    "school_c" => $school,
    "lead_source" => $leadsrc ));
    }
    }

    $soap=new SugarSoap('http://agame.sugarondemand.com/soap.php?wsdl'); // we automatically log in

    $result=$soap->getContacts(' email1 like "%"',5," last_name desc");
    print_r($result);
    if($result['result_count']>0){
    foreach($result['entry_list'] as $record){
    $array= $soap->nameValuePairToSimpleArray($record['name_value_list']);
    echo $array['first_name'] . " " . $array['last_name'] . " - " . $array['email1']. "
    ";
    }
    } else {
    echo "No contacts found";
    }
    $result=$soap->createUser('email@gmail.com','Lastname','Firstname','Employer','Somewhere','Campaign');

  15. This is great! Sandi: thanks for your comment. Dean: thanks for your very helpful reply! I don't have any specific advice other than if one field doesn't save, double- and triple-check your field names for that field. For the missing records, start will a full list and add criteria one at a time, until you see which one causes your records to disappear. Good luck :)

  16. Hello,

    Is the first time that i work with sugarCRM.. i need to register from a form 2 fields directly into sugarcrm.. this is my php code ..

    'http://URL/sugarcrm/soap.php',
    "uri" => 'http://www.sugarcrm.com/sugarcrm',
    "trace" => 1
    );

    //user authentication array
    $user_auth = array(
    "user_name" => 'user',
    "password" => MD5('pass'),
    "version" => '.01'
    );

    // connect to soap server
    $client = new SoapClient(NULL, $options);

    // Login to SugarCRM
    $response = $client->login($user_auth,'test');

    $session_id = $response->id;

    $user_id = $client->get_user_id($session_id);

    $response = $client->set_entry($session_id, 'Targets', array(
    array("name" => 'last_name',"value" => '$_POST[nome]'),
    array("name" => 'email1',"value" => '$_POST[email]'),
    array("name" => 'assigned_user_id',"value" => $user_id)
    ));

    var_dump($response);

    ?>
    After clicking SUBMIT, i receive an error "INTERNAL SERVER ERROR". My sugarCRM is on a virtual machine (bitnami/ ubuntu 10.10).

    Best regards,

    Cosmin

  17. I have been developing a library to interact with the "REST" API:

    https://github.com/academe/sugarrestapi

    The documentation needs a tidy-up, and bits need completing, but it works and is in operation on a number of sites. I kind of do a bit more on it for each project. With this library you basically log in, which gives you a login session key. You can retain this session key between pages or users to avoid logging in for every page load.

    Once logged in, there are objects for dealing with Entries and EntryLists. The EntryLists support paging, and can pull in data from relationships. Hopefully it will be useful to someone, but please ask if it dos not make sense or you cannot see how to achieve a particular task. Anything that helps me decide what to put into the documentation can only help :-)

    -- Jason

  18. Hi !
    Thanks a lot for this, LORNAJANE !
    I'm completely new in SugarCRM. At the moment I'm trying to populate dropdowns through my web services.
    I can already fill those values, but when I want to show that value in listview or put it in a pdf, instead of the value it only shows the position of the array and not the value.
    Can you help me? I really appreciate if you can, because I'm trying to solve this problem a few days ago and can not find the solution.
    I'm customizing a community edition.
    Thanks in advance,

    Marta

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

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>