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
|
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 idstring Request ID
-
buildFileURL(attributes [, options])
-
Builds a file resource URL.
The
attributeshash 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
fieldproperty 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 attributesObject Hash with file information.
optionsObject <optional>
URL options hash.
Properties
Name Type Argument Description htmlJsonFormatboolean <optional>
Flag indicating if
sugar-html-jsonformat must be used (trueby default iffieldproperty is specified).passDownloadTokenboolean <optional>
Flag indicating if download token must be passed in the URL (
falseby default).deleteIfFailsboolean <optional>
Flag indicating if related record should be marked deleted:1 if file operation unsuccessful.
keepboolean <optional>
Flag indicating if the temporary file should be kept when issuing a
GETrequest to theFileTempApi(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
attributeshash must containidof the resource being actioned upon for record CRUD andrelatedIdif the URL is build for relationship CRUD.Parameters:
Name Type Argument Description modulestring module name.
actionstring CRUD method.
attributesObject <optional>
object of resource being actioned upon, e.g.
{name: "bob", id:"123"}.paramsObject <optional>
URL parameters.
Returns:
URL for specified resource.
- Type
- string
-
bulk(data, callbacks [, options])
-
Calls API requests in bulk.
Parameters:
Name Type Argument Description dataObject Object with requests array.
callbacksObject optionsObject <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 methodstring CRUD action to make (read, create, update, delete) are mapped to corresponding HTTP verb: GET, POST, PUT, DELETE.
urlstring resource URL.
dataObject <optional>
data will be stringified into JSON and set to request body.
callbacksObject <optional>
callbacks object.
optionsObject <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 keystring -
collection(module, data [, params] [, callbacks] [, options])
-
Fetches a collection field.
Parameters:
Name Type Argument Description modulestring Module name.
dataObject object containing information to build the url.
Properties
Name Type Description fieldstring The name of the collection field to fetch.
idstring The name of the bean id the collection field belongs to.
paramsObject <optional>
URL parameters.
callbacksObject <optional>
callback object.
optionsObject <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 modulestring Module to fetch the count for.
dataObject <optional>
Data object containing relationship information.
Properties
Name Type Argument Description linkstring <optional>
The link module name.
idstring <optional>
The id of the model.
callbacksfunction <optional>
Callback functions.
optionsObject <optional>
URL options hash.
Properties
Name Type Argument Description filterObject <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 Platformstring ThemeNameObject callbacksObject <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 modulestring Module name.
fieldstring Name of enum field.
callbacksObject <optional>
Callback object
optionsObject <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 paramsObject Download parameters.
Properties
Name Type Description modulestring Module name.
uidArray Array of record ids to request export.
$eljQuery JQuery selector to element.
callbacksObject <optional>
Various callbacks.
Properties
Name Type Argument Description successfunction <optional>
Called on success.
errorfunction <optional>
Called on failure.
completefunction <optional>
Called when finished.
optionsObject <optional>
Request options hash.
- passOAuthToken: Boolean flag indicating if OAuth token must be passed in the URL (
trueby default)
Returns:
The AJAX request.
- Type
- HttpRequest
- passOAuthToken: Boolean flag indicating if OAuth token must be passed in the URL (
-
favorite(module, id, favorite [, callbacks] [, options])
-
Marks/unmarks a record as favorite.
Parameters:
Name Type Argument Description modulestring Module name.
idstring Record ID.
favoriteboolean Flag indicating if the record must be marked as favorite.
callbacksObject <optional>
Callback object.
optionsObject <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 methodstring operation type: create, read, update, or delete.
dataObject object with file information.
{ module: module name id: model id field: Name of the file-type field. }Thefieldproperty is optional. If not specified, the API fetches the file list.$filesObject <optional>
jQuery/Zepto DOM elements that carry the files to upload.
callbacksObject <optional>
callback object.
optionsObject <optional>
Request options hash.
- htmlJsonFormat: Boolean flag indicating if
sugar-html-jsonformat must be used (trueby default) - iframe: Boolean flag indicating if iframe transport is used (
trueby default) See Api#buildFileURL function for other options.
Returns:
The AJAX request.
- Type
- HttpRequest
- htmlJsonFormat: Boolean flag indicating if
-
fileDownload(url [, callbacks] [, options])
-
Given a url, attempts to download a file.
Parameters:
Name Type Argument Description urlstring url to call
callbacksObject <optional>
Callback object
optionsObject <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 modulestring Module name.
idstring Record ID.
followedboolean Flag indicates if wants to subscribe the record changes.
callbacksObject <optional>
Callback object.
optionsObject <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 optionsObjec <optional>
Options to decide what to get from the server.
Properties
Name Type Argument Default Description typesArray <optional>
Metadata types to fetch. E.g.:
['vardefs','detailviewdefs']modulesArray <optional>
Module names to fetch. E.g.:
['accounts','contacts']callbacksObject <optional>
callback object.
publicObject <optional>
false Pass
trueto get the public metadata.paramsObject <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 idstring Request ID
-
getStateProperty(key)
-
Retrieve a property from the current state.
Parameters:
Name Type Description keystring 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 requestHttpRequest The request to trigger.
errorObject The error object with at least the
payloadproperty.onErrorfunction The function to call in case of Error during the login request.
-
info( [callbacks])
-
Fetches server information.
Parameters:
Name Type Argument Description callbacksObject <optional>
callback object.
Returns:
The AJAX request.
- Type
- HttpRequest
-
isAuthenticated()
-
Checks if API instance is currently authenticated.
Returns:
trueif authenticated,falseotherwise.- 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 urlstring Returns:
trueif this is an authentication request,falseotherwise.- Type
- boolean
-
isExternalLogin()
-
Returns
truewhen using an external login provider.Returns:
truewhen we are using an external login provider,falseotherwise.- Type
- boolean
-
isLoginRequest(url)
-
Checks if request is a login request.
Parameters:
Name Type Description urlstring Returns:
trueif this is a login request,falseotherwise.- Type
- boolean
-
login(credentials [, data] [, callbacks])
-
Performs login.
Credentials:
username: user's login name or email, password: user's password in clear textParameters:
Name Type Argument Description credentialsObject user credentials.
dataObject <optional>
extra data to be passed in login request such as client user agent, etc.
callbacksObject <optional>
callback object.
Returns:
The AJAX request.
- Type
- HttpRequest
-
logout( [callbacks])
-
Performs logout.
Parameters:
Name Type Argument Description callbacksObject <optional>
Callback object.
Returns:
The AJAX request.
- Type
- HttpRequest
-
me(method [, data] [, params] [, callbacks])
-
Executes CRUD on user profile.
Parameters:
Name Type Argument Description methodstring Operation type: read or update (reserved for future use).
dataObject <optional>
user Profile object.
paramsObject <optional>
URL parameters.
callbacksObject <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
falsefor "skipMetadataHash" option to override this behavior.Parameters:
Name Type Argument Description actionstring <optional>
Optional ping operation. Currently, Sugar REST API supports "whattimeisit" only.
callbacksObject <optional>
callback object.
optionsObject <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 methodstring operation type: create, read, update, or delete.
modulestring module name.
dataObject 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.
paramsObject <optional>
URL parameters.
callbacksObject <optional>
callback object.
optionsObject <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 methodstring operation type: create, read, update, or delete.
modulestring module name.
dataObject object with relationship information.
paramsObject <optional>
URL parameters.
callbacksObject <optional>
callback object.
optionsObject <optional>
request options.
Returns:
The AJAX request.
- Type
- HttpRequest
-
resetAuth()
-
Clears authentication tokens.
-
resetState()
-
Clears the current API request state object.
-
search(params, callbacks [, options])
-
Searches for specified query.
Parameters:
Name Type Argument Description paramsObject Properties.
Properties
Name Type Argument Description qstring Query.
module_liststring <optional>
Comma-separated module list.
fieldsstring <optional>
Comma-separated list of fields.
max_numnumber <optional>
Max number of records to return.
offsetnumber <optional>
Initial offset into the results.
callbacksObject Hash with success and error callbacks.
Properties
Name Type Description successfunction Function called on success. Takes one argument.
errorfunction Function called on failure. Takes one argument.
optionsObject <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 flagBoolean Flag indicating if external login is in effect
-
setExternalLoginUICallback(callback)
-
Sets a function as external login UI callback.
Parameters:
Name Type Description callbackfunction -
setRefreshTokenSuccessCallback(callback)
-
Sets the callback to be triggered after a token refresh occurs.
Parameters:
Name Type Description callbackfunction 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 keystring 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 contactDataObject user profile.
dataObject <optional>
extra data to be passed in login request such as client user agent, etc.
callbacksObject <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 bulkIdnumber | string The id of the bulk request.
-
updatePassword(password, password [, callbacks])
-
Updates password.
Parameters:
Name Type Argument Description passwordObject The new password
passwordObject The new password
callbacksObject <optional>
Callback object.
Returns:
The AJAX request.
- Type
- HttpRequest
-
verifyPassword(password [, callbacks])
-
Verifies password.
Parameters:
Name Type Argument Description passwordObject The password to verify
callbacksObject <optional>
Callback object.
Returns:
The AJAX request.
- Type
- HttpRequest