© 2015 X2Engine Inc.

Difference between revisions of "REST API Reference"

From X2Engine
Jump to: navigation, search
(Interpreting Payload Data)
 
(29 intermediate revisions by 4 users not shown)
Line 1: Line 1:
 
[[Category:Development]]
 
[[Category:Development]]
X2Engine's second-generation HTTP-based API, '''available as of version 4.1''', is (for the most part) REST-ful, and includes many improvements over the original API.
+
X2Engine's second-generation HTTP-based API, '''available as of version 4.1''', is (for the most part) REST-ful, and includes many improvements over the original API.
 +
 
 +
The source code of the main components used in this API are:
 +
* [https://github.com/X2Engine/X2Engine/blob/master/x2engine/protected/controllers/Api2Controller.php protected/controllers/Api2Controller.php]
 +
* [https://github.com/X2Engine/X2Engine/blob/master/x2engine/protected/components/util/ResponseUtil.php protected/components/ResponseBehavior.php]
 +
* [https://github.com/X2Engine/X2Engine/blob/master/x2engine/protected/components/util/ResponseUtil.php protected/components/util/ResponseUtil.php]
 +
Functional tests for the API can be found alongside the tests for the legacy API, in [https://github.com/X2Engine/X2Engine/tree/master/x2engine/protected/tests/api protected/tests/api].
  
 
= Introduction =
 
= Introduction =
Line 34: Line 40:
  
 
== Access Credentials ==
 
== Access Credentials ==
To use the API, you will need to obtain X2Engine API credentials, which include a username and an API key. An X2Engine user with administrative privileges can get or set API keys in the Users module administrator. Any user can authenticate via the API by visiting the ''Update'' page for any given user.
+
To use the API, you will need to obtain X2Engine API credentials, which include a username and an API key. An X2Engine user with administrative privileges can get or set API keys in the Users module, by going to the edit page for that user. To summarize:
 +
# As the administrator, go to the user management module. You'll find it under "Users"
 +
# Click on the desired user
 +
# Click "Update User"
 +
# See the "API Key" field.
 +
 
 +
While there is a user in this section called "API User" you should not use it for this version of the API. That user exists to maintain backwards compatibility for a very old version of the API so that users who have set up API connectors with those endpoints will not have their code break. This user will not function with the current API and attempting to use it will generate a 403 error.
  
 
== Explore the API Using Your Web Browser ==
 
== Explore the API Using Your Web Browser ==
Line 85: Line 97:
  
  
'''Note:''' because headers are sent without any built-in encryption, it is highly recommended that you use the API over HTTPS (HTTP encrypted using TLS), if available, or make API requests only within a network where packets are not easily intercepted.
+
=== Caveats ===
 +
'''Note, firstly:''' because headers are sent without any built-in encryption, it is highly recommended that you use the API over HTTPS (HTTP encrypted using TLS), if available, or make API requests only within a network where packets are not easily intercepted.
 +
 
 +
Furthermore, if you have password-protected any web directories that contain X2Engine, you will need to make a "Satisfy any" exception for URIs within the API, or clients may not be able to authenticate.
  
 
= Model-based Input and Output =
 
= Model-based Input and Output =
Line 145: Line 160:
 
* Comparisons based on action description in queries:
 
* Comparisons based on action description in queries:
 
** They are unaffected by options that control comparisons; the comparison is un-escaped "LIKE" and the criteria combination operator is effectively "AND" (<tt>_partial=1&_escape=0</tt>).  
 
** They are unaffected by options that control comparisons; the comparison is un-escaped "LIKE" and the criteria combination operator is effectively "AND" (<tt>_partial=1&_escape=0</tt>).  
** They will also be very slow.
+
** They will also be very slow; effectively, the comparison in the query is being performed on a <tt>TEXT</tt> column in a joined table
  
 
The limitations of filtering by action description are endemic to how the "field" is actually stored in a different database table than the contacts, and the type of the column is <tt>TEXT</tt>.
 
The limitations of filtering by action description are endemic to how the "field" is actually stored in a different database table than the contacts, and the type of the column is <tt>TEXT</tt>.
Line 160: Line 175:
 
! scope="row" | <tt>Quote</tt>
 
! scope="row" | <tt>Quote</tt>
 
|Quote records can be accessed and manipulated, but associated "line items" data cannot be viewed or manipulated.
 
|Quote records can be accessed and manipulated, but associated "line items" data cannot be viewed or manipulated.
 +
|-
 +
! scope="row" | <tt>X2Leads</tt>
 +
|This data type can be fully accessed and manipulated, but there is not yet any built-in action available for directly converting a lead to an opportunity.
 
|-
 
|-
 
! scope="row" | <tt>X2List</tt>
 
! scope="row" | <tt>X2List</tt>
Line 175: Line 193:
  
 
To update a record, send a <tt>PUT</tt> or <tt>PATCH</tt> request to a direct URI, and set the body and <tt>Content-Type</tt> header as one would in a <tt>POST</tt> request to create such a record. Finally, to delete the record, send a DELETE request to that same direct URI. It is not necessary in the case of deletion to include a body or set the <tt>Content-Type</tt> header.
 
To update a record, send a <tt>PUT</tt> or <tt>PATCH</tt> request to a direct URI, and set the body and <tt>Content-Type</tt> header as one would in a <tt>POST</tt> request to create such a record. Finally, to delete the record, send a DELETE request to that same direct URI. It is not necessary in the case of deletion to include a body or set the <tt>Content-Type</tt> header.
 +
 +
If you need to retrieve the record count of any of the supported classes, then you can append the "count" operation to the URI of a GET request. For example, to retrieve the number of Contacts in the system, one would call the URL:
 +
  index.php/api2/Contacts/count
 +
This can also be combined with the _findBy directive to allow count of models matching specific criteria, i.e., to count the number of Contacts named "Thaddeus" the respective API call would be:
 +
  index.php/api2/Contacts/count/by:firstName=Thaddeus.json
 +
 +
== Direct Manipulation by Attributes ==
 +
Given a set of uniquely-identifying attribute names and values, it is possible to directly access and manipulate an existing X2Model-based record by without first querying it. The direct URI for this use case is:
 +
 +
  index.php/api2/{_class}/by:{_findBy}.json
 +
 +
where the query parameter <tt>{_findBy}</tt> is a list of key and value pairs formatted as <tt>key1=value1;key2=value2</tt>.
 +
 +
For example: provided the email address "james@example.com" and first name "James" uniquely identify the contact with ID of 457, the following two direct access URIs are equivalent:
 +
 +
  index.php/api2/Contacts/by:email=james@example.com;firstName=James.json
 +
  index.php/api2/Contacts/457.json
 +
 +
Furthermore, note what happens in the following scenarios:
 +
 +
'''If the set of attributes (i.e. email address) is not unique to a single record:''' the find-by-attributes direct URI will return with a 300 status and an [[#Error Objects|error object]] containing the two special properties: ''queryUri'', the URI to query for records by the attributes given, and: ''directUris'', a list containing the direct URI of each matching record.
 +
 +
''' If no contact matches the attributes given:''' the URI will respond with a 404 status.
 +
 +
=== Using the first matching record ===
 +
If one wants to forcefully select and use the first record matching the attributes, regardless of how many match, append the <tt>_useFirst</tt> parameter and set equal to 1, i.e.
 +
 +
  index.php/api2/Contacts/by:email=james@example.com;firstName=James.json?_useFirst=1
  
 
== Working With Associated Actions ==
 
== Working With Associated Actions ==
Line 413: Line 459:
 
   index.php/api2/hooks
 
   index.php/api2/hooks
  
The POST-ed JSON-encoded dictionary should contain at least the following properties:  
+
The POST-ed JSON-encoded dictionary object should contain the following properties:  
 
{|class="wikitable"
 
{|class="wikitable"
 
|-
 
|-
 
! scope="row" | <tt>event</tt>
 
! scope="row" | <tt>event</tt>
| An event name; see [[#Supported Event Names and X2Flow]]
+
| An event name; see [[#Events Reference]]
 
|-
 
|-
 
! scope="row" | <tt>target_url</tt>
 
! scope="row" | <tt>target_url</tt>
Line 426: Line 472:
 
|-
 
|-
 
|}
 
|}
 +
 +
Upon successful creation of a web hook, note that the server will respond with a '''201''' status. The body will be the JSON-encoded attributes of the new hook record, and the <tt>Location</tt> header of the response will be set to a URL that can be used to remove the web hook when it is no longer needed (see [[#Deleting Web Hooks]]).
  
 
== Supported Event Names and X2Flow ==
 
== Supported Event Names and X2Flow ==
Line 436: Line 484:
 
When you create a hook, you will have the option of setting its <tt>directPayload</tt> property to 1. A value of 0/false (the default value) for this field implies that if one of the trigger parameters is named "model" and is a subclass of X2Model (i.e. contact, account, opportunity), the (JSON-encoded) payload data will contain a property <tt>'''resource_url'''</tt> pointing to the URL on X2Engine of that model record. Thus, upon receiving the webhook request from X2Engine, the client end should then make a <tt>GET</tt> request from that URL to retrieve the model part of the payload data. If, on the other hand, <tt>directPayload</tt> is set to 1/true, what will instead happen is that the model will be included in the payload's <tt>'''model'''</tt> property as a dictionary of attribute-value pairs.
 
When you create a hook, you will have the option of setting its <tt>directPayload</tt> property to 1. A value of 0/false (the default value) for this field implies that if one of the trigger parameters is named "model" and is a subclass of X2Model (i.e. contact, account, opportunity), the (JSON-encoded) payload data will contain a property <tt>'''resource_url'''</tt> pointing to the URL on X2Engine of that model record. Thus, upon receiving the webhook request from X2Engine, the client end should then make a <tt>GET</tt> request from that URL to retrieve the model part of the payload data. If, on the other hand, <tt>directPayload</tt> is set to 1/true, what will instead happen is that the model will be included in the payload's <tt>'''model'''</tt> property as a dictionary of attribute-value pairs.
  
Note, the two most common possible properties <tt>resource_url</tt> and <tt>model</tt> are mutually exclusive; which one if any will get included depends on the <tt>direcPayload, other properties of the payload include but may not be limited to the following:
+
Note, the two most common possible properties <tt>resource_url</tt> and <tt>model</tt> are mutually exclusive; which one if any will get included depends on the <tt>direcPayload</tt>, other properties of the payload include but may not be limited to the following:
  
 
The class of model (and thus the structure of data) that should be expected to come from any given web hook generally depends on the model class to which the event corresponds. For example, the model is of class <tt>Actions</tt> in an <tt>ActionCompleteTrigger</tt> event, but they could be any general record type (contacts, actions, accounts, etc.) in a <tt>RecordCreateTrigger</tt> event.
 
The class of model (and thus the structure of data) that should be expected to come from any given web hook generally depends on the model class to which the event corresponds. For example, the model is of class <tt>Actions</tt> in an <tt>ActionCompleteTrigger</tt> event, but they could be any general record type (contacts, actions, accounts, etc.) in a <tt>RecordCreateTrigger</tt> event.
Line 445: Line 493:
 
|-
 
|-
 
! scope="col" | Event
 
! scope="col" | Event
 +
! scope="col" | Description
 
! scope="col" | Payload
 
! scope="col" | Payload
 
|-
 
|-
 
|ActionCompleteTrigger
 
|ActionCompleteTrigger
|'''model''': An action; '''user''': username of the user who completed the action
+
|An action has been marked as complete
 +
|'''model'''/'''resource_url''': An action; '''user''': username of the user who completed the action
 
|-
 
|-
 
|ActionOverdueTrigger
 
|ActionOverdueTrigger
|'''model''': an action; '''duration''': the amount of time that has passed since the due date of the action
+
|An action is overdue (cron required)
 +
|'''model'''/'''resource_url''': an action; '''duration''': the amount of time that has passed since the due date of the action
 
|-
 
|-
 
|ActionUncompleteTrigger
 
|ActionUncompleteTrigger
|'''model''': An action; '''user''': username of the user who marked the action as uncomplete
+
|An action has been marked as uncomplete
 +
|'''model'''/'''resource_url''': An action; '''user''': username of the user who marked the action as uncomplete
 
|-
 
|-
 
|CampaignEmailClickTrigger
 
|CampaignEmailClickTrigger
|'''model''': the contact who clicked their campaign email; '''campaign''': Name of the email campaign
+
|A tracking link in a campaign has been clicked
 +
|'''model''': the contact who clicked the link in their campaign email; '''campaign''': Name of the email campaign
 +
|-
 +
|CampaignUnsubscribeTrigger
 +
|A contact has unsubscribed from email campaigns
 +
|'''model''': the contact; '''campaign''': Name of the email campaign
 +
|-
 +
|CampaignWebActivityTrigger
 +
|''(Professional Edition only)'' A contact who was part of a campaign is visiting your website
 +
|'''model'''/'''resource_url''': the contact; '''campaign''': Name of the email campaign; '''url''': URL of the page that the contact is visiting
 +
|-
 +
|NewsletterEmailClickTrigger
 +
|''(Professional Edition only)'' A newsletter subscriber has clicked a tracking link
 +
|'''item''': The list item record (<tt>{"emailAddress":<email address>,"opened":<timestamp opened>,"clicked":<timestamp clicked>,"unsubscribed":<has unsubscribed>}</tt>); '''email''': email address of subscriber; '''campaign''': name of the newsletter campaign; '''url''': URL visited by the subscriber
 +
|-
 +
|NewsletterEmailOpenTrigger
 +
|''(Professional Edition only)'' A newsletter subscriber has opened an email
 +
|'''item''': The list item record (<tt>{"emailAddress":<email address>,"opened":<timestamp opened>,"clicked":<timestamp clicked>,"unsubscribed":<has unsubscribed>}</tt>); '''email''': email address of subscriber; '''campaign''': name of the newsletter campaign
 +
|-
 +
|NewsletterUnsubscribeTrigger
 +
|''(Professional Edition only)'' A newsletter subscriber has unsubscribed
 +
|'''item''': The list item record (<tt>{"emailAddress":<email address>,"opened":<timestamp opened>,"clicked":<timestamp clicked>,"unsubscribed":<has unsubscribed>}</tt>); '''email''': email address of subscriber; '''campaign''': name of the newsletter campaign
 +
|-
 +
|RecordCreateTrigger
 +
|A record of one of the main types (contact, action, account, opportunity, etc.) has been created
 +
|'''model'''/'''resource_url''': The data that was inserted
 +
|-
 +
|RecordDeleteTrigger
 +
|A record of one of the main types (contact, action, account, opportunity, etc.) has been deleted
 +
|'''model'''/'''resource_url''': The data that was inserted
 +
|-
 +
|RecordTagAddTrigger
 +
|A record has been tagged
 +
|'''model'''/'''resource_url''': The record that was tagged; '''tags''': an array of strings (tags) that were added.
 +
|-
 +
|RecordTagRemoveTrigger
 +
|Tags have been deleted from a record
 +
|'''model'''/'''resource_url''': The record whose tags were changed; '''tags''': an array of strings (tags) that were removed
 +
|-
 +
|RecordUpdateTrigger
 +
|A record of one of the main types (contact, action, account, opportunity, etc.) has been updated
 +
|'''model'''/'''resource_url''': The data that was updated
 +
|-
 +
|RecordViewTrigger
 +
|A record of one of the main types (contact, action, account, opportunity, etc.) has been viewed
 +
|'''model'''/'''resource_url''': The data that was viewed
 +
|-
 +
|TargetedContentRequestTrigger
 +
|''(Professional Edition Only)'' Targeted content is being accessed on your website
 +
|'''model'''/'''resource_url''': The contact on your website; '''url''': the URL being viewed; '''flowId''': internal parameter (not of much use outside X2Engine)
 +
|-
 +
|UserLoginTrigger
 +
|A user has logged in
 +
|'''user''': the username of the user who has logged in
 +
|-
 +
|UserLogoutTrigger
 +
|A user has logged out
 +
|'''user''': the username of the user who has logged out
 +
|-
 +
|WebActivityTrigger
 +
|''(Professional Edition Only)'' A contact is viewing your website
 +
|'''model'''/'''resource_url''': the contact; '''url''': the URL being viewed; '''probability''' ''(Platinum Edition only)'' percentage confidence of browser-fingerprinting-based match between a web client and a contact
 +
|-
 +
|WebleadTrigger
 +
|A new web lead has come in
 +
|'''model'''/'''resource_url''': the contact associated with the form submission; '''tags''': a list of tags added to the contact through the submission, if applicable
 +
|-
 +
|WorkflowCompleteStageTrigger
 +
|A process stage has been completed
 +
|'''workflow''': The workflow template model (has properties name, isDefault, lastUpdated and colors); '''model'''/'''resource_url''': the record (i.e. Opportunity/Contact) for which the stage was completed; '''workflowId''': internal use (not very useful outside X2Engine); '''stageNumber''': the number of the stage in the process that was completed.
 +
|-
 +
|WorkflowCompleteTrigger
 +
|A process has been fully completed
 +
|'''workflow''': The workflow template model (has properties name, isDefault, lastUpdated and colors); '''model'''/'''resource_url''': the record (i.e. Opportunity/Contact) for which the stage was completed; '''workflowId''': internal use (not very useful outside X2Engine)
 +
|-
 +
|WorkflowRevertStageTrigger
 +
|A process stage has been reverted.
 +
|Same as WorkflowCompleteStageTrigger
 +
|-
 +
|WorkflowStartStageTrigger
 +
|A process stage has been started
 +
|Same as WorkflowCompleteStageTrigger
 +
|-
 +
|WorkflowStartTrigger
 +
|A process has been started
 +
|Same as WorkflowCompleteTrigger
 
|-
 
|-
 
|}
 
|}
  
 
== Deleting Web Hooks ==
 
== Deleting Web Hooks ==
(section coming soon)
+
Given the numeric identifier of a web hook, it can be deleted by sending a <tt>DELETE</tt> to a URI formatted as follows:
 +
  index.php/api2/hooks/:{_id}
 +
So, for a web hook with id=74:
 +
  index.php/api2/hooks/:74
 +
 
 +
The full URL should have been given to the API client in the <tt>Location</tt> header in the response to the original web hook creation request. Upon successful deletion, the server will respond with status code '''204'''.
  
 
= Interpreting Server Responses =
 
= Interpreting Server Responses =
Line 493: Line 635:
 
|-
 
|-
 
! colspan="3" | '''Redirection''' (<tt>3XX</tt>)
 
! colspan="3" | '''Redirection''' (<tt>3XX</tt>)
 +
|-
 +
! scope="row" | <tt>300</tt>
 +
|When using the "[[#Direct Manipulation by Attributes|find by attributes]]" direct access URI
 +
|''Multiple choices.'' There criteria specified for direct access (as opposed to querying) match more than one record.
 
|-
 
|-
 
! scope="row" | <tt>303</tt>
 
! scope="row" | <tt>303</tt>

Latest revision as of 21:01, 21 December 2015

X2Engine's second-generation HTTP-based API, available as of version 4.1, is (for the most part) REST-ful, and includes many improvements over the original API.

The source code of the main components used in this API are:

Functional tests for the API can be found alongside the tests for the legacy API, in protected/tests/api.

Introduction

This API within X2Engine, can be accessed via the URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root

 index.php/api2

It also:

  • Exclusively uses JSON for data input and output
  • Tends to use similar URIs for both input and output (distinguishing operations via the request method)
  • Uses a variety of server response codes to distinguish error scenarios in the case of an unsuccessful transaction
  • Uses the "HTTP Basic Auth" method for authentication

For example, to create a contact, one would send a POST request with its body a JSON-encoded attributes list to the URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root

 index.php/api2/Contacts

with the Content-Type header set to application/json, and the request body as (for example):

{"firstName":"John","lastName":"Smith","visibility":1,"email":"johnsmith@example.com"}

If creation of the contact is successful, the server should respond with status code 201 ("Created"), and the response should contain a Location header with the full URL (including protocol) of the newly created contact (in addition to all the attributes of the new contact). If for example the new contact's ID is 123, that URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root would be

 index.php/api2/Contacts/123.json

and a GET request to that URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root would elicit a response from the server whose body contains a JSON-encoded list of attributes.

URI Formats, Terminology and Conventions

Note, the above example, the URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root to which the POST request is sent (to create the contact) is referred to in this documentation as a base URI. Base URIs, when requested using the GET method, return a JSON-encoded array, each entry in the array corresponding to a record and being a dictionary of column:value pairs. So for example, if sending GET to the contacts model base URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root

 index.php/api2/Contacts

the response would look like this:

[...,{"email": "johnsmith@example.com","firstName": "John","lastName": "Smith",...},...]

Whenever a URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root points to an object or resource uniquely identified with a specific database record, that URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root is referred to as a direct URI. Direct URIs end in ".json" and respond to GET requests with JSON-encoded dictionary objects of column values for the record as it is in the database. So, the URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root in the above example (index.php/api2/Contacts/123.json) would respond with:

{"email": "johnsmith@example.com","firstName": "John","lastName": "Smith",...}

Direct URIs will almost always end in ".json", and base URIs will not. In general, the following convention applies almost universally within the API: If the URI ends in ".json", the resource will be a JSON-encoded dictionary object. Otherwise, it will be a JSON-encoded array. In the latter case, if each element of the array is a dictionary object, the dictionary objects should have uniform structure.

Access Credentials

To use the API, you will need to obtain X2Engine API credentials, which include a username and an API key. An X2Engine user with administrative privileges can get or set API keys in the Users module, by going to the edit page for that user. To summarize:

  1. As the administrator, go to the user management module. You'll find it under "Users"
  2. Click on the desired user
  3. Click "Update User"
  4. See the "API Key" field.

While there is a user in this section called "API User" you should not use it for this version of the API. That user exists to maintain backwards compatibility for a very old version of the API so that users who have set up API connectors with those endpoints will not have their code break. This user will not function with the current API and attempting to use it will generate a 403 error.

Explore the API Using Your Web Browser

Once you have API credentials, you can examine the web API using your web browser by making GET requests to locations within index.php/api2 (simply by typing them into your browser's location bar). You can get a nicer view of the data returned by the server by installing a JSON viewing plugin in your web browser. A recommended plugin for this purpose is JSONView, which is available for Firefox and for Google Chrome (it's an unofficial port, but the developer of the API and author of this article uses it).

Example 1: hello, world

Try visiting the following URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root within X2Engine:

 index.php/api2/appInfo.json

Initially you will be prompted to enter the username and password to complete authentication; enter the API key corresponding to the user in the password field. The above URL should respond with a JSON string containing some basic info about the X2Engine application.

Example 2: direct access

You can get the ID of any given account record by going to it inside X2Engine as you normally would and examining the URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root. It should generally look something like this:

 index.php/accounts/32

or:

 index.php/accounts/id/32

In both of the above examples, the primary key value (id) of the record in question is 32. To view it in the API:

 index.php/api2/Accounts/32.json

Note how in the API, the first letter of "Accounts" in the direct URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root is capitalized. This is because active record data in the API is accessed not via specifying the module containing the active record class, or to which the class corresponds, but by specifying the actual class name to use when accessing (or querying) data.

Example 3: querying

 index.php/api2/Actions?_order=-id&_limit=3

This will show you the last 3 action records (i.e. emails, call logs, to-do's) created in the system (which the current acting API user has permission to view), in descending order of their primary key values (column "id"). If you have no action records in your system, you should receive an empty array.

Prerequisites for API Applications

When writing an application to interface with X2Engine via the API, it is required or strongly recommended that your language/coding environment of choice:

  • Have a JSON parsing and encoding library available
  • Have a library for making HTTP requests which can:
    • Set request headers
    • Parse response headers and read the response status code
    • Natively support requests using HTTP Basic Auth for access
    • Read responses even when the response code is not in the "success" category (2xx)
    • Make POST, PATCH/PUT and DELETE requests
  • Can access the network

Many high-level languages, such as Perl, PHP, Python and Ruby, meet these requirements. The specific usage of these languages is beyond the scope of this article; you will need to refer to the documentation of the library/libraries in use.

It is expected in the near future that a growing number of official API access classes (each in a different programming language) will be available for quick and easy development of API applications.

Authentication

As stated before, the API uses "HTTP Basic" authorization. Many HTTP client libraries will have native methods of setting headers for HTTP basic auth. It is recommended that you use such a method for authentication and read the relevant documentation, rather than setting headers manually, as that will save time and more likely lead to quicker success.

In all other cases, to authenticate and access the API using this method, each request must include the Authorization header. To compose the header, first combine the username and API key into a single string with a colon, as:

 {username}:{userKey}

Next, obtain the string in Base-64 encoding. For example, username:password in base 64 is dXNlcjpwYXNzd29yZA==. Thus, the resulting header would look like this:

 Authorization: Basic dXNlcjpwYXNzd29yZA==

See also the the Wikipedia article on this topic.


Caveats

Note, firstly: because headers are sent without any built-in encryption, it is highly recommended that you use the API over HTTPS (HTTP encrypted using TLS[[wikipedia:Transport Layer Security]] a method of connecting to a remote network host that encrypts traffic on any given network protocol that uses it.), if available, or make API requests only within a network where packets are not easily intercepted.

Furthermore, if you have password-protected any web directories that contain X2Engine, you will need to make a "Satisfy any" exception for URIs within the API, or clients may not be able to authenticate.

Model-based Input and Output

Most of the modules in X2Engine (i.e. Contacts) will each have a corresponding active record model. This model is what is customized whenever adding a custom field. It is essentially a PHP class that is a child of X2Model (see: X2Model and Dynamic Fields for more information). Almost all API-based functions involving such data objects will contain the name of that class in the URL, i.e.

 index.php/api2/Accounts
 index.php/api2/Contacts/135/Actions
 index.php/api2/Contacts/112.json

In general, the base URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root for functions pertaining to models is

 index.php/api2/{_class} 

where {_class} is the class. The direct URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root is generally:

 index.php/api2/{_class}/{_id}.json

where {_id} is the ID of the record to access.

Getting Model Classes

From the following URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root one can obtain a list of models:

 index.php/api2/models

Each model in the list is a dictionary containing:

modelName The class of the model
title The human-readable name of the model
attributes An array of attribute names

To include only fully-supported classes versus partially-supported model classes, include the "partialSupport" parameter and have it equal zero:

 index.php/api2/models?partialSupport=0

Fully-Supported Model Classes

As of this writing, X2Engine by default has the following model classes that are fully supported in the API — meaning, all or nearly all of the most essential functionality that is possible in X2Engine via a web browser, in terms of manipulation of persistent data storage, is also possible via the API.

  • Accounts
  • BugReports
  • Contacts
  • Campaign
  • Opportunity
  • Product
  • Services

Additionally, any custom modules will also have corresponding active record models fully supported by the API. This should usually be the same name as the module, but without spaces and the first letter always capitalized. If in doubt, to find the model class corresponding to a given module (i.e. a custom module), look in the "models" sub-directory of that module. The name of the file excluding the extension (.php) should be the name of the class. For instance, in the file protected/modules/contacts/models/Contacts.php there should be the following line:

class Contacts extends X2Model {

Partially-Supported Models

Manipulation of data using the following models (or certain aspects of the following models) is not fully supported in the API as of this writing — meaning, while most operations are possible, some important functionality is not yet possible:

Actions Actions can be created, updated, viewed, queried and deleted as all other model types. However:
  • Action completion and backdating (setting or overwriting the completion date) is not yet supported unless one enables "raw input" (Platinum Edition only), because completeDate is a "read-only" field
  • Associated "action timer" records (applicable only to Professional/Platinum edition) cannot be accessed or manipulated
  • Comparisons based on action description in queries:
    • They are unaffected by options that control comparisons; the comparison is un-escaped "LIKE" and the criteria combination operator is effectively "AND" (_partial=1&_escape=0).
    • They will also be very slow; effectively, the comparison in the query is being performed on a TEXT column in a joined table

The limitations of filtering by action description are endemic to how the "field" is actually stored in a different database table than the contacts, and the type of the column is TEXT.

Docs Can be accessed/manipulated as with other models. However, "edit permissions" do not work the same way as they do in the application.
Groups Groups can be queried, viewed and created, albeit only by an administrative user, and in a very limited capacity. Users cannot be added to or removed from groups; manipulating the associated "group-to-user" data is not yet possible.
Media Media records can be accessed and manipulated as with any other model, but the API does not yet support directly uploading files to go with them.
Quote Quote records can be accessed and manipulated, but associated "line items" data cannot be viewed or manipulated.
X2Leads This data type can be fully accessed and manipulated, but there is not yet any built-in action available for directly converting a lead to an opportunity.
X2List This data type (contact lists in X2Engine) can be accessed and manipulated, but the actual contents of the list (whether dynamic or static) cannot.

Creating, Viewing Updating and Deleting Records

To create a record, perform a POST request to the base URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root for the model, i.e.

 index.php/api2/Contacts

to create a contact. As mentioned in the example in the #Introduction, the body of the request must be a JSON-encoded library of attributes to set in the model, and the Content-Type header must be set to application/json.

To view, update or delete a record, first determine its direct URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root within the API, as set in the Location header if creation was successful, or as determined via its class and id, i.e.

 index.php/api2/Contacts/33.json

to specify a contact record with its id equal to 33.

To update a record, send a PUT or PATCH request to a direct URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root, and set the body and Content-Type header as one would in a POST request to create such a record. Finally, to delete the record, send a DELETE request to that same direct URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root. It is not necessary in the case of deletion to include a body or set the Content-Type header.

If you need to retrieve the record count of any of the supported classes, then you can append the "count" operation to the URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root of a GET request. For example, to retrieve the number of Contacts in the system, one would call the URL:

 index.php/api2/Contacts/count

This can also be combined with the _findBy directive to allow count of models matching specific criteria, i.e., to count the number of Contacts named "Thaddeus" the respective API call would be:

 index.php/api2/Contacts/count/by:firstName=Thaddeus.json

Direct Manipulation by Attributes

Given a set of uniquely-identifying attribute names and values, it is possible to directly access and manipulate an existing X2Model-based record by without first querying it. The direct URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root for this use case is:

 index.php/api2/{_class}/by:{_findBy}.json

where the query parameter {_findBy} is a list of key and value pairs formatted as key1=value1;key2=value2.

For example: provided the email address "james@example.com" and first name "James" uniquely identify the contact with ID of 457, the following two direct access URIs are equivalent:

 index.php/api2/Contacts/by:email=james@example.com;firstName=James.json
 index.php/api2/Contacts/457.json

Furthermore, note what happens in the following scenarios:

If the set of attributes (i.e. email address) is not unique to a single record: the find-by-attributes direct URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root will return with a 300 status and an error object containing the two special properties: queryUri, the URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root to query for records by the attributes given, and: directUris, a list containing the direct URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root of each matching record.

If no contact matches the attributes given: the URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root will respond with a 404 status.

Using the first matching record

If one wants to forcefully select and use the first record matching the attributes, regardless of how many match, append the _useFirst parameter and set equal to 1, i.e.

 index.php/api2/Contacts/by:email=james@example.com;firstName=James.json?_useFirst=1

Working With Associated Actions

The Actions model is unique in that it can be "associated" with almost any other type of model record. Actions records comprise all "history" items on any given record, i.e. emails, calls logged, notes, calendar events and also plain actions. Actions that have an association with another model can be used via clean URIs that point to "within" the associated model.

URI Formats

To view/query all actions associated with an active record model of class {_class} and id {_id}, use the following base URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root:

 index.php/api2/{_class}/{_id}/Actions

For instance, one could find all actions, including emails, on contact id=1233, via:

 index.php/api2/Contacts/1233/Actions

To view an individual action of id {_actionId}, one can use this direct URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root:

 index.php/api2/{_class}/{_id}/Actions/{_actionId}.json

Creating, Updating and Deleting Actions

Similar to the the basic model access API function, PATCH, POST, PUT and DELETE requests can be sent to associated action URIs to create/modify/delete records just as those URIs can also be used to view data. POST to the base URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root,

 index.php/api2/{_class}/{_id}/Actions

to create a new action associated with model record of class {_class} and id {_id}. Then, using the direct URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root,

 index.php/api2/{_class}/{_id}/Actions/{_actionId}.json

PATCH/PUT/DELETE requests can be used to modify/delete an existing associated action record.

Metadata Functions

There is "structural" metadata that one can retrieve through the API to more effectively determine how to proceed with future API transactions. There are also some functions in the API that pertain to functionality associated with model records, but do not modify data within the records themselves, and create associated metadata.

Fields

One can access field metadata for a given model class by using the following base URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root (which supports querying):

 index.php/api2/{_class}/fields

One can directly access the metadata of a field by its name via the following direct URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root format:

 index.php/api2/{_class}/fields/{_fieldName}.json

For instance, this URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root

 index.php/api2/Contacts/fields/leadSource.json

would respond with:

{"id":"88", "modelName":"Contacts", "fieldName":"leadSource", "attributeLabel":"Lead Source", "modified":"0", "custom":"0", "type":"dropdown", "required":"0", "uniqueConstraint":"0", "safe":"1", "readOnly":"0", "linkType":"103", "searchable":"0", "relevance":"", "isVirtual":"0","defaultValue":null,"keyType":null}

Field-Level Permissions

Any given user's access level to a field can be controlled by assigning them to a role and then setting field permissions for that role via Manage Roles under Admin.

A GET to the following will respond with a dictionary of active record model attributes, each value corresponding to field-level access permissions for that field granted the current acting API user.

 index.php/api2/{_class}/fieldPermissions.json

For example, as the default administrator, for model Contacts, getting the following:

 index.php/api2/Accounts/fieldPermissions.json

will respond with:

{"leadtype":2, "leadSource":2, "leadstatus":2, "leadDate":2, "leadscore":2, "interest":2, "dealvalue":2, "closedate":2, "rating":2, "dealstatus":2, "name":2, "nameId":1, "id":1, "website":2, "type":2, "visibility":2, "annualRevenue":2, "phone":2, "tickerSymbol":2, "address":2, "city":2, "state":2, "country":2, "zipcode":2, "parentAccount":2, "primaryContact":2, "employees":2, "assignedTo":2, "createDate":1, "description":2, "lastUpdated":1, "lastActivity":1, "updatedBy":1}

For each of these entries, the number associated with the field indicates the following:

0 No access; when directly accessing a model record, the response data will not include the content of that field
1 Read-only access; responses will include the content of that field, but any input to that field will be discarded
2 Read/write access. The current API user can both view and edit data in the field.

Zapier-Friendly Fields

There is similarly a dynamic fields API action that returns an array of fields intended for use by Zapier. The object format returned from this action is described in Action Fields (Custom) in the Zapier developer documentation.

The base URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root is:

 index.php/api2/{_class}/zapierFields

This action is generally useful for API usage insofar as it will also return ranges of acceptable values for each field, if applicable, in the choices property. For example, if the type of a field is dropdown, the dropdown options will be returned in the choices property of each element in the returned array. Similarly, if the type of the field is assignment, the element's choices property will include a list of users and groups. Furthermore, it has the ability to easily select only fields of a given permission level or greater. For this, use the _permissionLevel parameter. For example, to get all writable fields in Contacts:

 index.php/api2/Contacts/zapierFields?_permissionLevel=2

(see #Field-Level Permissions for more information)

Unfortunately, the action does not support querying, although it does not need to for its intended purpose.

Dropdowns

Note, to get a list of acceptable values for a given model in cases when the field type is not dropdown, use the choices property of data returned by #Zapier-Friendly Fields.

Some fields, i.e. lead source in contacts, are of type "dropdown"; their content is intended to be either blank, or an option in a static list. Dropdown menus can be queried at base URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root

 index.php/api2/dropdowns

Dropdown fields can also be directly accessed via

 index.php/api2/dropdowns/{_id}.json

To find out if a field is of type dropdown, and which dropdown menu it uses: the value for type in the field's metadata record should be "dropdown", and the linkType field should contain the dropdown's ID. So, using the example in #Fields, the corresponding dropdown record is at

 index.php/api2/dropdowns/103.json

which contains:

{"id":"103", "name":"Lead Source", "options":{"None":"None", "Google":"Google", "Facebook":"Facebook", "Walk In":"Walk In"}, "multi":"0", "parent":null, "parentVal":null}

Note, for convenience's sake the "options" field won't be returned verbatim as the raw JSON (that's how the options are stored). Rather, that field will be decoded into a sub-dictionary of the overall object.

Relationships

It is possible to create, view, and delete relationships between supported API models in X2Engine via the API.

URI Formats

Relations functionality is in general accessed within the following base URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root:

 index.php/api2/{_class}/{_id}/relationships

So, to view all relationships going to or from account 131:

 index.php/api2/Accounts/131/relationships

To view the contents (related model class and ID) of a specific relationship on the account (let's say the relation record has its id=304281 for instance):

 index.php/api2/Accounts/131/relationships/304281.json

The Relationships active record model has the following attributes that can be used in queries:

id
Unique numeric identifier for the relationship
firstType, firstId
The model class and record ID at one end of the relationship, respectively
secondType, secondId
The model class and record ID at the other end of the relationship, respectively

For instance, to find all outgoing relationships with Accounts to contact id=126:

 index.php/api2/Contacts/126/relationships?secondType=Accounts

Adding/Removing Relationships

To create a new relationship, sent POST to the base URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root.

To remove a relationship, send DELETE to the direct URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root of the record, i.e. index.php/api2/Accounts/131/relationships/304281.json in the earlier example.

Tags

All basic, fully-supported models in X2Engine should support tagging. Tags cannot be individually modified, but can only be created, viewed, queried and removed, in order to enforce preservation of the important metadata such as who added the tag and at what date.

URI Formats

Tags on a given model record can be retrieved via GET at the following base URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root:

 index.php/api2/{_class}/{_id}/tags

The response should be a flat array of tag names. For example, if account 51 has tags "#customer" and "#local", sending GET to the following URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root

 index.php/api2/Accounts/51/tags

will yield:

["#customer","#local"]

To view more extensive metadata of the tag, i.e. who added the tag and at what date:

 index.php/api2/{_class}/{_id}/tags/{_tagName}.json

i.e.

 index.php/api2/Accounts/51/tags/local.json

The above will return a dictionary of x2_tags column names and values. Note, the tag name in the URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root must either exclude the preceding hash mark or include it via its corresponding URL encoding sequence, %23. This is because the hash mark is a special character in the HTTP protocol and will interfere with proper resolution of the URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root. Using the above example:

 index.php/api2/Accounts/51/tags/%23local.json

That URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root will return the exact same data as the previous URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root; they are considered equivalent.

Adding Tags to a Record

Adding tags also utilizes that same URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root scheme as with viewing tags. To add one or more tags, send them as string elements in a flat JSON-encoded array via POST to that location. For example, to use the previous example, one can apply the tags "#customer" and "#local" from "record 51" to record 52 by POST-ing the same JSON returned from a GET at:

 index.php/api2/Accounts/51/tags

to:

 index.php/api2/Accounts/52/tags

Removing Tags

To delete a tag, send a DELETE request to the direct viewing location of the tag. So, for instance, to delete "#local" from account 51, send DELETE to index.php/api2/Accounts/51/tags/local.json

Querying Data

Almost any "base" URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root, which can be used for accessing all records of a type or for creating new records of a type, can also be used for querying records of that type. Responses to queries (and GET requests to these URIs in general) will always be JSON-encoded arrays of records, each record represented as an attribute dictionary.

Options for searching, as well as attributes to match column values against (for filtering), are all specified as query parameters (a.k.a. "get parameters"). The search options, to protect against name collisions with column names, each have names that begin with an underscore, i.e. _order.

General Search Option Parameters

In queries, one can use a variety of advanced options that include sorting, pagination, partial matching, and in some cases tags.

Parameter Meaning Default Usage
_escape Wildcard usage 1 Set 0 in parameters to allow characters like "%" and "_" to be used as SQL wildcards in search filter attributes. Controls the resultant value of the $escape argument sent to CDbCriteria.compare() in configuring the search. Note, to perform wildcard searches properly, the parameter _partial must be set to 1 so that CDbCriteria uses LIKE for the value comparison. For info on SQL wildcards and comparisons, see: MySQL: String Comparison Functions
_limit Page size may vary Set to a number to control the maximum number of records to include in the results of the search. The default and maximum page size is 1000, and in Platinum Edition this default amount is user-configurable.
_or Use "OR" operator 0 Set to 1 to make the operator used for combining search criteria OR instead of the default, AND.
_order Sorting none Set equal to the name of a column to sort by, optionally prefixed with a plus or minus sign to specify ascending or descending order (respectively). For example, _order=-leadScore in a Contacts query sorts contacts by lead score with the highest-scored contacts first. Note, sorting applies not only to the current page but to the data set spanning all pages. Thus, if the total number of possible results is larger than the page size, the set of results shown in the current page will be affected.
_page Page number 0 The zero-starting-point page number of the data. Useful for when the query would return more results than the page size specified.
_partial Partial match 0 Set to 1 to enable partial matching in search filters. This parameter controls the value sent to CDbCriteria.compare() as the $partialMatch argument. If true, the LIKE comparison will be used; otherwise, full equality will be used as the comparison.
_tagOr Inclusive tag search 0 When performing tag-based searches, set to 1 to indicate to include records with any of the specified tags rather than all of them.
_tags Has tag(s) none When querying tag-supporting X2Model sub-classes (meaning, those which can be tagged), this can be included and set to a comma-delineated list of tags. This will restrict results to records having all of said tags, or if _tagOr is enabled, any of the tags. Note, tag names should not contain their preceding "#" (or, at least should not contain it without URL-encoding it) because "#" is a special character in the HTTP protocol that will interfere with how your request to the server is interpreted.

Adding Query Parameters

Appending option parameters proceeds as it would for any script that can receive URL-encoded variables via the request: follow the base URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root with a question mark, and delineate [name]=[value] parameter declarations with ampersands (note: this might be different, depending on your web server's configuration, but the nearly-ubiquitous default is ampersand-delineation). For example:

 index.php/api2/Contacts?_limit=10&firstName=Harry&lastName=P%25&_partial=1&_escape=0&_order=+lastName

This will return the first ten contacts out the list of contacts having first name "Harry" and last name beginning with "P", sorted alphabetically by last name.

Searching For Models By Tag

In addition to the _tags search option, there is a "pretty" dedicated base URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root format for tag searching:

 index.php/api2/tags/{_tags}/{_class}

So, for instance, to find all contacts with the tags "#customer" and "#important":

 index.php/api2/tags/customer,important/Contacts

The above is equivalent to

 index.php/api2/Contacts?_tags=customer,important

Note, additional search parameters can also be included. For instance, to return the first ten most recently updated contacts with the above tags:

 index.php/api2/tags/customer,important/Contacts?_order=-lastUpdated&_limit=10

The reason for this is to express tags as categories, and thus in a loose sense "folders" in which one would find records.

Web Hooks

To develop real-time integration, that is to say, to have data sent from X2Engine to a third-party service immediately when a triggering event occurs, the best method is web hooks. Note, there is also the means of sending web requests to external URLs via the "Remote API Call" X2Flow action. For more information about this feature, see the X2Flow documentation for this action.

While said X2Flow action may suffice in many basic use cases, there are limitations to it that are addressed by web hooks:

  • Configuring X2Flow cannot be performed via the API
  • The action (making a web request) cannot be performed on a per-user basis (i.e. making a different request for each user)
  • The X2Flow user interface is not available in the open source edition of X2Engine

In cases where the remote end, which will receive data from X2Engine, can be modified with custom code, web hooks are a method of "subscribing" to events in X2Engine via the API. Whenever an event would happen in X2Engine, X2Engine will submit payload data to a return URL specified in the original webhook request, as JSON-encoded data in the request body.

Creating Web Hooks

To create a hook with an event that depends on a model type (i.e. contact updated vs. account updated), send a JSON-encoded list of hook attributes via POST to the following URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root:

 index.php/api2/{_class}/hooks

Or, to create a web hook associated with a generic event (that does not depend on model type), or a model of determined/unambiguous type (i.e. "Action Complete"):

 index.php/api2/hooks

The POST-ed JSON-encoded dictionary object should contain the following properties:

event An event name; see #Events Reference
target_url The remote URL to receive the payload
directPayload (optional): a 1 or 0 (or true/false). See #Interpreting Payload Data

Upon successful creation of a web hook, note that the server will respond with a 201 status. The body will be the JSON-encoded attributes of the new hook record, and the Location header of the response will be set to a URL that can be used to remove the web hook when it is no longer needed (see #Deleting Web Hooks).

Supported Event Names and X2Flow

Events for which web hooks can be created are all named after X2Flow trigger class names. Trigger classes (whose files are named after them, like all other class files) are stored in the directory

 protected/components/x2flow/triggers

In fact, any time that X2Flow::trigger is called, a corresponding call to ApiHook::runAll is also made, to execute all web hooks associated with that trigger event. The payload that is sent for all web hooks corresponding to that event is based on the value of the $params argument that is sent to X2Flow::trigger. In all cases, the payload is first converted to a pure array, i.e. not containing any objects or resource handles, so that it can be JSON-encoded and sent to the web hook target URL. The exact payload data will differ depending on the action; see "#Interpreting Payload Data" (coming soon) for further information.

Interpreting Payload Data

When you create a hook, you will have the option of setting its directPayload property to 1. A value of 0/false (the default value) for this field implies that if one of the trigger parameters is named "model" and is a subclass of X2Model (i.e. contact, account, opportunity), the (JSON-encoded) payload data will contain a property resource_url pointing to the URL on X2Engine of that model record. Thus, upon receiving the webhook request from X2Engine, the client end should then make a GET request from that URL to retrieve the model part of the payload data. If, on the other hand, directPayload is set to 1/true, what will instead happen is that the model will be included in the payload's model property as a dictionary of attribute-value pairs.

Note, the two most common possible properties resource_url and model are mutually exclusive; which one if any will get included depends on the direcPayload, other properties of the payload include but may not be limited to the following:

The class of model (and thus the structure of data) that should be expected to come from any given web hook generally depends on the model class to which the event corresponds. For example, the model is of class Actions in an ActionCompleteTrigger event, but they could be any general record type (contacts, actions, accounts, etc.) in a RecordCreateTrigger event.

Events Reference

As of version 4.1.1, the following trigger events are available in X2Flow:

Event Description Payload
ActionCompleteTrigger An action has been marked as complete model/resource_url: An action; user: username of the user who completed the action
ActionOverdueTrigger An action is overdue (cron[[wikipedia:Cron]]: a job scheduler for UNIX-like operating systems required) model/resource_url: an action; duration: the amount of time that has passed since the due date of the action
ActionUncompleteTrigger An action has been marked as uncomplete model/resource_url: An action; user: username of the user who marked the action as uncomplete
CampaignEmailClickTrigger A tracking link in a campaign has been clicked model: the contact who clicked the link in their campaign email; campaign: Name of the email campaign
CampaignUnsubscribeTrigger A contact has unsubscribed from email campaigns model: the contact; campaign: Name of the email campaign
CampaignWebActivityTrigger (Professional Edition only) A contact who was part of a campaign is visiting your website model/resource_url: the contact; campaign: Name of the email campaign; url: URL of the page that the contact is visiting
NewsletterEmailClickTrigger (Professional Edition only) A newsletter subscriber has clicked a tracking link item: The list item record ({"emailAddress":<email address>,"opened":<timestamp opened>,"clicked":<timestamp clicked>,"unsubscribed":<has unsubscribed>}); email: email address of subscriber; campaign: name of the newsletter campaign; url: URL visited by the subscriber
NewsletterEmailOpenTrigger (Professional Edition only) A newsletter subscriber has opened an email item: The list item record ({"emailAddress":<email address>,"opened":<timestamp opened>,"clicked":<timestamp clicked>,"unsubscribed":<has unsubscribed>}); email: email address of subscriber; campaign: name of the newsletter campaign
NewsletterUnsubscribeTrigger (Professional Edition only) A newsletter subscriber has unsubscribed item: The list item record ({"emailAddress":<email address>,"opened":<timestamp opened>,"clicked":<timestamp clicked>,"unsubscribed":<has unsubscribed>}); email: email address of subscriber; campaign: name of the newsletter campaign
RecordCreateTrigger A record of one of the main types (contact, action, account, opportunity, etc.) has been created model/resource_url: The data that was inserted
RecordDeleteTrigger A record of one of the main types (contact, action, account, opportunity, etc.) has been deleted model/resource_url: The data that was inserted
RecordTagAddTrigger A record has been tagged model/resource_url: The record that was tagged; tags: an array of strings (tags) that were added.
RecordTagRemoveTrigger Tags have been deleted from a record model/resource_url: The record whose tags were changed; tags: an array of strings (tags) that were removed
RecordUpdateTrigger A record of one of the main types (contact, action, account, opportunity, etc.) has been updated model/resource_url: The data that was updated
RecordViewTrigger A record of one of the main types (contact, action, account, opportunity, etc.) has been viewed model/resource_url: The data that was viewed
TargetedContentRequestTrigger (Professional Edition Only) Targeted content is being accessed on your website model/resource_url: The contact on your website; url: the URL being viewed; flowId: internal parameter (not of much use outside X2Engine)
UserLoginTrigger A user has logged in user: the username of the user who has logged in
UserLogoutTrigger A user has logged out user: the username of the user who has logged out
WebActivityTrigger (Professional Edition Only) A contact is viewing your website model/resource_url: the contact; url: the URL being viewed; probability (Platinum Edition only) percentage confidence of browser-fingerprinting-based match between a web client and a contact
WebleadTrigger A new web lead has come in model/resource_url: the contact associated with the form submission; tags: a list of tags added to the contact through the submission, if applicable
WorkflowCompleteStageTrigger A process stage has been completed workflow: The workflow template model (has properties name, isDefault, lastUpdated and colors); model/resource_url: the record (i.e. Opportunity/Contact) for which the stage was completed; workflowId: internal use (not very useful outside X2Engine); stageNumber: the number of the stage in the process that was completed.
WorkflowCompleteTrigger A process has been fully completed workflow: The workflow template model (has properties name, isDefault, lastUpdated and colors); model/resource_url: the record (i.e. Opportunity/Contact) for which the stage was completed; workflowId: internal use (not very useful outside X2Engine)
WorkflowRevertStageTrigger A process stage has been reverted. Same as WorkflowCompleteStageTrigger
WorkflowStartStageTrigger A process stage has been started Same as WorkflowCompleteStageTrigger
WorkflowStartTrigger A process has been started Same as WorkflowCompleteTrigger

Deleting Web Hooks

Given the numeric identifier of a web hook, it can be deleted by sending a DELETE to a URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root formatted as follows:

 index.php/api2/hooks/:{_id}

So, for a web hook with id=74:

 index.php/api2/hooks/:74

The full URL should have been given to the API client in the Location header in the response to the original web hook creation request. Upon successful deletion, the server will respond with status code 204.

Interpreting Server Responses

HTTP Response Codes

It is important to be able to read and interpret status codes (and for that matter, response headers) because in all success scenarios, the API does not respond with data envelopes. By this it is meant the act of wrapping a data model's attributes inside another array containing metadata about the status of the request. This is in effort to streamline and make more elegant code that handles response data. It is also for consistency's sake. A contacts model accessed as a resource object with name ending with .json is expected to be that contact, and not rather an array with server response info or other metadata.

In general, the meanings of response codes closely or exactly follow the formal definitions as defined in RFC2616, as well as the informal definitions of unconventional status codes (See wikipedia:List of HTTP status codes). The following table lists each of the possible status codes that the API will respond with, the contexts in which they would appear, and what they indicate.

Code Request type or usage scenario Meaning
Success (2XX)
200 GET, PATCH, PUT

Also, when adding tags via POST

OK. General success status
201 POST Created. A record was created; see the value of the Location response header for its URL in the API
204 DELETE No content. An action was completed but the server does not need to return any content. The body of the response will be empty.
Redirection (3XX)
300 When using the "find by attributes" direct access URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root Multiple choices. There criteria specified for direct access (as opposed to querying) match more than one record.
303 GET

When requesting an object that exists but is not actually associated with the record specified in the request

See other. The requested resource is somewhere else. The Location header should contain the correct, full URL to the resource.
Client Error (4XX)
400 All request methods/actions Invalid request. General status code for when something is missing, malformed or incorrect in the request headers/body.
401 All request methods/actions. Authentication failure or missing authentication credentials.
403 All request methods/actions. Forbidden. This may be because the user in API authentication does not actually have permission in X2Engine to perform the specified action. In Platinum Edition, this code can also indicate that the IP address of the API client has been blocked.
404 All request methods/actions. Not found, or invalid URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root. It is used whenever a specified record to retrieve directly does not exist, but also as a catch-all for a location that the API was not configured to interpret.
405 All request methods/actions Method not allowed. The URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root is not malformed, but the method of the request being sent to the server is not permitted. An example would be sending a POST request, which is intended for creating new records, to the URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root of an existing record, or sending a DELETE/POST/PUT request to a "read-only" resource.
408 All methods; server-generated Request timeout. This code is not as of this writing not produced by the API; it might be returned by the web server itself.
413 All methods; server-generated Request entity too large. This code is not as of this writing not produced by the API; it might be returned by the web server itself.
415 PATCH, POST, PUT Unsupported media type. As of this writing, this happens only whenever the request is sent with a body and the Content-Type header is not set to "application/json"
422 PATCH, POST and PUT

When creating or updating a record

Unprocessable entity. This always indicates a data validation error when attempting to set fields of and save an active record model. The client is expected to resolve these issues and resubmit the data with all of the fields formatted in such a way that it is acceptable.
429 Platinum Edition only

All request methods/actions

Too many requests. When rate limiting is enabled in the API settings, the server will use this code to indicate that the API client has been making requests to the API too frequently. When this status is sent, the response should also contain a Retry-After header specifying the number of seconds to wait before trying again.

There is one exception to this, however: when attempting to create a web hook for a given user, event and model name, if the hook limit has already been reached for a user, event and model name, a 429 without Retry-After would be sent, and this implies that no more hooks for that combination should be created.

Server Error (5XX)
500 All request methods/actions Internal server error. General status for when something isn't right on the server. PHP and database errors will produce this status code.
501 All request methods/actions Not implemented. The API should use this code to denote that a given method, action, etc. is not yet available, but may be in the future.
503 Professional and Platinum Editions

All request methods/actions

Unavailable. X2Engine and/or its API service has been disabled/locked by an administrator.

Error Objects

In all error responses produced by the API and not by the server itself, the body of the response will be a JSON containing metadata about the error and the response. This is for compatibility with less-than-satisfactory client libraries which cannot read the actual response code or headers, but might be able to read the response body when the code is not in the success (2XX) range. In such cases, the response will be a JSON-encoded object with at least the following properties:

httpHeaders A dictionary of HTTP headers that were set deliberately by the API (as opposed to automatically, by the web server software) in the response.
message A general message about what happened and why. This will in most cases also be saved in the API log.
error Boolean true/false; will generally be true.
status The HTTP status code that was sent in the response header

In some cases, the response JSON may include the following additional properties:

errors A dictionary of validation errors encountered when attempting to save an active record model; included with responses of status code 422.

The structure will be indexed by attribute name, each entry containing a list of applicable validation errors. It is essentially the resulting value of the CModel.errors property.