Class: Api

Api


new Api(args)

The SugarCRM JavaScript API allows users to interact with SugarCRM instance via its REST interface.

Most Sugar API methods accept callbacks object:

{
    success: function(data) {},
    error: function(error) {},
    complete: function() {},
}
Parameters:
Name Type Description
args Object

The configuration parameters for the instance.

Properties
Name Type Argument Default Description
serverUrl string <optional>
'/rest/v10'

Sugar REST URL end-point.

platform string <optional>
''

Platform name ("portal", "mobile", etc.).

keyValueStore Object <optional>

Reference to key/value store provider used to read/save auth token from/to. It must implement three methods:

  set: void function(String key, String value)
  get: String function(key)
  cut: void function(String key)

The authentication tokens are kept in memory if the key/value store is not specified.

timeout number <optional>

Request timeout in seconds.

defaultErrorHandler function <optional>

The default error handler.

clientID string <optional>
'sugar'

The clientID for oAuth.

disableBulkApi boolean <optional>
externalLoginUICallback function <optional>

The callback to be called if external login is activated.

Members


clientID :string

Client Id for oAuth.

Type:
  • string

debug :boolean

Flag indicating if API should run in debug mode (console debugging of API calls).

Type:
  • boolean

defaultErrorHandler :function

Default fallback HTTP error handler. Used when api.call is not supplied with an error: function in callbacks parameter.

Type:
  • function

serverUrl :string

URL of Sugar REST end-point.

Type:
  • string

timeout :number

Request timeout (in milliseconds).

Type:
  • number

Methods


abortRequest(id)

Aborts a request by ID.

Parameters:
Name Type Description
id string

Request ID


buildFileURL(attributes [, options])

Builds a file resource URL.

The attributes hash must contain the following properties:

{
    module: module name
    id: record id
    field: Name of the file field in the given module (optional).
}

Example 1:

var url = app.api.buildFileURL({
   module: 'Contacts',
   id: '123',
   field: 'picture'
});

// Returns:
'http://localhost:8888/sugarcrm/rest/v10/Contacts/123/file/picture?format=sugar-html-json&platform=base'

The field property is optional. If omitted the method returns a URL for a list of file resources.

Example 2:

var url = app.api.buildFileURL({
   module: 'Contacts',
   id: '123'
});

// Returns:
'http://localhost:8888/sugarcrm/rest/v10/Contacts/123/file?platform=base'
Parameters:
Name Type Argument Description
attributes Object

Hash with file information.

options Object <optional>

URL options hash.

Properties
Name Type Argument Description
htmlJsonFormat boolean <optional>

Flag indicating if sugar-html-json format must be used (true by default if field property is specified).

passDownloadToken boolean <optional>

Flag indicating if download token must be passed in the URL (false by default).

deleteIfFails boolean <optional>

Flag indicating if related record should be marked deleted:1 if file operation unsuccessful.

keep boolean <optional>

Flag indicating if the temporary file should be kept when issuing a GET request to the FileTempApi (it is cleaned up by default).

Returns:

URL for the file resource.

Type
string

buildURL(module, action [, attributes] [, params])

Builds URL based on module name action and attributes of the format rooturl/module/id/action.

The attributes hash must contain id of the resource being actioned upon for record CRUD and relatedId if the URL is build for relationship CRUD.

Parameters:
Name Type Argument Description
module string

module name.

action string

CRUD method.

attributes Object <optional>

object of resource being actioned upon, e.g. {name: "bob", id:"123"}.

params Object <optional>

URL parameters.

Returns:

URL for specified resource.

Type
string

bulk(data, callbacks [, options])

Calls API requests in bulk.

Parameters:
Name Type Argument Description
data Object

Object with requests array.

callbacks Object
options Object <optional>

Options object.

Returns:

The AJAX request.

Type
HttpRequest

call(method, url [, data] [, callbacks] [, options])

Makes AJAX call via jquery/zepto AJAX API.

Parameters:
Name Type Argument Description
method string

CRUD action to make (read, create, update, delete) are mapped to corresponding HTTP verb: GET, POST, PUT, DELETE.

url string

resource URL.

data Object <optional>

data will be stringified into JSON and set to request body.

callbacks Object <optional>

callbacks object.

options Object <optional>

options for request that map directly to the jquery/zepto Ajax options.

Returns:

AJAX request.

Type
HttpRequest

clearBulkQueue()

Clears the bulk call queue.


clearStateProperty(key)

Removes the given key from the current state.

Parameters:
Name Type Description
key string

collection(module, data [, params] [, callbacks] [, options])

Fetches a collection field.

Parameters:
Name Type Argument Description
module string

Module name.

data Object

object containing information to build the url.

Properties
Name Type Description
field string

The name of the collection field to fetch.

id string

The name of the bean id the collection field belongs to.

params Object <optional>

URL parameters.

callbacks Object <optional>

callback object.

options Object <optional>

request options.

Returns:

The AJAX request.

Type
HttpRequest

count(module [, data] [, callbacks] [, options])

Fetches the total amount of records for a given module.

Example 1:

app.api.count('Contacts', null, {
    success: function(data) {
        console.log('Total number of Contacts:' +
            data.record_count);
    }
});

Example 2:

app.api.count('Accounts', null,
    {
        success: function(data) {
            console.log('Total number of "B" Accounts:' +
                data.record_count);
        }
    },
    {
        filter: [{'name': {'$starts': 'B'}}]
    }
);

Example 3:

app.api.count('Accounts',
    {
        id: 'abcd',
        link: 'cases'
    },
    {
        success: function(data) {
            console.log('Total number of "B" cases related' +
                'to "abcd" account:' + data.record_count);
        }
    },
    {
        filter: [{'name': {'$starts': 'B'}}]
    }
);
Parameters:
Name Type Argument Description
module string

Module to fetch the count for.

data Object <optional>

Data object containing relationship information.

Properties
Name Type Argument Description
link string <optional>

The link module name.

id string <optional>

The id of the model.

callbacks function <optional>

Callback functions.

options Object <optional>

URL options hash.

Properties
Name Type Argument Description
filter Object <optional>

If supplied, the count of filtered records will be returned, instead of the total number of records.

Returns:

Result of Api#call.

Type
HttpRequest

css(Platform, ThemeName [, callbacks])

Makes a call to the CSS Api.

Parameters:
Name Type Argument Description
Platform string
ThemeName Object
callbacks Object <optional>

Callback object.

Returns:

The AJAX request.

Type
HttpRequest

enumOptions(module, field [, callbacks] [, options])

Loads an enum field's options using the enum API.

Parameters:
Name Type Argument Description
module string

Module name.

field string

Name of enum field.

callbacks Object <optional>

Callback object

options Object <optional>

Options object

Returns:

The AJAX request.

Type
HttpRequest

exportRecords(params, $el [, callbacks] [, options])

Triggers a file download of the exported records.

Parameters:
Name Type Argument Description
params Object

Download parameters.

Properties
Name Type Description
module string

Module name.

uid Array

Array of record ids to request export.

$el jQuery

JQuery selector to element.

callbacks Object <optional>

Various callbacks.

Properties
Name Type Argument Description
success function <optional>

Called on success.

error function <optional>

Called on failure.

complete function <optional>

Called when finished.

options Object <optional>

Request options hash.

  • passOAuthToken: Boolean flag indicating if OAuth token must be passed in the URL (true by default)
Returns:

The AJAX request.

Type
HttpRequest

favorite(module, id, favorite [, callbacks] [, options])

Marks/unmarks a record as favorite.

Parameters:
Name Type Argument Description
module string

Module name.

id string

Record ID.

favorite boolean

Flag indicating if the record must be marked as favorite.

callbacks Object <optional>

Callback object.

options Object <optional>

request options.

Returns:

The AJAX request.

Type
HttpRequest

file(method, data [, $files] [, callbacks] [, options])

Executes CRUD on a file resource.

Parameters:
Name Type Argument Description
method string

operation type: create, read, update, or delete.

data Object

object with file information.

{
  module: module name
  id: model id
  field: Name of the file-type field.
}
The field property is optional. If not specified, the API fetches the file list.

$files Object <optional>

jQuery/Zepto DOM elements that carry the files to upload.

callbacks Object <optional>

callback object.

options Object <optional>

Request options hash.

  • htmlJsonFormat: Boolean flag indicating if sugar-html-json format must be used (true by default)
  • iframe: Boolean flag indicating if iframe transport is used (true by default) See Api#buildFileURL function for other options.
Returns:

The AJAX request.

Type
HttpRequest

fileDownload(url [, callbacks] [, options])

Given a url, attempts to download a file.

Parameters:
Name Type Argument Description
url string

url to call

callbacks Object <optional>

Callback object

options Object <optional>

Options object

  • iframe: jquery element upon which to attach the iframe for download if not specified we must fall back to window.location.href

follow(module, id, followed [, callbacks] [, options])

Subscribe/unsubscribe a record changes.

Parameters:
Name Type Argument Description
module string

Module name.

id string

Record ID.

followed boolean

Flag indicates if wants to subscribe the record changes.

callbacks Object <optional>

Callback object.

options Object <optional>

request options.

Returns:

The AJAX request.

Type
HttpRequest

getDownloadToken()

Returns the current download token.

Returns:

The current download token.

Type
string

getMetadata( [options])

Fetches metadata.

Parameters:
Name Type Argument Description
options Objec <optional>

Options to decide what to get from the server.

Properties
Name Type Argument Default Description
types Array <optional>

Metadata types to fetch. E.g.: ['vardefs','detailviewdefs']

modules Array <optional>

Module names to fetch. E.g.: ['accounts','contacts']

callbacks Object <optional>

callback object.

public Object <optional>
false

Pass true to get the public metadata.

params Object <optional>

Extra params to send to the request.

Returns:

The AJAX request.

Type
HttpRequest

getMetadataHash()

Returns the current metadata hash.

Returns:

The current metadata hash

Type
string

getOAuthToken()

Returns the current access token.

Returns:

The current access token.

Type
string

getRefreshToken()

Returns the current refresh token.

Returns:

The current refresh token.

Type
string

getRequest(id)

Gets request by ID.

Parameters:
Name Type Description
id string

Request ID


getStateProperty(key)

Retrieve a property from the current state.

Parameters:
Name Type Description
key string
Returns:
Type
Mixed

getUserprefHash()

Gets the user preference hash for use in checking state of change.

Returns:

The user preference hash set from a /me response.

Type
string

handleExternalLogin(request, error, onError)

Handles login with an external provider.

Parameters:
Name Type Description
request HttpRequest

The request to trigger.

error Object

The error object with at least the payload property.

onError function

The function to call in case of Error during the login request.


info( [callbacks])

Fetches server information.

Parameters:
Name Type Argument Description
callbacks Object <optional>

callback object.

Returns:

The AJAX request.

Type
HttpRequest

isAuthenticated()

Checks if API instance is currently authenticated.

Returns:

true if authenticated, false otherwise.

Type
boolean

isAuthRequest(url)

Checks if the request is authentication request.

It could be either login (including token refresh) our logout request.

Parameters:
Name Type Description
url string
Returns:

true if this is an authentication request, false otherwise.

Type
boolean

isExternalLogin()

Returns true when using an external login provider.

Returns:

true when we are using an external login provider, false otherwise.

Type
boolean

isLoginRequest(url)

Checks if request is a login request.

Parameters:
Name Type Description
url string
Returns:

true if this is a login request, false otherwise.

Type
boolean

login(credentials [, data] [, callbacks])

Performs login.

Credentials:

    username: user's login name or email,
    password: user's password in clear text
Parameters:
Name Type Argument Description
credentials Object

user credentials.

data Object <optional>

extra data to be passed in login request such as client user agent, etc.

callbacks Object <optional>

callback object.

Returns:

The AJAX request.

Type
HttpRequest

logout( [callbacks])

Performs logout.

Parameters:
Name Type Argument Description
callbacks Object <optional>

Callback object.

Returns:

The AJAX request.

Type
HttpRequest

me(method [, data] [, params] [, callbacks])

Executes CRUD on user profile.

Parameters:
Name Type Argument Description
method string

Operation type: read or update (reserved for future use).

data Object <optional>

user Profile object.

params Object <optional>

URL parameters.

callbacks Object <optional>

Callback object.

Returns:

The AJAX request.

Type
HttpRequest

ping( [action] [, callbacks] [, options])

Pings the server.

The request doesn't send metadata hash by default. Pass false for "skipMetadataHash" option to override this behavior.

Parameters:
Name Type Argument Description
action string <optional>

Optional ping operation. Currently, Sugar REST API supports "whattimeisit" only.

callbacks Object <optional>

callback object.

options Object <optional>

request options.

Returns:

The AJAX request.

Type
HttpRequest

records(method, module, data [, params] [, callbacks] [, options])

Executes CRUD on records.

Parameters:
Name Type Argument Description
method string

operation type: create, read, update, or delete.

module string

module name.

data Object

request object. If it contains id, action, link, etc., URI will be adjusted accordingly. If methods parameter is 'create' or 'update', the data object will be put in the request body payload.

params Object <optional>

URL parameters.

callbacks Object <optional>

callback object.

options Object <optional>

request options.

Returns:

The AJAX request.

Type
HttpRequest

relationships(method, module, data [, params] [, callbacks] [, options])

Executes CRUD on relationships.

The data paramerer represents relationship information:

{
   id: record ID
   link: relationship link name
   relatedId: ID of the related record
   related: object that contains request payload (related record or relationship fields)
}
Parameters:
Name Type Argument Description
method string

operation type: create, read, update, or delete.

module string

module name.

data Object

object with relationship information.

params Object <optional>

URL parameters.

callbacks Object <optional>

callback object.

options Object <optional>

request options.

Returns:

The AJAX request.

Type
HttpRequest

resetAuth()

Clears authentication tokens.


resetState()

Clears the current API request state object.


Searches for specified query.

Parameters:
Name Type Argument Description
params Object

Properties.

Properties
Name Type Argument Description
q string

Query.

module_list string <optional>

Comma-separated module list.

fields string <optional>

Comma-separated list of fields.

max_num number <optional>

Max number of records to return.

offset number <optional>

Initial offset into the results.

callbacks Object

Hash with success and error callbacks.

Properties
Name Type Description
success function

Function called on success. Takes one argument.

error function

Function called on failure. Takes one argument.

options Object <optional>

Request options.

Returns:

The AJAX request.

Type
HttpRequest

setExternalLogin(flag)

Sets a flag indicating that external login prodecure is used.

This means that 401 errors would contain external URL that we should use for authentication.

Parameters:
Name Type Description
flag Boolean

Flag indicating if external login is in effect


setExternalLoginUICallback(callback)

Sets a function as external login UI callback.

Parameters:
Name Type Description
callback function

setRefreshTokenSuccessCallback(callback)

Sets the callback to be triggered after a token refresh occurs.

Parameters:
Name Type Description
callback

function to be called


setStateProperty(key, value)

Set a property of the current state. The current state will be attached to all api request objects when they are sent. Modifications to the state after the request is sent but before the request completes will not affect that requests state.

States should be used to track conditions or parameters that should be applied to all requests made regardless of their source.

Parameters:
Name Type Description
key string
value *

signup(contactData [, data] [, callbacks])

Performs signup.

TODO: The signup action needs another endpoint to allow a guest to signup

Parameters:
Name Type Argument Description
contactData Object

user profile.

data Object <optional>

extra data to be passed in login request such as client user agent, etc.

callbacks Object <optional>

callback object.

Returns:

The AJAX request.

Type
HttpRequest

triggerBulkCall(bulkId)

Begins a BulkAPI request. Previous uses of call() should have options.bulk set to an ID.

Calling triggerBulkCall with the same ID will combine all the previously queued requests into a single bulk call.

Parameters:
Name Type Description
bulkId number | string

The id of the bulk request.


updatePassword(password, password [, callbacks])

Updates password.

Parameters:
Name Type Argument Description
password Object

The new password

password Object

The new password

callbacks Object <optional>

Callback object.

Returns:

The AJAX request.

Type
HttpRequest

verifyPassword(password [, callbacks])

Verifies password.

Parameters:
Name Type Argument Description
password Object

The password to verify

callbacks Object <optional>

Callback object.

Returns:

The AJAX request.

Type
HttpRequest