Web Services in Your Own Language: Part 5 – SugarCRM Python library

sugarcrmdevelopers —  June 20, 2011 — 10 Comments

Editor’s Note: This post comes from our summer intern tech writer, Ian Caton, who was a part of a Capstone class at my alma mater, Kent State University in Kent, OH. They were tasked with building a better API for the language of their choice to help make it easier for developers to interact with SugarCRM’s web services API. His team chose Python, and here he talks about the work they’ve done. You can grab the code from GitHub at https://github.com/sugarcrm/python_webservices_library.

Python Logo

What Is Python?

Python is a high-level programming language and operates on many different levels of programming paradigms, such as object-oriented, imperative and functional programming styles. There is a great emphasis on usability and readability when working with python, which helps to create an easier environment for the user and programmer to work with. A lot of the built in functionality in python makes it a very powerful language to use for web based programming. Some very well known examples of companies that use python are Google, NASA, Youtube and Reddit, which helps show that it is not only powerful but also effective as a web based language. So let’s get started, first go to http://www.python.org/download/ and download the 2.7.1 version of python for the platform of your choice. Follow the step by step instructions to install python onto your machine, but it should be fairly straightforward. There are also a vast number of free tutorials and books to teach you the basics of using python and understanding the basic functionalities that you will need to get you started working on using python with SugarCRM. In case you are feeling exceptionally lazy, here are a couple sources to help teach you Python:

  • A tutorial on learning Python
  • A free Python book
  • Another free Python book for game programming
  • Pygame uses python and is for game development
  • A youtube tutorial on learning python from Google

    Why Use This Python API With SugarCRM?

    Using this Python API with SugarCRM helps to alleviate a lot of the redundancies that you normally come across. For example, you may notice when looking through the source code that we have each function make a call to another function, sendrequest(). This is an example of something implemented into the Python version of sugar, to make it easier on the user. Normally, you must encode everything in a json format before passing it to the server, but the sendrequest function does this work for us. Just take a look at the send request function itself and you can see how redundant it becomes to add those 7 lines onto every function call. We have another function that helps to aid the user, which is the tonamevaluelist function. This is used when you are working with name value list, which you see in the get entry functions. When you are trying to get a specific lists of data fields, you would have to add “name” and “value” to each item, but this function does it for the user. The fromnamevaluelist function is useful in a similar manner as the tonamevaluelist function, but is useful in setting entries where the former is used for getting entries.  Both of these functions make it easier for the user and gives them the ability to make a more intuitive list. Also, Python has good unit testing functionality built into the language itself. Which allows us to integrate unit testing easily into the SugarCRM API without much hassle and we are able to test new functionality as it’s created.

    Getting Started

    Now that Python has been installed onto your machine, let’s get started using python with SugarCRM. First and foremost, let’s initialize a sugar object using python. The way that python achieves this is by defining a __init__ object (which you can see by looking at the source code from the link above). The self parameter is really just a pointer to itself, or the object created after the session is made, which is the session parameter in a normal sugar function call. However, take a look at the other parameters, hostname, username and password. Initially they are left blank as a precaution, but go ahead and set them to your login specific information. In my example I will set them to the following:

    user = "test"
    pass = "123"
    url  = "http://sugarinstance/service/v2/rest.php"

    And simply pass everything like this:

    session = sugarcrm.Sugarcrm(url, user, pass)

    You can also just input everything into the function call itself, like such:

    session = sugarcrm.Sugarcrm(url = "http://sugarinstance/service/v2/rest.php", username = "test", password = "123")

    Both function calls will give you the same result, it is simply up to the user which they prefer. Now to check to make sure you are logged in, you can type

    if session.connected = 1:
    print "Connection successful to "+url
    if session.id != 0:
    print "Login successful!"

    These statements are to insure that a connection has been achieved and the session id is valid. The output should look like the following, assuming everything was input correctly:

    Login example

    You can log out in the same way, just have sesssion make a call to the logout function. If the session id is 0 then the connection has ended successfully.


    Now let’s discuss how you manipulate modules using Python. First, call the get_available_modules function to get a list of the modules on your database. To make the call to this function, take our session object and store the value in a new object. Something similar to this:

    modules = session.get_available_modules()

    Use the modules value to print a list of all of the modules on your database. Take one of those values and place it into the get_module_fields function. This function has two variable fields, a module field and a specific fields array parameter. You can leave the fields parameter blank, and just use the module parameter to see exactly what fields exist in the given module. However, it will most likely be a wall of text, so you will need to use the fields parameter to get specific information. So for example, let’s take the “Accounts” module and “billing_address_city”, “billing_address_state”, and the “rating” fields.

    modules = session.get_entry_fields('Accounts', ['rating','billing_address_state', 'billing_address_city'])

    When you print modules, you should get output similar to the following:

    Get Entry Fields Example


    Now that we have discussed how modules work with Python, we can talk about entries. We will first explain the get_entry_list function. Like in the modules example, you can leave everything blank except for the module name, but you will get a long list that doesn’t really help us. We want to add information to the “query” and “select_fields” parameters to get more precise information. Let’s choose “Accounts” for the module, industry type “retail” for the query, and the “id” and “sic code” for our selected fields. Given the above information, your query should now look like this:

    entry_list = session.get_entry_list('Accounts', "accounts.industry = 'retail'", "","",['id','sic_code'][])

    Get Entry Example

    The get_entries_count function will simply tell you how many entries exist in a given module. The parameters here are similar to the get entry list, where we need a query and a module. Make another call using the “Accounts” module and industry type “retail”.

    entries_count = session.get_entries_count('Accounts', "accounts.industry = 'retail'")

    Printing the value in entries_count will give you a number, which simply tells you how many fields with the retail type, exist in Accounts. Now we will explain the set_entry function. We need a module and a name value list for the set entry function so let’s go ahead and make one.

    first_nvl = sugarcrm.toNameValueList({'name':'Freds Printing','billing_address_state':'OH','industry':'Retail'})

    The name value list is an array of values used to store information into your database. This is just a simple example to show you the syntax to create a name value list, printing information from any given entry will show you all the information that can be stored in a name value list. Now we can call the set entry function by using this newly created name value list and store it as a sugar bean.

    first_bean = session.set_entry('Accounts', first_nvl)

    Set Entry Example

    Let’s create another bean and another name value list.

    second_nvl = sugarcrm.toNameValueList({'name':'Smooth Gravel Software','billing_address_state':'OH','industry':'Retail'})
    second_bean = session.set_entry('Accounts', second_nvl)

    This leads us into the next topic of the get entry function and the get entries function and how they work using the above beans and name value lists. We will now combine this information, using the get entry function.

    first_list = get_entry('Accounts', first_bean, "","")

    Now let’s output our newly created sugar bean entry that we stored into our database. You do this with the following syntax.

    print sugarcrm.fromNameValueList(first_list['entry_list'][0]['name_value_list'])

    Get Entry Example

    Now if we wanted to combine both examples into one unit, we can do this through the get entries function. It’s important to take note of the ids parameter. This parameter is an array of sugar beans. So we will take both of our beans and store them like such:

    beans = [first_bean,second_bean]
    combined_list = session.get_entries('Accounts', beans)

    To output the combined list, we will make a for loop which will iterate through the entire list to output all of the correct information.

    for x in total_list['entry_list']
    print sugarcrm.fromNameValueList(x['name_value_list'])
    print 'n'

    Get Entries Example

    I hope you find Python to be an efficient alternative to using the base form of SugarCRM. I worked with fellow Kent State University students on creating a Python wrapper class to overlap with the SugarCRM API. Our goal was to make a more efficient way of using the SugarCRM API. Since Python is a powerful language and is good for web based programming, we felt confident about our ability to achieve this. We were not only successful in doing so, but we would like to think that we have helped to improve on the established API that you are already familiar with. Our class consists of the sugarcrm.py class where the majority of the functionality is contained, another class dedicated to unit testing current functionality as well as newly implemented functionality, and a couple of other classes to aid in functionality.

    Let me know if you have any thoughts, concerns, problems or questions in regards to using Python or making Python work with API and hopefully I will be of assistance, if not I will be happy to direct you to another member of my team so they can aid you instead.

    10 responses to Web Services in Your Own Language: Part 5 – SugarCRM Python library


      Hey I’m trying to get this to work, but cannot login to sugarCRM.

      It continues to tell me:
      ERROR: Invalid Login : Login attempt failed please check the username and password 

      I know all my usernames and passwords are in order, wondering if you have any insight in to why this is happening. Thanks!


      I’m curious as to whether or not this should still work in version 6.5.5 CE and with LDAP?
      As I cannot seem to make it work, even while doing the DES3 encryption on the first 24 characters of the md5’d password.


      im having the same problem logging in, i even rewrote it all “correctley” using the requests library, and im still getting: ERROR: Invalid Login : Login attempt failed please check the username and password, but if i do the steps with the curl binary i can connect? odd. im goiing to try to write the connection code with pythons curl library and see if that helps.


      ok i was able to connect by cloning the github repo and doing checkout 2364096, then making sure i was using that copy of the sugarcrm.py file with: from sugarcrm import sugarcrm; print sugarcrm.__file__, now my password and username work yea!@


      howto use relationship in this module

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s