Difference between revisions of "REST API"

From AgileApps Support Wiki
Line 50: Line 50:


:[[REST API:Session Management Resources]]
:[[REST API:Session Management Resources]]
{{Note| The session management APIs can be used only when the LongJump capability is enabled.}}


===Administration Resources===
===Administration Resources===

Revision as of 08:48, 10 January 2024

The REST (REpresentational State Transfer) API is a mechanism that lets you send and receive data over an HTTP interface. With the REST API, XML and/or JSON messages can be exchanged with the platform, to integrate an enterprise application. The REST API exposes objects, files, actions and transactions for integration with external (third-party) enterprise applications.

1 Requirements

There are a number of considerations to take into account when writing a program that uses the REST APIs.

Chief among them is the need to include the login cookie string in each REST request.

For more on that subject, and for other things you need to know, make sure to review and understand the programming Considerations.

2 REST Resources (categorized)

This is a categorized list of available Resources.

See also: REST Resources (alphabetical), REST API CheatSheet

2.1 Session Management Resources

login Perform a Login action
logout Perform a Logout action
isSessionValid Determine if a valid session is in progress
userInfo Get information about the logged-in user
delegation Perform delegation
LogoutAll Log out all the sessions of a user
getActiveSessions Retrieve all active sessions of a user
logout Logout few sessions of a user
REST API:Session Management Resources

Notepad.png

Note: The session management APIs can be used only when the LongJump capability is enabled.

2.2 Administration Resources

accessProfile Manage Access Profiles
application Manage Applications
applicationTabs Manage application tabs
applicationAccess Manage Application Access
auditLog Access the Audit Log
companyInfo Manage Company Information
passwordPolicy Manage the Password Policy
user Manage User Records
team Manage Team Records
role Manage Role Records
teamDataSharingPolicy Manage the way in which data is shared among teams
tenantDataSharingPolicy Manage the way in which data is shared among tenants
userTeam Manage User Team Records

2.3 Data Management Resources

record Manage Records in an Object
bulk record Manage multiple Records in one call
composite record Manage Composite Objects
recordLocator Manage methods by which Records can be found
import mapping profile Manage field-mapping profiles used in an import
bulk Perform a mass data import
document Access stored documents
execSQL Make SQL queries

2.4 Customization Resources

object Manage Object metadata
field Manage Field metadata
index Manage Index metadata
globalPicklist Manage Global Picklists
translationWorkbench Get translated strings from the Translation Workbench
package Download or subscribe to a Package

2.5 Development Resources

class Manage Class definitions
exec Execute Class methods
utility Manage Time Zone Codes
customPage Manage Custom Pages
staticResource Manage Static Resources

2.6 Job and Status Resources

scheduledJob Manage scheduled jobs & check their status.
import Status Check on the status of CSV data import.
packageDeploy Status Check on the status of a package deployment.
REST API:Status Resources

2.7 Service Provider Resources

license Retrieve Platform License Information
promoCode Manage Promotion Codes
tenant Manage a Tenant
tenantCapabilities Manage Tenant Capabilities

2.8 Community Resources

community Actions related to the Community Tenant

3 Sample Programs

BaseClient Login, display sessionId, and logout.
BaseUtil Utility classes used by BaseClient, mostly for message formatting.
BulkUploadClient Import CSV data
PackageDownloadClient Download a package
PackageSubscribeClient Subscribe to a package
StaticResourceUploadClient   Upload a resource file to the platform.
Add a Note   Add a note to an object record.
Learn more: REST API pages, which contain additional code samples

4 Conventions and Considerations

4.1 Considerations

Warn.png

Important: To use the REST APIs, the first step is to log into the platform. The response to the REST login request contains a cookie string that includes the session ID and other session details.

That cookie string must be present in all subsequent REST requests.

(Browsers do that automatically, so once you are logged in, REST APIs in JSP pages "just work". But when writing a program, you need to code that behavior.)

Learn more: REST API Sample programs
  • The REST APIs are granular (each call operates on a single entity)
  • Each REST API call is treated as a single transaction
  • In most cases, APIs have a direct one-to-one mapping with the UI
  • Input and output can be structured using either XML or JSON.
  • The content types for request data are application/xml and application/json.
    (text/xml is not supported.)
  • It is necessary to login to the platform before making a REST API call (and logout afterwards)
  • All REST API calls execute within the context of the User that is logged in. As with all UI actions, this means that any subsequent REST API calls (to access levels, data visibility, team membership, etc.), are governed by the Data Access Permissions granted to the User.
  • REST API calls are broadly categorized as Data API or Metadata API (excluding login/logout)
  • Data calls can span multiple objects, for example, the owner field in an object, or Lookups (foreign key relationships) to some other objects
  • The REST API implements the database CRUD model (Create, Read/Select, Update, Delete) using HTTP protocol requests (POST, GET, UPDATE and DELETE).
CRUD Action HTTP Method
Create POST
Read/Select GET
Update PUT
Delete DELETE
  • Field elements are optional in record updates. If a field is missing, existing data in that field is unaffected. If a field is present, but empty, any existing data in that field is deleted.
  • All data coming from and going to the platform is in [[Database Format].
    (See the REST API:Field Type Reference for the data formats to specify for the different field types.)
  • When the database value for a checkbox field is null, the REST API returns 0. (So the value is always 1 (checked) or 0 (unchecked), whether or not the field has been initialized.)

Notepad.png

Note:
When specifying a URL in code, any special characters (characters other than letters and numbers) need to be encoded. For example, a space character can be encoded using either + or %20.

(Browsers typically take care of encoding URLs entered into the address bar--so the URL displayed after visiting a page may differ somewhat from the one that was initially entered.)

Here are some typical encodings:

space
+
%
%20 or +
%2B
%25

So:

Instead of Use

& (A&B)
space (A B)

%26 (A%26B)
%20 (A%20B)


It can be hard to get be hard to get the encoding right, so it's desirable to use a language library designed for the purpose.
Learn more:


4.2 Conventions

The following conventions apply to REST requests (data sent to the server), responses (data coming back), and resources (URLs):

  • GET requests can specify the response format using the alt query parameter. (?alt=json or ?alt=xml)
  • POST requests add things. PUT requests update things.
  • POST/PUT request format can be either JSON or XML.
The argument format is specified using Content-Type in the http header.
The Content-Type value is either application/xml or application/json
There is no default. The Content-Type must be specified.

Notepad.png

Note: For information on usage of special characters when using XML format, see XML

  • POST/PUT requests can specify the response format as either JSON or XML by using Accept in the http header.
  • The default format for all responses is JSON. (In JavaScript, such data can be easily and efficiently eval'ed into an object.)
  • Some browsers (notably Firefox) automatically add an Accept header that specifies an XML response. (When testing behavior in those browsers, you'll see XML coming back, even though the default is JSON. Particularly when testing GET requests.)
  • REST API calls typically require either an Object Type Identifier or a Record Id, specified in either the URI and/or XML, in order to specify the type of object and/or the specific record to be acted on.
  • Elements (tagnames) in XML requests and responses are listed under the heading, Fields. That usage is historical, deriving from the fact that, in general, each request/response corresponds to a Java Bean used in a Java API call.
  • For POST requests, a resourceId is returned, which can be a positive integer or a GUID, depending upon the type of resource created.
  • For PUT requests (updates):
  • The target object/record is specified in the URI.
  • An object or record ID specified in the request is ignored.
  • Fields are specified in the request.
  • Most fields are optional. (Those that are required are specified in the documentation page for that resource, under Fields.)
  • If a field is missing, existing data in that field is unaffected.
  • If a field is specified, but empty, any existing data in that field is deleted.
  • Fields are specified in a table for each REST API.
  • Field data types describe the kind of data that the field contains. The most common data types are:
Boolean A binary value. The case-insensitive choices are : "true", "false", "yes", "no", "1", or "0".
Currency A string of digits, including a single decimal point
Date A date, time, or combination of the two. Format is specified in the "Additional Information" column of the field-specification table.
int A numeric, integer value.
Number with Decimal A string of digits, including a single decimal point
List A list containing homogenous of subelements. If the element name is <things>, then the subelements are generally labeled <thing>.
String An alphanumeric string value.
Struct A structure consisting of multiple heterogenous subelements. If the element name is <things>, then subelements might be <car>, <house>, <boat>.
Learn more: Database Format

4.2.1 Query Parameter Arguments

Parameters shown in braces in URIs and REST requests designate arguments you supply. These parameters are typical:

  • {yourDomain} - represents the Service Domain (platform hostname or IP address)
  • {objectName} - an Object Type Identifier
  • {recordId} - a Record identifier
  • {viewId} - a View identifier

In each case, you specify the value for your domain, the name of the object your are accessing, etc.

Notepad.png

Note: Where {objectName} is required, an {objectId} can also be used. But {objectName} is recommended, because it is always human-readable. (The {objectId} is human-readable for System Objects, but not for Custom Objects.)

Examples:

  • https://{yourDomain}/networking/rest/user/{recordId}
  • https://{yourDomain}/networking/rest/field/{objectName}/{fieldName}

4.2.2 Dynamic Search Parameters

Search URIs use query parameters like these:

Query Parameters
  • fieldList - A comma-separated list of field names to retrieve
  • The asterisk (*) wildcard specifies all fields
  • {fieldname} specifies an individual field (e.g. name)
(Use the REST API:field Resource to get a complete list of fields.)
  • For a Composite Object, specify {alias}.{fieldname} to select a related-record field, where the alias is defined in the Object Relationships.
  • For a Database View, specify {alias}.{fieldname}, where the object alias is defined in the Database View.
  • alias.* specifies all fields in the aliased object.
  • filter - Filtering criteria to filter the records
  • pageSize - Number of records to retrieve from the result set in order to make a "page".
  • page - Number of the logical page in a database result set. The first page is page "zero" (0).
Page zero is returned by default, so appending &pageSize=1 to your query returns a single record.
  • getTotalRecordCount returns the number of total records.
    Causes the following structure to be returned, where N is the total number of records:
<platform> 
   <status>
   <packageDeploy>
   ...
   </packageDeploy>
   </status>
   <message>
      <code>0</code>
      <description>Success</description>
   </message>

   <!-- added by the query param -->
   <totalRecordCount>N</totalRecordCount> 
</platform>
  • sortBy - Field name for primary sort
    Ex: &sortBy=name
  • sortOrder - Sort order of the primary field, either asc or desc (ascending or descending)
    Ex: &sortOrder=desc
  • sortBy2 - Field name for secondary sort
  • sortOrder2 - Sort order of the second field, either asc or desc (ascending or descending)
For more information, see: Specifying Query Parameters in REST APIs


5 Error Codes

All requests return standard HTTP status codes as well as a message code and description, in the body of the response.

5.1 HTTP Status Codes

The most commonly returned HTTP status codes are:

Code Status Description
200 SUCCESS Returned by a successful GET, PUT, or DELETE.
201 CREATE_SUCCEEDED Returned by a successful POST. Indicates that a new entity has been added to the platform.
400 BAD_REQUEST Invalid argument, or other error as indicated by accompanying platform message.
404 BAD_URL The specified resource does not exist, or the server could not be reached.
405 METHOD_NOT_ALLOWED The requested resource does not respond to the specified method, or to the content type of the request. This message is returned when:
  • The wrong method type was specified. (Typically, GET instead of POST, or vice versa.)
  • The wrong URL was specified. (The URL exists, but it's not one that responds to the specified method.)
  • The wrong content-type was specified. (The URL exists, and the method is valid, but there is no variant of the resource that processes the specified content type.)

(Check your spelling, and double-check the API description.)

415 UNSUPPORTED_MEDIA_TYPE Content-Type has not been specified in the request header. Depending on data format, it should either be application/xml or application/json.
Learn more: Response Status

5.2 Platform Message Codes

In addition to the standard HTTP return code, the body of the response from the server includes a <message> section, which contains:

code
An Integer containing a success or failure code:
  • A value of 0 indicates a successful call.
  • Any negative value (<0) indicates an error.
description
A String containing an explanatory message.

The most commonly returned platform message codes are:

Platform Code with Http Status Description
-1 INTERNAL_SERVER_ERROR (500) Request could not be completed.
See description for the error message.
-101 UNAUTHORIZED User not logged in
-200 NOT_FOUND (404) Invalid object name, object ID, or record identifier
-300 BAD_REQUEST (400) Resource does not exist
-400 BAD_REQUEST (400) Invalid time zone
-690 BAD_REQUEST (400) Record does not exist
-850 BAD_REQUEST (400) Insufficient permission for this operation
-4000 BAD_REQUEST (400) Error downloading package
-4001 BAD_REQUEST (400) Please provide file name
-4003 BAD_REQUEST (400) Manage Packages permission is not enabled
-4004 BAD_REQUEST (400) Provide either file name or Package ID
-4005 BAD_REQUEST (400) Invalid package ID
-4006 BAD_REQUEST (400) Invalid Tenant ID
-4007 BAD_REQUEST (400) Invalid deploy time
-4600 FORBIDDEN (403) Feature is not enabled for this tenant
-4601 BAD_REQUEST (400) Invalid payload for this resource (data is not well formed, has an invalid tag, or is missing a required tag)
-4602 BAD_REQUEST (400) Invalid type
-4603 BAD_REQUEST (400) Invalid ID
-4604 BAD_REQUEST (400) Duplicate follower
-4605 BAD_REQUEST (400) Invalid vote action
-7000 BAD_REQUEST (400) Invalid index name

Learn more: See the javadoc constants for a complete list of PlatformException error-code constants.