Webservices Tutorial

An Introduction to Simply Webservices

Simply provides a simple,powerful and secure application programming interface(the API) to work with entities stored in it. To use this document, you should have a basic familiarity with software development,Web services, and the Simply crm.

Webservices provide a easier way to Integrate Simply with your other software systems.

API Call characterstics

  • REST – API is REST based, so all the communication b/w client and server can happen over HTTP as GET or POST requests.
  • JSON – JSON is used to encode response and request.
  • Requests And Responses – Your client application prepares and submits a service request to the API, the API processes the request and returns a response, and the client application handles the response.
  • Committed Automatically – Every operation that writes to a Simply object is committed automatically. This is analogous to the AUTOCOMMIT setting in SQL.

API Response

Response Object

All responses will have the following format.

If the request is processed successfully,

<code>Response{
    success:Boolean=true
    result:Object //The Operation Result object
}
</code>

If there is a failure while processing the request,

<code>Reponse{
    success:Boolean=false
    error:ErrorObject
}
</code>

Error Object

<code>ErrorObject{
    errorCode:String //String representation of the error type
    errorMessage:String //Error message from the api.
}
</code>

errorCode is a string representation of the error type.

Error Handling

The response for any webservice request is a json object. The object has a field success which will have the value true if the operation was a success and false otherwise. If success is false the response object will contain a field error which will contain json object. The error object will contain two fields errorType, a single word description of the error, and errorMsg, a string containing a description of the error.

The example code is written in Php and has two dependencies the Zend Json library and Http_Client.

Requirements to run examples given in Toturial

  1. An installation of Simply with webservices.
  2. Php to run the example code
  3. HTTP_Client which can be installed by doing a pear install HTTP_Client
  4. Zend Json, you will need to download the <a href=”http://framework.zend.com/releases/ZendFramework-1.6.1/ZendFramework-1.6.1-minimal.zip “>minimal zend framework</a>

Logging In

The api does not use the password to log in. Instead, Simply provides a unique access key for each user. To get the user key for a user, go to the My Preferences pane of that user. You will find a Access Key field.

Login starts a client session with server, authenticates the user and returns a sessionId which will be used for all the subsequent communication with the server.

Logging in is a two step process, In the first step client obtains the challenge token from the server, which is used along with the user’s access key to log in.

Get Challenge

Get a challenge token from the server. This must be a GET request.

url format

<code>Request Type: GET
http://Simply_url/webservice.php?operation=getchallenge
    &username=[username]
</code>

Get Challenge Example

To get the challenge token you need to execute the following code.

<code>//e.g.
//url path to Simply/webservice.php like http://Simply_url/webservice.php
$endpointUrl = "http://localhost/ws/webservice.php";
//username of the user who is to logged in. 
$userName="admin";

$httpc = new HTTP_CLIENT();
//getchallenge request must be a GET request.
$httpc->get("$endpointUrl?operation=getchallenge&username=$userName");
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//check for whether the requested operation was successful or not.
if($jsonResponse['success']==false) 
    //handle the failure case.
    die('getchallenge failed:'.$jsonResponse['error']['errorMsg']);

//operation was successful get the token from the reponse.
$challengeToken = $jsonResponse['result']['token'];
</code>

GetChallengeResult

An object representing the response result of a getchallenge operation,

<code>GetChallengeResult{
    token:String //Challenge token from the server.
    serverTime:TimeStamp //The current server time.
    expireTime:TimeStamp //The time when the token expires.
}
</code>

Now that you have the challenge token you can go ahead with the login. The access key field in the login operation is the md5 checksum of the concatenation of the challenge token and the user’s own access key. The login operation, as opposed to getchallenge, is a post request.

Login

Login to the server using the challenge token obtained in get challenge operation.

url format

<code>Request Type:POST
http://Simply_url/webservice.php?operation=login
    &username=[username]
    &accessKey=[accessKey]
</code>

for accessKey create a md5 string after concatenating user accesskey from my preference page and the challenge token obtained from get challenge result.

Login Example

<code>//e.g.
//access key of the user admin, found on my preferences page.
$userAccessKey = 'dsf923rksdf3';

//create md5 string concatenating user accesskey from my preference page 
//and the challenge token obtained from get challenge result. 
$generatedKey = md5($challengeToken.$userAccessKey);
//login request must be POST request.
$httpc->post("$endpointUrl", 
    array('operation'=>'login', 'username'=>$userName, 
        'accessKey'=>$generatedKey), true);
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('login failed:'.$jsonResponse['error']['errorMsg']);

//login successful extract sessionId and userId from LoginResult to it can used for further calls.
$sessionId = $jsonResponse['result']['sessionName']; 
$userId = $jsonResponse['result']['userId'];

</code>

The session id is used to identify the current session and will be a common parameter in all subsequent requests.

LoginResult

An object representing the response result of a login operation,

<code>LoginResult{
    sessionId:String //Unique Identifier for the session
    userId:String //The Simply id for the logged in user
    version:String //The version of the webservices api
    SimplyVersion:String //The version of the Simply crm.
}
</code>

Getting Information

The api provides two operations to get information about available Simply objects.

The first one is listtypes, which provides a list of available modules. This list only contains modules the logged in user has access to.

List Types

List the names of all the Simply objects available through the api.

url format

<code>Request Type: GET
http://Simply_url/webservice.php?operation=listtypes
    &sessionName=[session id]
</code>

Returns a map containing the key ‘types’ with the value being a list of names of Simply objects.

List Types Example

<code>//listtypes request must be GET request.
$httpc->get("$endpointUrl?sessionName=$sessionId&operation=listtypes");
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('list types failed:'.$jsonResponse['error']['errorMsg']);
//Get the List of all the modules accessible.
$modules = $jsonResponse['result']['types'];
</code>

The second operation is describe which provides detailed type information about a Simply object.

Describe

Get the type information about a given Simply object.

url format

<code>Request Type: GET
http://Simply_url/webservice.php?operation=describe
    &sessionName=[session id]
    &elementType=[elementType]
</code>

Describe Example

<code>//e.g.
//Simply Object name which need be described or whose information is requested.
$moduleName = 'Contacts';

//use sessionId created at the time of login.
$params = "sessionName=$sessionId&operation=describe&elementType=$moduleName";
//describe request must be GET request.
$httpc->get("$endpointUrl?$params");
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('describe object failed:'.$jsonResponse['error']['errorMsg']);
//get describe result object.
$description = $jsonResponse['result'];

</code>

The description consists of the following fields

  1. label – The label used for the name of the module.
  2. name – The name of the module.
  3. createable – A boolean value specifying whether the object can be created.
  4. updateable – A boolean value specifying whether the object can be updated.
  5. deleteable – A boolean value specifying whether the object can be deleted.
  6. retrieveable – A boolean value specifying whether the object can be retrieved.
  7. fields – An array containing the field names and their type information.

Each element in the fields array describes a particular field in the object.

  1. name – The name of the field, as used internally by Simply.
  2. label – The label used for displaying the field name.
  3. mandatory – This is a boolean that specifies whether the field is mandatory, mandatory fields must be provided when creating a new object.
  4. type – An map that describes the type information for the field.
  5. default – The default value for the field.
  6. nillable – A boolean that specifies whether the field can be set to null.
  7. editable – A boolean that specifies whether the field can be modified.

The type field is of particular importance as it describes what type of the field is. This is an map that will contain at the least an element called name which is the name of the type. The name could be one of the following.

  1. string – A one line text field.
  2. text – A multiline text field.
  3. integer – A non decimal number field.
  4. double – A field for for floating point numbers.
  5. boolean – A boolean field, can have the values true or false.
  6. time – A string of the format hh:mm, format is based on the user’s settings time format.
  7. date – A string representing a date, the type map will contain another element called format which is the format in which the value of this field is expected, its based on the user’s settings date format.
  8. datetime – A string representing the date and time, the format is base on the user’s settings date format.
  9. autogenerated – Thes are fields for which the values are generated automatically by Simply, this is usually an object’s id field.
  10. reference – A field that shows a relation to another object, the type map will contain another element called refersTo which is an array containing the name of modules of which the field can point to.
  11. picklist – A field that can a hold one of a list of values, the map will contain two elements, picklistValues which is a list of possible values, and defaultValue which is the default value for the picklist.
  12. multipicklist – A picklist field where multiple values can be selected.
  13. phone – A field for storing phone numbers
  14. email – A field for storing email ids
  15. url – A field for storing urls
  16. skype – A field for storing skype ids or phone numbers.
  17. password – A field for storing passwords.
  18. owner – A field for defining the owner of the field. which could be a group or individual user.

DescribeResult

<code>DescribeResult{
    label:String //label of the module.
    name:String  //name of the module, as one provided in request.
    createable:Boolean //true if the logged-in user is allowed create records of type and false otherwise.
    updateable:Boolean //true if the logged-in user is allowed update records of type and false otherwise.
    deleteable:Boolean //true if the logged-in user is allowed delete records of type and false otherwise.
    retrieveable:Boolean //true if the logged-in user is allowed retrievealbe records of type and false otherwise.
    fields:Array //array of type Field.
}
</code>
Feild
<code>Feild{

<pre class="_fck_mw_lspace">   name:String //name of the field.



   label:String //label of the field.
   mandatory:Boolean //true if the needs to be provided with value while doing a create request and false otherwise.
   type:FieldType //an instance of FieldType.
   default:anyType //the default value for the field.
   nillable:Boolean //true if null can provided a value for the field and false otherwise.
   editalbe:Boolean //true if field can provided with a value while create or update operation.

}

</code></pre>

FieldType
<code>FieldType{
<pre class="_fck_mw_lspace">   name:Type //field type
   refersTo:Array //an array of Simply object names of types of record to which the field can refer to, its only defined for reference FieldType.
   picklistValues:Array //an array of type PicklistValue type. its only defined for picklist Fieldtype.
   defaultValue:String //an value of the default selected picklist value, its only defined for picklist Fieldtype.
   format:String //date format in which date type field need to populated with, eg, mm-dd-yyyy. its only defined for Date Fieldtype.

}

</code></pre>

picklist field value needs to provided explicitly.

PicklistValue
<code>PicklistValue{
    name:String //name of the picklist option.
    value:String //value of the picklist option.
}
</code>

Sample of describeResult Object

//$description from above example. For example print_r($description) might display

<code>Array
(
    [label] => Contacts
    [name] => Contacts
    [createable] => 1
    [updateable] => 1
    [deleteable] => 1
    [retrieveable] => 1
    [fields] => Array
        (
            [0] => Array
                (
                    [name] => account_id
                    [label] => Account Name
                    [mandatory] => 
                    [type] => Array
                        (
                            [name] => reference,
                            [refersTo] => Array
                            (
                                "Accounts"
                            )
                        )
                    [default] => 
                    [nillable] => 1
                    [editable] => 1
                )
        )
)

</code>

CRUD Operations

The api provides operations to create, retrieve, update and delete crm entity objects.

Create

Create a new entry on the server.

url format

<code>Request Type: POST
http://Simply_url/webservice.php?operation=create
    &sessionName=[session id]
    &element=[object]
    &elementType=[object type]

</code>

Create Example

Exmaple 1

You can create a contact using the create operation, in this case the mandatory fields are lastname and assigned_user_id.

<code>//e.g.
//fill in the details of the contacts.userId is obtained from loginResult.
$contactData  = array('lastname'=>'Valiant', 'assigned_user_id'=>$userId);
//encode the object in JSON format to communicate with the server.
$objectJson = Zend_JSON::encode($contactData);
//name of the module for which the entry has to be created.
$moduleName = 'Contacts';

//sessionId is obtained from loginResult.
$params = array("sessionName"=>$sessionId, "operation"=>'create', 
    "element"=>$objectJson, "elementType"=>$moduleName);
//Create must be POST Request.
$httpc->post("$endpointUrl", $params, true);
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('create failed:'.$jsonResponse['error']['errorMsg']);
$savedObject = $jsonResponse['result'];
$id = $savedObject['id'];
</code>

$savedObject is a map containing the fields of the new object including an id field which can be used to refer to the object.

Example 2.

Create a Contact and associate with an existing Account.

<code>//e.g 2
//Create a Contact and associate with an existing Account.
$queryResult = doQuery("select accountname,id from accounts where accountname='Simply';");
$accountId = $queryResult[0]['id'];
//For more details on how do a query request please refer the query operation example.

//fill in the details of the contacts.userId is obtained from loginResult.
$contactData  = array('lastname'=>'Valiant', 'assigned_user_id'=>$userId,'account_id'=>$accountId);
//encode the object in JSON format to communicate with the server.
$objectJson = Zend_JSON::encode($contactData);
//name of the module for which the entry has to be created.
$moduleName = 'Contacts';

//sessionId is obtained from loginResult.
$params = array("sessionName"=>$sessionId, "operation"=>'create', 
    "element"=>$objectJson, "elementType"=>$moduleName);
//Create must be POST Request.
$httpc->post("$endpointUrl", $params, true);
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('create failed:'.$jsonResponse['error']['errorMsg']);
$savedObject = $jsonResponse['result'];
$id = $savedObject['id'];
</code>
Example 3.

Create a Contact and associate with a new Account.

<code>//e.g 3

<p>//Create a Contact and associate with a new Account.
</p><p>//fill in the details of the Accounts.userId is obtained from loginResult.
$accountData  = array('accountname'=>'Simply', 'assigned_user_id'=>$userId);
//encode the object in JSON format to communicate with the server.
$objectJson = Zend_JSON::encode($accountData);
//name of the module for which the entry has to be created.
$moduleName = 'Accounts';
</p><p>//sessionId is obtained from loginResult.
$params = array("sessionName"=>$sessionId, "operation"=>'create', 
</p>
<pre class="_fck_mw_lspace">   "element"=>$objectJson, "elementType"=>$moduleName);


//Create must be POST Request. $httpc->post(“$endpointUrl”, $params, true); $response = $httpc->currentResponse(); //decode the json encode response from the server. $jsonResponse = Zend_JSON::decode($response[‘body’]);

//operation was successful get the token from the reponse.

if($jsonResponse[‘success’]==false)

   //handle the failure case.
   die('create failed:'.$jsonResponse['error']['errorMsg']);

$account = $jsonResponse[‘result’]; $accountId = $account[‘id’];

$contactData = array(‘lastname’=>’Valiant’, ‘assigned_user_id’=>$userId,’account_id’=>$accountId);

//encode the object in JSON format to communicate with the server. $objectJson = Zend_JSON::encode($contactData); //name of the module for which the entry has to be created. $moduleName = ‘Contacts’;

//sessionId is obtained from loginResult.

$params = array(“sessionName”=>$sessionId, “operation”=>’create’,

   "element"=>$objectJson, "elementType"=>$moduleName);

//Create must be POST Request. $httpc->post(“$endpointUrl”, $params, true); $response = $httpc->currentResponse(); //decode the json encode response from the server. $jsonResponse = Zend_JSON::decode($response[‘body’]);

//operation was successful get the token from the reponse.

if($jsonResponse[‘success’]==false)

   //handle the failure case.
   die('create failed:'.$jsonResponse['error']['errorMsg']);

$savedObject = $jsonResponse[‘result’]; $id = $savedObject[‘id’];

</code></pre>

CreateResult

A Map representing the contents of a crmentity based object. All reference fields are represented using Id type. A key called id of type Id represents the object’s unique id. This field is present for any object fetched from the database.

Retrieve

Retrieve a existing entry from the server.

url format

<code>Request Type: GET
http://Simply_url/webservice.php?operation=retrieve
    &session_name=[session id]
    &id=[object id
</code>

Retrieve Example

To retrieve an object using it’s id use the retrieve operation. You can retrieve the contact created in the create example.

<code>//sessionId is obtained from loginResult.
$params = "sessionName=$sessionId&operation=retrieve&id=$id";
//Retrieve must be GET Request.
$httpc->get("$endpointUrl?$params");
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);
//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('retrieve failed:'.$jsonResponse['error']['errorMsg']);

$retrievedObject = $jsonResponse['result'];
</code>

RetrieveResult

A Map representing the contents of a crmentity based object. All reference fields are represented using Id type. A key called id of type Id represents the object’s unique id. This field is present for any object fetched from the database.

Update

To update a retrieved or newly created object, you can use the update operation.

url format

<code>Request Type: POST
http://Simply_url/webservice.php?operation=update
    &sessionName=[session id]
    &element=[object]

</code>

Update Example

You can add a first name to the contact.

<code>//retrievedObject from previous example(Example 1).
$retrievedObject['firstname'] = 'Prince';
//encode the object in JSON format to communicate with the server.
$objectJson = Zend_JSON::encode($retrievedObject);

//sessionId is obtained from the login operation result.
$params = array("sessionName"=>$sessionId, "operation"=>'update', 
    "element"=>$objectJson);
//update must be a POST request.
$httpc->post("$endpointUrl", $params, true);
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('update failed:'.$jsonResponse['error']['errorMsg']);

//update result object.
$updatedObject = $jsonResponse['result'];
</code>

UpdateResult

A Map representing the contents of a crmentity based object. All reference fields are represented using Id type. A key called id of type Id represents the object’s unique id. This field is present for any object fetched from the database.

Delete

To delete an object use the delete operation.

url format

<code>Request Type: POST
http://Simply_url/webservice.php?operation=delete
    &sessionName=[session id]
    &id=[object id]
</code>

Delete Example

<code>
//delete a record created in above examples, sessionId a obtain from the login result.
$params = array("sessionName"=>$sessionId, "operation"=>'delete', "id"=>$id);
//delete operation request must be POST request.
$httpc->post("$endpointUrl", $params, true);
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('delete failed:'.$jsonResponse['error']['errorMsg']);

</code>

The delete does not have a result. The success flag is enough to find out if the operation was successful.

Queries

Simply provides a simple query language for fetching data. This language is quite similar to select queries in sql. There are limitations, the queries work on a single Module, embeded queries are not supported, and does not support joins. But this is still a powerful way of getting data from Simply.

Query always limits its output to 100 records, Client application can use limit operator to get different records.

url format

<code>Request Type: GET
http://Simply_url/webservice.php?operation=query
    &sessionName=[session id]
    &query=[query string]
</code>

Query Example

Example 1

<code>//query to select data from the server.
$query = "select * from Contacts where lastname='Valiant';";
//urlencode to as its sent over http.
$queryParam = urlencode($query);
//sessionId is obtained from login result.
$params = "sessionName=$sessionId&operation=query&query=$queryParam";
//query must be GET Request.
$httpc->get("$endpointUrl?$params");
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('query failed:'.$jsonResponse['errorMsg']);

//Array of SimplyObjects
$retrievedObjects = $jsonResponse['result'];
</code>

Example 2

specify the columns to be fetch for each records.

<code>//query to select data from the server.
$query = "select lastname,firstname,account_id,assigned_user_id from Contacts where lastname='Valiant';";
//urlencode to as its sent over http.
$queryParam = urlencode($query);
//sessionId is obtained from login result.
$params = "sessionName=$sessionId&operation=query&query=$queryParam";
//query must be GET Request.
$httpc->get("$endpointUrl?$params");
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('query failed:'.$jsonResponse['errorMsg']);

//Array of SimplyObjects
$retrievedObjects = $jsonResponse['result'];

</code>

This will return a array containing arrays representing the fields of each object that matched the query.

QueryResult

QueryResult is an Array of SimplyObjects.

SimplyObject

A Map representing the contents of a crmentity based object. All reference fields are represented using Id type. A key called id of type Id represents the object’s unique id. This field is present for any object fetched from the database.

The Query format

<code>select * | <column_list> | <count(*)>
from <object> [where <conditionals>] 
[order by <column_list>] [limit [<m>, ]<n>];

</code>

The column list in the order by clause can have at most two column names.

  • column_list: comma separated list of field names.
  • object: type name of the object.
  • conditionals: condition operations or in clauses or like clauses separated by ‘and’ or ‘or’ operations these are processed from left to right. The are no grouping, that is bracket operators.
  • conditional operators: <, >, <=, >=, =, !=.
  • in clauses: <column name> in (<value list>).
  • like clauses: <column name> in (<value pattern>).
  • value list: a comma separated list of values.
  • m, n: integer values to specify the offset and limit respectively.

Sync

Sync will return a SyncResult object containing details of changes after modifiedTime.

url format

<code>Request Type: GET
http://Simply_url/webservice.php?operation=sync
    &sessionName=[session id]
    &modifiedTime=[timestamp]
    &elementType=[elementType]
</code>

elementType: This is an optional parameter, if specified only the changes for that module after the given time are returned, otherwise changes to all user accessible modules after the given time are returned.

TimeStamp – A long representation of the number of seconds since unix epoch.

Example

Example 1

Create a Account and capture it in the sync API.

<code>//time after which all the changes on the server are needed.
$stime = time();
//Create some data now so it is captured by the sync api response.
//Create Account.
//fill in the details of the Accounts.userId is obtained from loginResult.
$accountData  = array('accountname'=>'Simply', 'assigned_user_id'=>$userId);
//encode the object in JSON format to communicate with the server.
$objectJson = Zend_JSON::encode($accountData);
//name of the module for which the entry has to be created.
$moduleName = 'Accounts';

//sessionId is obtained from loginResult.
$params = array("sessionName"=>$sessionId, "operation"=>'create', 
    "element"=>$objectJson, "elementType"=>$moduleName);
//Create must be POST Request.
$httpc->post("$endpointUrl", $params, true);
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('create failed:'.$jsonResponse['error']['errorMsg']);
$createResult = $jsonResponse['result'];

$params = "operation=sync&modifiedTime=$stime&sessionName=$sessionId";

//sync must be GET Request.
$httpc->get("$endpointUrl?$params");
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('query failed:'.$jsonResponse['errorMsg']);

//Array of SimplyObjects
$retrievedObjects = $jsonResponse['result'];

</code>

Response contains the Account with was created.

Example 2

Create a Account and a Contact, use sync api only for Accounts module only changes to Accounts module are returned.

<code>//time after which all the changes on the server are needed.
$stime = time();
//Create some data now so it is captured by the sync api response.

//fill in the details of the Accounts.userId is obtained from loginResult.
$accountData  = array('accountname'=>'Simply', 'assigned_user_id'=>$userId);
//encode the object in JSON format to communicate with the server.
$objectJson = Zend_JSON::encode($accountData);
//name of the module for which the entry has to be created.
$moduleName = 'Accounts';

//sessionId is obtained from loginResult.
$params = array("sessionName"=>$sessionId, "operation"=>'create', 
    "element"=>$objectJson, "elementType"=>$moduleName);
//Create must be POST Request.
$httpc->post("$endpointUrl", $params, true);
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('create failed:'.$jsonResponse['error']['errorMsg']);
$createResult = $jsonResponse['result'];

//Create a Contact.
//fill in the details of the contacts.userId is obtained from loginResult.
$contactData  = array('lastname'=>'Valiant', 'assigned_user_id'=>$userId);
//encode the object in JSON format to communicate with the server.
$objectJson = Zend_JSON::encode($contactData);
//name of the module for which the entry has to be created.
$moduleName = 'Contacts';

//sessionId is obtained from loginResult.
$params = array("sessionName"=>$sessionId, "operation"=>'create', 
    "element"=>$objectJson, "elementType"=>$moduleName);
//Create must be POST Request.
$httpc->post("$endpointUrl", $params, true);
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('create failed:'.$jsonResponse['error']['errorMsg']);
$savedObject = $jsonResponse['result'];
$id = $savedObject['id'];

$params = "operation=sync&modifiedTime=$stime&sessionName=$sessionId";

//sync must be GET Request.
$httpc->get("$endpointUrl?$params");
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('query failed:'.$jsonResponse['errorMsg']);

//Array of SimplyObjects
$retrievedObjects = $jsonResponse['result'];

</code>

SyncResult

An object representing the response of a sync operation,

<code>SyncResult{
    updated:[Object] //List of Objects created or modified.
    deleted:[Id] //List of *Id* of objects deleted.
    lastModifiedTime:Timstamp //time of the latest change. which can used in the next call to the Sync api to get all the latest changes that the client hasn't obtained.
}
</code>

Logging Out

Logout

Logout from the webservices session, this leaves the webservice session invalid for furthur use.

url format

<code>Request Type: GET
http://Simply_url/webservice.php?operation=logout
    &sessionName=[session id]
</code>

Example

<code>//SessionId is the session which is to be terminated.
$params = "operation=logout&sessionName=$sessionId";

//logout must be GET Request.
$httpc->get("$endpointUrl?$params");
$response = $httpc->currentResponse();
//decode the json encode response from the server.
$jsonResponse = Zend_JSON::decode($response['body']);

//operation was successful get the token from the reponse.
if($jsonResponse['success']==false)
    //handle the failure case.
    die('query failed:'.$jsonResponse['errorMsg']);
//logout successful session terminated.
</code>

Extending Simply Web Client Using Webservices

Extend Session

Extends current Simply web client session to webservices and returns a webservices session id. when working the from the within the Simply web client, user can re-use the current authenticated session instead of login to Simply again for webservices.

Notice: if the user does a Extend Session then the session will be tied together, so logging out one(webservices or web client) will log the user out of the other as well. for extend session operation to work cookies must be enabled on the client browser.

url format

<code>Request Type: POST
http://Simply_url/webservice.php?operation=extendsession
</code>

Example

<code>
</code>

This Example is written is Javascript, as Extend Session is only valid from the Simply web client.

Requirements To Run the Example
  • JQUERY library – to do ajax http request.
  • JSON library – json2.js file available with Simply at json.org
Example 1
<code>
//operation parameters.
var params = "operation=extendsession";
//end point of the services.
var endPointUrl = "http://Simply_url/webservice.php";

//extendSession is post request, invoke jquery http post request.
$.post(endPointUrl, params, function(result){
    //decode the json encode response from the server.
    var jsonResponse = json.parse(result);

    //operation was successful get the token from the reponse.
    if(jsonResponse['success']==false)
        //handle the failure case.
        die('login failed:'+jsonResponse['error']['errorMsg']);

    //login successful extract sessionId and userId from LoginResult so it can used for further calls.
    var sessionId = jsonResponse['result']['sessionName']; 
    var userId = jsonResponse['result']['userId'];
});
</code>