Amon
Amon

Reputation: 2951

Interacting with suiteCRM API V7.9 with Python requests

I've been trying for a while now to connect to the suiteCRM API using Python's request module but to no avail, the official tutorial uses PHP: https://docs.suitecrm.com/developer/api/api-4_1/

I can't seem to create the Python equivalent of this request, no matter what I get the same response:

<pre>/**
 * SugarWebServiceImplv4_1.php
 *
 * This class is an implementation class for all the web services.  Version 4_1 adds limit/off support to the
 * get_relationships function.  We also added the sync_get_modified_relationships function call from version 
 * one to facilitate querying for related meetings/calls contacts/users records.
 *
 */
Class [ <user> class SugarWebServiceImplv4_1 extends SugarWebServiceImplv4 ] {


  - Constants [0] {
  }

  - Static properties [1] {
    Property [ public static $helperObject ]
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Methods [36] {
    /**
     * Class Constructor Object
     *
     */
    Method [ <user, overwrites SugarWebServiceImplv4, ctor> public method __construct ] {

    }

    /**
     * Retrieve a collection of beans that are related to the specified bean and optionally return relationship data for those related beans.
     * So in this API you can get contacts info for an account and also return all those contact's email address or an opportunity info also.
     *
     * @param String $session -- Session ID returned by a previous call to login.
     * @param String $module_name -- The name of the module that the primary record is from.  This name should be the name the module was developed under (changing a tab name is studio does not affect the name that should be passed into this method)..
     * @param String $module_id -- The ID of the bean in the specified module
     * @param String $link_field_name -- The name of the lnk field to return records from.  This name should be the name the relationship.
     * @param String $related_module_query -- A portion of the where clause of the SQL statement to find the related items.  The SQL query will already be filtered to only include the beans that are related to the specified bean.

... that continues on, it looks like some documentation.

This is my code:

def get_info():

    headers = {
            "Content-Type": "application/json"
        }

    creds = OrderedDict()
    creds = {"user_auth": {'user_name':"***", "password": "***"}}
    creds = json.dumps(creds)

    data = {
        'method':'login', 
        'input_type': 'JSON', 
        'response_type':'JSON', 
        'rest_data': creds
    }

    data = json.dumps(data)
    response = requests.post("http://example.com/suitecrm/service/v4_1/rest.php", headers=headers, data=data)
    print(response.text)
    return response.text

Does anyone have any experience doing this? Thank you

edit: this is the PHP call from their docs:

<?php

$url = "http://example.com/suitecrm/service/v4_1/rest.php";

function restRequest($method, $arguments){
 global $url;
 $curl = curl_init($url);
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 $post = array(
         "method" => $method,
         "input_type" => "JSON",
         "response_type" => "JSON",
         "rest_data" => json_encode($arguments),
 );

 curl_setopt($curl, CURLOPT_POSTFIELDS, $post);

 $result = curl_exec($curl);
 curl_close($curl);
 return json_decode($result,1);
}


$userAuth = array(
        'user_name' => 'suitecrmuser',
        'password' => md5('suitecrmpassword'),
);
$appName = 'My SuiteCRM REST Client';
$nameValueList = array();

$args = array(
            'user_auth' => $userAuth,
            'application_name' => $appName,
            'name_value_list' => $nameValueList);

$result = restRequest('login',$args);
$sessId = $result['id'];

$entryArgs = array(
 //Session id - retrieved from login call
    'session' => $sessId,
 //Module to get_entry_list for
    'module_name' => 'Accounts',
 //Filter query - Added to the SQL where clause,
    'query' => "accounts.billing_address_city = 'Ohio'",
 //Order by - unused
    'order_by' => '',
 //Start with the first record
    'offset' => 0,
 //Return the id and name fields
    'select_fields' => array('id','name',),
 //Link to the "contacts" relationship and retrieve the
 //First and last names.
    'link_name_to_fields_array' => array(
        array(
                'name' => 'contacts',
                        'value' => array(
                        'first_name',
                        'last_name',
                ),
        ),
),
   //Show 10 max results
        'max_results' => 10,
   //Do not show deleted
        'deleted' => 0,
 );
 $result = restRequest('get_entry_list',$entryArgs);

print_r($result);

Upvotes: 1

Views: 1138

Answers (1)

mrbarletta
mrbarletta

Reputation: 922

Please check this working example, it should help you get started. Its using python3.

import urllib.request
import json
import hashlib

encode = hashlib.md5("MasterPass".encode('utf-8'))
encodedPassword = encode.hexdigest()
args = {'user_auth': {'user_name': 'admin','password': encodedPassword}}
crmUrl="https://yourname.crm.cr/service/v4_1/rest.php"
data = json.dumps(args)
args = {'method': 'login', 'input_type': 'json',
        'response_type' : 'json', 'rest_data' : data}
params = urllib.parse.urlencode(args).encode('utf-8')
response = urllib.request.urlopen(crmUrl, params)
response = response.read().strip()
if not response:
    print( "error: " , response)
result = json.loads(response.decode('utf-8'))
print (result)

Upvotes: 4

Related Questions