Manage Functions

You can customize and shape your API by defining RESTful endpoints by way of functions, by defining RESTful endpoints, or resources, explicitly using API Creator, or by adding custom endpoints. This article focuses on the functions that you can create.
lac52
You can customize and shape your API by defining RESTful endpoints by way of functions, by defining RESTful endpoints, or resources, explicitly using API Creator, or by adding custom endpoints. This article focuses on the functions that you can create.
For more information about guidance about which endpoint type to define for your API, see Customize your API.
Functions can:
  • Call the defined JavaScript for the function and return a JSON response.
  • Declare explicit arguments.
  • Pass rows automatically. Set some fields and 
    Layer7 Live API Creator
     updates the row (including relevant reactive logic). Instead of getting, altering, and saving a row by having to issue APIs, use a function.
 
Layer7 Live API Creator
 includes functions in your Swagger API documentation.
You manage your functions by creating them, by viewing a list of them, by controlling access to them, and by deleting them. You can call functions by way of GET and POST operations.
In this article:
 
 
2
 
 
Function Types
You can define the following types of functions:
  • Top-level functions
    Top-level functions are functions that are not associated to an entity (table or view) or table-based resource. By default, functions are top-level functions. Use top-level functions to define any logic or service operation as endpoints.
  • Resource-oriented functions
    Resource-oriented functions are functions that are associated to an entity or table-based resource. These functions are operations on a entity or table-based resource row. Resource-oriented functions can access individual records in the code for the resource using the current table 
    row
     object. 
    Layer7 Live API Creator
     makes the row available to the function and any arguments. The function can then operate on the row (for example, 
    sendMail
     to alert a colleague about an Order), including update (for example, 
    giveRaise
     to an employee based on a 
    percentRaise
     argument). 
    Layer7 Live API Creator
     provides the mapping and translation, for example column de-aliasing. You can use the code for your function over multiple table-based resources that are based on the same table. You can also update the row in functions. When the function completes, 
    Layer7 Live API Creator
     calls the associated logic and persists the row to disk.
    Resource-oriented functions advance the API interface from create, read, update, and delete (CRUD) operations to operations the application requires. Resource-oriented functions can act as methods that encapsulate your business logic. Reactive logic ensures that 
    Layer7 Live API Creator
     reuses the API behavior over the PUT, POST, and DELETE HTTP methods for entities and table-based resources. This behavior contributes to a separation of concerns (SoC). Client development can enforce data integrity by proceeding based on the API interface, in parallel with API Server logic.
Create Functions
With your cursor in a code editor, for example, the custom endpoints code editor, click the 
Examples
 drop-down, click the insert icon (+) next to the code example that you want to insert into the code editor, and then click 
Save
.
Create a Function
  1. With your API open, in the Create section, click 
    Functions
    .
    If your API does not have existing functions, the Welcome to Functions page appears. If your API has existing functions, they are listed on the By function tab that displays by default.
  2. Complete one of the following options:
    • If you have not defined any functions, on the Welcome to Functions page, click 
      Create a Function
      .
    • If you have defined at least one function, on the By function tab, click 
      Create Function
      .
    The Definition tab for the new function appears by default.
  3. Complete the following fields, and then click 
    Save
    :
    Function name
     
    The name for the function. Enter a meaningful name for your function (or accept the default name).
    Code
     
    Defines the JavaScript code for the function. You can:
    • Insert a code example into the code editor.
      For more information about how to insert code examples, and the examples that are available from the functions code editor, see JavaScript Code Examples.
    • Code functions in JavaScript that reference JavaScript libraries and Java JAR files in your 
      classpath
      .
      For more information about the context variables that are commonly accessed in JavaScript code, see the "Add Context Variables to the JavaScript Code" section.
  4. (Optional) Add one or more parameters to your function. Click the 
    Parameters
     tab, click 
    Add Parameter
    , complete the following fields, and then click 
    Save
    :
    Name
     
    The name for the parameter. Enter a meaningful name for your parameter (or accept the default name).
    Type
     
    Define the parameter type.
    Values:
     number, string, or boolean
    Default:
     string 
    Required
     
    Specify whether the parameter is required.
    Default:
     Cleared
    Comments
     
    Enter a description of the parameter. 
  5. (Optional) Define the function type. Click the 
    Resources
     tab, complete the following field, and then click 
    Save
    :
    Function Type
     
    Defines the function type.
    Options:
     
    • Top-Level:
       Defines the logic or service operation for this function as endpoints. 
    • Resource-Oriented:
       Associates this function to an entity or table-based resource. In the code editor, enter the entities and table-based resources to which this function applies. Enter the names on separate lines.
    Use the following syntax for entities:
    <data source prefix>:<table name>
    Default:
     Top-Level
    For more information about function types, see the "Function Types" section.
  6. Describe the purpose of this function by defining comments and the return type that the function expects by clicking the 
    Documentation
     tab.
     
    Layer7 Live API Creator
     includes these comments and the return type in your Swagger API documentation.
  7. Save your changes.
Your function is created and is active.
Add Context Variables to the JavaScript Code
You code functions in JavaScript. Functions can reference JavaScript libraries and any Java JAR files that you have added to your 
classpath
. Your function returns a JavaScript object, which 
Layer7 Live API Creator
 converts to JSON or translates if you are using XML output.
Your functions can access the following variables:
Variable
Example
Notes
Parameters
var theRaise = parameters.percentRaise * (row.Salary/100);
Define your parameters.
For more information about how to define your parameters, see the "Create a Function" section.
row
row.Salary += theRaise;
The code for functions that are associated to entities or table-based resources can reference the (table) 
row
 attribute, as shown in the following image. 
row
 attributes are based on the column names for the entity. Alias column names (or attributes) for resources are not available from the 
row
 attribute.
req
var user = req.userIdentifier
req.json
var temp = JSON.parse(req.json);
The JSON payload that is passed in.
SysUtility
var functionResponse = SysUtility.getFunction(eachTest.TestName, null);
For an example, view the 
testB2BAll
 function in the Business to Business (B2B) API sample.
The following image shows an example of the 
giveRaise
 function's JavaScript code (this function is part of the B2B API sample):
var theRaise = parameters.percentRaise * (row.Salary/100);
row.Salary += theRaise; // runs logic, persists change row(s) to database...
return [ {"status": "Success"}, {"raise": theRaise} ]; // , {"row": row.toString()} ];
/*
This function works with the Employees table:
http://localhost:8080/rest/default/b2bderbynw/v1/nw:Employees/1/giveRaise?percentRaise=10
It also works with the EmployeesWithRaises resource, even though the Salary field is aliased.
The 'row.Salary' reference works because Live API Creator has already performed resource/object mapping.
So, row is a *table* row. You can reuse the function over many resources.
http://localhost:8080/rest/default/b2bderbynw/v1/EmployeesWithRaises/1/giveRaise?percentRaise=10
*/
Example: Create a Function
You can create a function for the 
employees
 table and the explicitly defined 
EmployeeWithRaises
 resource that gives an employee a raise. The following code snippet shows the JavaScript code:
var theRaise = parameters.percentRaise * (row.Salary/100);
row.Salary += theRaise; // runs logic, persists change row(s) to database...
return [ {"status": "Success"}, {"raise": theRaise} ];
This JavaScript code is from the 
Resource-oriented
 function code example. This example is also illustrated in the Business to Business (B2B) Give Raise example.
For more information about the Give Raise example, see Employee Raise Example.
Control Access to Functions
You can control access to your functions by setting function-level permissions for roles.
For more information about how to control a role's permission to call specific functions, see Authorization and Role-Based Endpoint Access.
View your List of Functions
In the Create section, click 
Functions
. The functions that you create are listed on the 
By function
 tab, using the following syntax:
<Function name>(<param1>,<param2>, etc.)
Call Functions
You can call functions in the following ways:
API users must have at least Read access to call resource-oriented functions.
Call Functions as Endpoints
You can call functions using the function name, optionally with parameters, using the following syntax:
http://localhost:8080/rest/default/demo/v1/
gcd?n1=0&n2=0
Call Functions on Entities of Table-Based Resources
Prerequisite:
 (Views) You have added a virtual primary key to the view.
For more information about how to add a virtual primary key to a view, see Manage Views.
You can call functions on entities or table-based resources and can pass arguments.
Use a URL with the following syntax:
.../v1/<data source prefix>:<entity or table-based resource name>/1/<function name>
Examples
 
The following code blocks shows examples of calling the 
giveRaise
 function:
http://localhost:8080/rest/default/b2bderbynw/v1/
nw:Employees/1/giveRaise?percentRaise=1
0
http://localhost:8080/rest/default/b2bderbynw/v1/
EmployeesWithRaises/1/giveRaise?percentRaise=10
Call Functions using POST
You can call functions by way of POST operations to pass a payload into the function.
The following example is the JavaScript code for the 
sortWithPOST
 example function that is included with the 
Demo
 API sample:
if (parameters.orderby == 'asc'){
var temp = JSON.parse(req.json);
return {"response":temp.fruits.sort()};
}
else if(parameters.orderby == 'desc'){
var temp = JSON.parse(req.json);
return {"response":temp.fruits.sort().reverse()};
}
else{
return {"error":"invalid orderby type"};
}
Call Functions using the SysUtility.getFunction() Method
You can call functions by way of GET operations. You can call functions from within API Server (for example, from logic, libraries, and functions) using the 
SysUtility.getFunction()
 method, for example:
var parms = {parm1: 1, parm2: 2};
var functionResponse = SysUtility.getFunction("myfunction", parms);
Call Functions using the SysUtility.postToFunction() Method
You can call functions by way of POST operations and pass in a payload in addition to the parameters. You can call functions from within API Server (for example, from logic, libraries, and functions) using the 
SysUtility.postToFunction()
 method, for example:
var parms = {orderby: "desc"};
var myPayload = {"fruits": ["Banana", "Orange", "Apple", "Mango"]};
var sortedArray = SysUtility.postToFunction("myFunction", parms, myPayload);
log.debug(sortedArray);
return JSON.parse(sortedArray);
Call Functions on Tables from Data Explorer
You can call resource-oriented functions from Data Explorer.
For more information about how to call functions on tables from Data Explorer, see Data Explorer.
Test Functions from the REST Lab
You can test your function in the REST Lab.
For more information about how to test a function in the REST Lab, see Test your API Using the REST Lab.