Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The Scripted REST API functionality allows application developers to implement is used to create custom web APIs .

Define API actions and request parameters that utilize the customized API logic (including but not limited to: the script implementing method; request path; authentication require; parameter obligate for related modules and actions).

Tip

Role required: admin.

Scripted REST API URIs

The format of scripted REST API URIs is represented below:

Code Block
{your_instance_url}/v1/api/{applicationSlug}/{module_path}/{version}/{action_path}?{params}

URI analysis

URI partDescription{your_instance_url}Path to the instance where the scripted REST API can be accessed.{applicationSlug}

This parameter is composite and designated out of the parts below:

{applicationSlug}{application.table_prefix}_{application.name}

The attributes listed above belong to the application within of which the implementing is being conducted.

Tip

Non-English application names will be transliterated automatically.

{module_path}API module containing references to essences implementing the customized REST API logic (actions, request parameters, and so on). API modules are described below.{version}(optional) Version of the API endpoint if versioning is used, for example, v1.{action_path}API action containing main logic and behavior of your Scripted REST API. API actions are described below.

for instance integrations with external applications. You can define a server script called by a REST request from an external system.

The script can process request parameters, perform actions on the instance, and generate a response. The configured REST API creates an endpoint for the requests from external systems, including other SimpleOne instances.


Tip

Role required: admin.

Endpoint setting


To set an endpoint, complete the steps below:

  1. Create an API Module. Navigate to Scripted REST API→ API Modules.
  2. Specify the Name, Active and Path fields. 

    Expand
    title

How to implement your custom API

  1. Create an API module.
  2. Create an API version.
  3. Configure API actions.
  4. Configure API request parameters.
  5. Bind API request parameters with appropriate API modules and actions.

Creating an API Module

API module is a connecting element for API versions and API actions. 

To create an API Module, please complete the steps below:

  1. Navigate to Scripted REST API → API Module.
  2. Click New and fill in the form.
  3. Click Save or Save and Exit to apply changes.
    API Module form fields


    FieldDescription
    NameSpecify the API module name.
    Path
Relative cmdb
  1. Specify a relative path to the API module, for example,
'
  1. support.
'
  1. ActiveSelect this checkbox to make the module active
or inactive. When set to 'false', you'll be unable to choose
  1. . This enables you to select this module in the referencing tables
(
  1. : API Version, API Action, and API Module Request Parameters
)

Creating an API Version

Scripted REST API enables versioning, allowing developers to deploy changes without affecting existing integrations.

To configure an API version, please complete the steps below:

  1. Navigate to Scripted REST API → API Version.
  2. Click New and fill in the fields.
  3. Click Save or Save and Exit to apply changes.


  1. Click Save or Save and Exit to apply the changes. A related record API Version is created and located in the Related list.
  2. Click the API Version record in the Related list to open it. You can add another record of the API module version in the Related list if needed. 

    Expand
    titleAPI Version
API version
  1. form fields


    FieldDescription
    ModuleSpecify the API module created earlier for this version.
    ActiveSelect this checkbox to make the version active or inactive. When set to
'
  1. false
'
  1. , you'll be unable to
choose
  1. select this version in referencing tables (API Action).
    Path
Path
  1. Specify a path to the API version, for example,
'
  1. v1
'
  1. .
Note

The first version, that is v1, ready for deployment, is created automatically when the API module is created.

API requests without a version specified automatically use the last version having Active state.

Configuring an API Action



  1. In

there, you can configure an action implementing the logic and behavior of your customized API method.
  1. the Related list area, select the API Action tab and click New.

    Expand
    titleAPI Action

Your actions created earlier can be reached by URI like:

Code Block
{your_instance_url}/v1/api/{application}/{module_path}/{action_path}

or

Code Block
{your_instance_url}/v1/api/{application}/{module_path}/{version}/{action_path}

The second URI sample is used in case of the versioning enabled.

To configure an API action, please complete the steps below:

  1. Navigate to Scripted REST API → API action.
  2. Click New and fill in the fields.
  3. Click Save or Save and Exit to apply changes.
API action
  1. form fields


    FieldDescription
    Name
The
  1. Specify the action name.
    Path
A
  1. Specify a path for API action.
    ActiveSelect this action to make the version active
or inactive
  1. . When set to
'
  1. false
'
  1. , you
'll be unable to choose
  1. cannot select this version in referencing tables (API Action Request Parameter).
    Is Authentication Required

    Select this checkbox if the request requires authentication before the execution. The token passes in the request header. By default, this statement is equal to

'
  1. true

'. Note

Only Bearer authentication method is supported. That said, you need to pass the authentication token in the request header.

In the code example below, you can obtain an option how to retrieve the authorization token with user login and password (this code block uses example data for the setRequestUrl method and the payload constant. Replace it within the real usage):

Code Blockconst request = sws.restRequestV1(); request.setRequestUrl('https://your-instance-url.simpleone.ru/v1/auth/login'); request.setRequestMethod('POST'); request.setRequestHeader('Content-type', 'application/json'); const payload = { "username": "admin", "password": "qwerty123456" } request.setRequestBody(JSON
  1. .

stringify(payload)); const response = request.execute(); ss.info(JSON.parse(response.getBody()).data.auth_key); // Info: 5WvOT9Ejlxd6Gb8bkCWMtG3XXMYcoDDJ
  1. Module
Choose
  1. Select the API Module created earlier (activate module before
choosing
  1. selecting). This field references the API Module (sys_api_module) table.
    Version
Choose
  1. Select the API version created earlier (activate version before
choosing
  1. selecting). This field references the API Version (sys_api_version) table.
    HTTP MethodSelect the method this action implements (for example, GET
,
  1. or POST
, for example
  1. ).
    Script

    Specify a script

implementing
  1. that implements your action

,
  1. using the Server-Side API, SimpleApiRequest and SimpleApiResponse side API classes there.

Configuring API request parameters

In there, you can specify the request parameters, for example, you can make the parameter mandatory for all referenced API essences.

To configure this, please complete the steps below:

  1. Navigate to Scripted REST API → API Request Parameter.
  2. Click New and fill in the fields.
  3. Click Save or Save and Exit to apply changes.

API Request parameter form fields

FieldDescriptionNameThe request parameter name.Is requiredSelect this checkbox to make this parameter mandatory for all referenced API essences.

Configuring API action request parameters

In this section, you can bind specified API module with relevant request parameters.

To configure them, please complete the steps below:

  1. Navigate to Scripted REST API → API Action Request Param.
  2. Click New and fill in the fields.
  3. Click Save or Save and Exit to apply changes.

API action request parameters form fields

FieldDescriptionActionSpecify the API action created earlier for which you need to define a related API request parameter. This field referenced the API action (sys_api_action) table.Request parameterSpecify a request parameter related to this action. When specified, an action referenced to this request parameter can use its options predefined in the API request parameters dictionary. This field references the Request Parameter (sys_api_request_param) table.


  1. Info

    You can create an API action to run its script when a request for action is received. 

    You can state a version to the request for action:

    {your_instance_url}/v1/api/{application}/{module_path}/{version}/{action_path}

    Or you can omit it:

    {your_instance_url}/v1/api/{application}/{module_path}/{action_path}

    API requests without a version specified automatically use the last active version.


  2. Fill in the Name and the Path fields. The example value of the Path field is tickets-count.

  3. In the HTTP Method field, specify the method to call the action.
  4. In the Script filed, add a script to call when a REST request for the action occurs. To work with the REST API requests in the SimpleOne platform, the SimpleRestRequest and SimpleRestResponse classes are defined. The data objects of these classes are available in the API action script. See the example below:

    Code Block
    languagejs
    titleAPI action
    linenumberstrue
    (function (request, response) {
        const reqBody = request.getBody();
        response.setBody({
            "body": JSON.stringify(reqBody),
            "count": 1
        })
    })(SimpleApiRequest, SimpleApiResponse)


Configuring API module request parameters

In this section, you can bind specified API module with relevant request parameters.

To configure this relationship, please complete the steps below:

  1. Navigate to Scripted REST API → API Module Request Param.
  2. Click New and fill in the fields.
  3. Click
  4. Click 
  5. Save or Save and Exit to apply the changes.
  6. You can set API

Module request parameters form fieldsFieldDescriptionModuleSpecify the API module created earlier for which you need to define a related API request parameter. This field references the API Module (sys_api_module) table.Request parameter

Specify a request parameter related to this module. When specified, all actions referenced to the module above can use this request parameter. This field references the Request Parameters (sys_api_request_param) table.

Example case

Consider a case of implementing Scripted REST API returning data in response to a POST request.

The request looks like: http://your-instance-url.example.com/v1/api/c_simple/api_module_path/api_action_path?param_1=value_1

Your actions should go as follows:

  • Create an API module. Fill in the fields as given below:
    1. Name  type a module name.   
    2. Path type api_module_path there.
    3. Select the Active checkbox to activate the module.
  • Create an API version out of API module created earlier. Fill in the fields as given below:Name type a version name.
  • Module this field populates automatically with reference to the API module
  • Path type v1 there,
  • Select the Active checkbox to activate the version.
  • Create an API action out of API version created earlier. Fill in the fields as given below:
    1. Name  type an action name.
    2. Path type api_action_path there.
    3. Module  this field populates automatically with reference to the API module.
    4. Version  this field populates automatically with reference to the API version.
    5. HTTP Method select POST in this list.
    6. Select the Active checkbox to activate the version.
    7. Is Authentication Required select this checkbox if you are sending authenticated requests.
    8. Script put a script here given in a code example below .
  • Send a POST request to the URL given in the introductory. You can use any tool you are comfortable with (cURL, or Postman, or any other one).
    1. Substitute the example domain (your-instance-url.example.com) in the endpoint and in the script body with your real hostname.
  • Check logs (the sys_log table) to locate responses.
  • Code Block
    languagejs
    themeEclipse
    titleScripted REST
    linenumberstrue
    (function (request, response) { ss.info("getBody(): " + JSON.stringify(request.getBody())); ss.info("getHeader('accept-encoding'): " + JSON.stringify(request.getHeader('accept-encoding'))); ss.info("getHeaders(): " + JSON.stringify(request.getHeaders())); // {"accept-encoding":["gzip, deflate, br"],"postman-token":["7803024c-7e21-4e0d-840b-392931597c2c"],"cache-control":["no-cache"],"accept":["*/*"],"user-agent":["PostmanRuntime/7.26.8"],"content-length":["0"],"connection":["close"],"x-nginx-proxy":["true"],"host":["your-instance-url"],"x-real-ip":["XX.XX.XX.XX"],"content-type":[""]} ss.info("getQueryParams(): " + JSON.stringify(request.getQueryParams())); // {"param_1":"value_1"} ss.info("getQueryString(): " + request.getQueryString()); // param_1=value_1 ss.info("getUri(): " + request.getUri()); // /v1/api/c_simple/api_module_path/api_action_path?param_1=value_1 ss.info("getUrl(): " + request.getUrl()); // https://your-instance-url.example.com
    1. action request parameterrelated to the action and select the Is Required option for any of them if necessary. See the screenshot below:
      Image Added
      When sending a request without a mandatory parameter, a user will receive the following message:

      Code Block
      {"error":"Required parameter param_1 not sent.","timing":{"before_echo": ...}}


    Endpoint call


    To call an endpoint, use the following URL format: 

    Code Block
    themeEclipse
    https://your_instance_url/v1/api/applicationSlug/module_path/version/action_path?params

    Where:

    • your_instance_url – the instance URL you use.
    • applicationSlug – the value of the Slug field of the application that the endpoint is created for. 
    • module_path – the value of the Path filed stated in the API Module.
    • version – the value of the Path field of the API Version.
    • action_path – the value of the Path field stated in the API Action.
    • params – the GET parameters.

    See below a URL example of calling an endpoint:

    Code Block
    themeEclipse
    https://sandbox-01.dev.simpleone.ru/v1/api/c_simple/api_module_path/api_action_path?param_1=value_1

    Authorization
    Anchor
    authorization
    authorization


    You can make requests to the Scripted REST API with a Bearer token or without any authorization. The type of request authorization depends on the selection of the Is Authentication Required checkbox on the API action form:

    Image Added

    A request to an API action that does not require authorization (Is Authentication Required=No) is executed under the Guest User:

    Image Added


    The requests with an invalid Bearer token are also executed under the Guest User. 

    To set Basic Auth for request authorization in Scripted REST API, do the following:

    1. Set up sending a POST request /v1/auth/login with Basic Auth from an external system to an instance to receive a token.
    2. Set up sending a request to the Scripted REST API with the token received in the first step. 

    Find below an authorization scheme:

    Image Added

    This is an example of a server script that uses the Simple API to get a token by sending a POST request with Basic Auth authorization: 

    Code Block
    languagejs
    titleExample
    linenumberstrue
    const simpleInstanceUri = ss.getProperty('simple.instance.uri');
    const URL_BASE = (simpleInstanceUri.startsWith('https://')) ? simpleInstanceUri : `https://${simpleInstanceUri}`;
    const authRequest = sws.restRequestV1();
    authRequest.setRequestUrl(`${URL_BASE}/v1/auth/login`);
    authRequest.setRequestMethod('POST');
    authRequest.setRequestHeader('Content-type', 'application/json');
    const payload = {
        "username": "admin",
        "password": "qwerty123456"
    }
    authRequest.setRequestBody(JSON.stringify(payload));
    const authResponse = authRequest.execute();
    if (JSON.parse(authResponse.getBody()).status === 'ERROR') {
      ss.error(JSON.parse(authResponse.getBody()).errors[0].message);
      ss.info('Check credentials at 10..11 lines of current script');
      return;
    }
    ss.info(JSON.parse(authResponse.getBody()).data.auth_key);
    // Info: 5WvOT9Ejlxd6Gb8bkCWMtG3XXMYcoDDJ

    Supported types Content-Type


    To get a request body in a script of API action, call the getBody() method for the request object.

    Find below an example script for the API action:

    Code Block
    titleAPI action
    linenumberstrue
    (function (request, response) {
       
        const reqBody = request.getBody();
        const bodyForResponse = typeof reqBody === 'string' ? reqBody : JSON.stringify(reqBody);
        response.setBody({
          "request_body_type": typeof reqBody,
          "request_body": bodyForResponse
        })
       
    })(SimpleApiRequest, SimpleApiResponse)


    Use the following Content-Type types for the requests sent to the API action:

    • application/json
    • application/jsonp
    • application/xml
    • text/xml
    • text/html
    • text/plain

    Sending a POST request with a JSON body


    Image Added

    Sending a POST request with an XML body


    Image Added


    Sending a POST request with an HTML body


    Image Added

    Sending a POST request with a text body


    Image Added

    Response from API action


    To create a response from the API action, use the  response object:

    Code Block
    themeEclipse
    linenumberstrue
    response.setBody({
          "count": 100,
          "status": "OK",
          "error_message": ""
        })


    The response of the API action includes a key timing containing the execution time of the API action script:

    Code Block
    themeEclipse
    linenumberstrue
      "timing": {
            "before_echo": 0.0884089469909668
        }


    Setting examples


    Here you can download a file with example configurations for the scripted REST API: [SOC] - Scripted REST API. Import the pack to your instance and try the following example settings. 

    Example 1. Get a system property value without authorization


    To verify the example: 

    1. Go to the main page of your instance.
    2. Add to the URL bar the following value: /v1/api/c_simple/api_module_path/api_action_path?param_1=value_1
    response.setBody({ "status": "ok", "support_phone": ss.getProperty('
    1. .
    2. Copy the result URL.
    3. Go to the URL in Incognito mode.

    As a result, you receive a response from the API action /record/sys_api_action/164054047017513732 with a system property value simple.auth_page.support_phone

    ') }); })(SimpleApiRequest, SimpleApiResponse)

    Example 2. Create a task record with an attachment


    To verify the example: 

    1. Open the record /record/sys_script/164053985417710860 .
    2. Click Run to run the script.

    As a result, you receive a response from the API action /record/sys_api_action/161831494014244852.

    On the bottom of the script form, there is a link to the created task record. See the screenshot below:

    Image Added

    The record contains two attachments with base 64 files transferred in lines 14-15 of the script in Step 1. See the screenshot below:

     Image Added 

    Features and recommendations 


    1. API action script is executed regardless of ACL.
    2. Authorization of requests to the Scripted REST API is not possible with Basic Auth. To authorize, use the solution described above in the Authorization section.
    3. A reply to the API action containing a key error with a value Undefined index: SimpleApiResponse means the script API action contains an error.
    4. To avoid data corruption, convert JSON data type into type String using a JSON.stringify() method.
      Image Added 
    5. If the execution time of the API action script exceeds the Timeout, move a part of the script to the Event Script and call a system event with an API action script.

    Table of Contents
    absoluteUrltrue
    classfixedPosition