REST Tutorial
REST Tutorial
REST Webservices
API Tutorial
Version 1.5.1.2
Rev. from 20.05.2016
berliCRM
Table Of Contents
OVERVIEW ................................................................................................................................................. 3
API Call characteristics ............................................................................................................................ 3
API Response ........................................................................................................................................... 3
Response Object .............................................................................................................................. 3
Error Object ..................................................................................................................................... 3
Error Handling ......................................................................................................................................... 4
Requirements to run examples provided in this Tutorial ....................................................................... 4
Logging In ................................................................................................................................................ 4
Get Challenge ...................................................................................................................................... 4
Login .................................................................................................................................................... 6
Getting Information................................................................................................................................. 7
List Types ......................................................................................................................................... 8
Describe ........................................................................................................................................... 8
CRUD Operations................................................................................................................................... 12
Create ............................................................................................................................................ 12
CreateResult .......................................................................................................................................... 14
Retrieve ......................................................................................................................................... 14
Update ........................................................................................................................................... 15
Delete ............................................................................................................................................ 16
Queries .................................................................................................................................................. 17
Query Example .............................................................................................................................. 17
QueryResult ........................................................................................................................................... 18
The Query format .......................................................................................................................... 18
Sync ....................................................................................................................................................... 18
SyncResult ..................................................................................................................................... 21
Logging Out ........................................................................................................................................... 21
Logout ............................................................................................................................................ 21
Acknowledgement................................................................................................................................. 22
OVERVIEW
The CRM system provides a simple, powerful and secure application programming interface
(the API) to create, modify or delete CRM contents. This document is a tutorial for developers
which intend to use REST based APIs to connect other applications with the CRM system.
REST the API is REST based. All communications between an application and the
CRM server can happen over HTTP as GET or POST requests.
JSON - JSON is used to encode response and request.
Requests and Responses - The application prepares and submits a service request to
the API, the API processes the request and returns a response, and the application
handles the response.
Committed Automatically - Every operation that writes to a CRM object is committed
automatically. This is analogous to the AUTOCOMMIT setting in SQL.
API Response
Response Object
<code>Response{
success:Boolean=true
result:Object //The Operation Result object
}
</code>
<code>Reponse{
success:Boolean=false
error:ErrorObject
}
</code>
Error Object
<code>ErrorObject{
code:String //String representation of the error type
message:String //Error message from the API.
}
</code>
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 for the errorType, a single word description of the error, and errorMsg
as a string containing a description of the error.
The following example code is written in PHP and has two dependencies, the Zend Json
library and Http_Client.
Logging In
The API does not use the CRM users password to log in. Instead, the CRM provides an
unique access key for each user. To get the user key for a user, go to the My Preferences
menu of that user in the CRM. There you will find an Access Key field.
The Login procedure starts a client session with the CRM server, authenticates the user and
returns a sessionId which will be used for all the subsequent communication with the CRM
server.
Logging in is a two-step process. In the first step the client obtains the challenge token from
the server, which is used along with the user's access key for the login.
Get Challenge
Get a challenge token from the server. This has to be a GET request.
URL format
<code>Request Type: GET
http://your_url/webservice.php?operation=getchallenge
&username=[username]
</code>
To get the challenge token you need to execute the following code.
<code>//e.g.
crm-now development documents Page 4
berliCRM
st contains the JSON Object with the Challenge Token, which can be handled like a regular
string.
GetChallengeResult
<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://your_url/webservice.php?operation=login
&username=[username]
&accessKey=[accessKey]
</code>
For accessKey create an md5 hash after concatenating the challenge token obtained before
and user accesskey from my preference page.
Login Example
<code>//e.g.
//access key of the user admin, found on my preferences page.
$userAccessKey = 'dsf923rksdf3';
</code>
The session id is used to identify the current session and will be a common parameter in all
subsequent requests.
Login Example
st2 contains the JSON Object with the Session ID and user ID, which can be handled like a
regular string.
LoginResult
<code>LoginResult{
sessionName:String //Unique Identifier for the session
userId:String //The CRM id for the logged in user
version:String //The version of the webservices API
vtigerVersion:String //The version of the CRM.
}
</code>
Getting Information
The API provides two operations to get information about available CRM objects.
The first one is called 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 CRM objects available through the API.
URL format
<code>Request Type: GET
http://your_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 CRM objects.
httpreq3.Method = "GET"
The second operation is called describe which provides detailed type information about a
CRM object.
Describe
URL format
<code>Request Type: GET
http://your_url/webservice.php?operation=describe
&sessionName=[session id]
&elementType=[elementType]
</code>
Describe Example
<code>//e.g.
//CRM Object name which need be described or whose information is
requested.
$moduleName = 'Contacts';
Each element in the fields array describes a particular field in the object.
The type field is of particular importance. It provides a map that will contain at least an
element called name which is the name of the type. The name could be one of the following.
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, it is based on the user's
settings date format.
8. datetime - A string representing the date and time, the format is based on the user's settings
date format.
9. autogenerated - These are fields for which the values are generated automatically by the
CRM, 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>
Field
<code>Field{
<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
crm-now development documents Page 10
berliCRM
PicklistValue
<code>PicklistValue{
name:String //name of the picklist option.
value:String //value of the picklist option.
}
</code>
//$description from above example. For example, print_r($description) might display the
result.
<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
URL format
<code>Request Type: POST
http://your_url/webservice.php?operation=create
&sessionName=[session id]
&element=[object]
&elementType=[object type]
</code>
Create Example
Example 1
You can create a contact using the create operation. You must consider mandatory fields in
the CRM marked by a red *, in this case the default 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';
$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.
<code>//e.g 2
//Create a Contact and associate with an existing Account.
$queryResult = doQuery("select accountname,id from accounts where
accountname='companyname';");
$accountId = $queryResult[0]['id'];
//For more details on how do a query request please refer the query
operation example.
Example 3.
<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'=>'Vtiger',
'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);
if($jsonResponse['success']==false)
$account = $jsonResponse['result'];
$accountId = $account['id'];
$contactData = array('lastname'=>'Valiant',
'assigned_user_id'=>$userId,'account_id'=>$accountId);
"element"=>$objectJson, "elementType"=>$moduleName);
die('create failed:'.$jsonResponse['error']['message']);
$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 an 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
URL format
<code>Request Type: GET
crm-now development documents Page 14
berliCRM
http://your_url/webservice.php?operation=retrieve
&sessionName=[session id]
&id=[object id]
</code>
Retrieve Example
To retrieve an object using its id use the retrieve operation. You can retrieve the contact
created in the create example.
$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://your_url/webservice.php?operation=update
&sessionName=[session id]
&element=[object]
</code>
Update Example
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.
Be aware that every field of a CRM object will be emptied if no value is supplied on an
update, therefor its always advised to retrieve the object, change the value(s) of field(s) and
then perform the update with the altered object.
Delete
URL format
<code>Request Type: POST
http://your_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']);
</code>
The success flag should be enough to find out if the operation was successful.
crm-now development documents Page 16
berliCRM
Queries
The CRM provides a simple query language for fetching data. This language is quite similar
to select queries in SQL. There are the following limitations:
Nevertheless, the remaining options have a powerful ways for getting data from the CRM.
Query always limits its output to 100 records. Client application can use limit operator to get
less records.
URL format
<code>Request Type: GET
http://your_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 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']);
//Array of vtigerObjects
$retrievedObjects = $jsonResponse['result'];
</code>
Example 2
$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']);
//Array of vtigerObjects
$retrievedObjects = $jsonResponse['result'];
</code>
This will return an array containing objects like retrieve would have fetched.
QueryResult
VtigerObject
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.
</code>
The column list in the order by clause can have at most two column names.
Sync
Sync will return a SyncResult object containing details of changes after modifiedTime.
URL format
<code>Request Type: GET
http://your_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.
Example 1
<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'=>'Vtiger',
'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';
$params =
"operation=sync&modifiedTime=$stime&sessionName=$sessionId";
//Array of vtigerObjects
$retrievedObjects = $jsonResponse['result'];
</code>
Example 2
Create an 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.
//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';
if($jsonResponse['success']==false)
//handle the failure case.
die('create failed:'.$jsonResponse['error']['message']);
$savedObject = $jsonResponse['result'];
$id = $savedObject['id'];
$params =
"operation=sync&modifiedTime=$stime&sessionName=$sessionId";
//Array of vtigerObjects
$retrievedObjects = $jsonResponse['result'];
</code>
SyncResult
<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 further
use.
URL format
<code>Request Type: GET
http://your_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";
Acknowledgement
This tutorial was originally provided by vtiger. With the friendly permission of vtiger it has been
modified to meet the specific requirements of crm-nows berliCRM version.