The Req Object
The Req Object
calac41
You can access the
req
object in rules and event handlers as the req
variable. This object is created once per request. Its contents are discarded when the request is complete. The req
object is suitable for transaction state but not for state that transcends requests.In this article:
Attributes
The
req
object has the following attributes:Attribute | Type | Description |
| string | The IP address of the client who initiated the request. |
| boolean | Values:
|
| object | All the parameters, and their values, as specified in the URL. Example:
|
| ApiKey | The API key that CA Live API Creator uses to authenticate the request. |
| ApiVersion | The API version object. You can get its name by calling (for example, "v1" ). |
| string | GET, POST, PUT, DELETE |
| string | The name of the resource/table on which the request is performed. |
| string | The base URL for this request. |
| string | The base URL for this request, but corrected to use as the host. Use this attribute if the caller must talk to (loopback) the local API. |
| string | The full base URL for this request, including the API version. |
| string | The full base URL for this request, but corrected to use as the host. Use this attribute if the caller must talk to (loopback) the local API. |
| object | All the HTTP headers that were provided by the caller, except the authentication header. The header names are case-insensitive. Example: req.httpHeaders['user-agent'] . |
Strings in the
object are Java strings internally. As a result, use care when using equality tests. While they perform just like JavaScript strings, when using '===' or '!==' equality tests, they are not the same and results can be unexpected. For example,req
is always false, where"GET" === req.verb
is true on a GET request."GET" == req.verb
Methods
The
req
object has the following methods:baseUrl() Method
Use the
baseUrl()
method to retrieve the base URL for the request, up to and included the API name:[http: || https]://[server.company.com[:port[/ServerWAR]] ]/[rest || data]/[TeamSpace name]/[URL fragment]/
For example:
https://rest.acme.com/rest/default/data/
getUserProperty() Method
Use the
method to retrieve an arbitrary object from the request object, as previously set by thegetUserProperty()
method.setUserProperty()
This method uses the following syntax:
req.getUserProperty(string, object)
setUserProperty() Method
Use the
setUserProperty()
method to set the specified API user property to the given value. After you have set the API user property, a piece of JavaScript code can retrieve the API user property in the scope of the request. This method uses the following syntax:
req.setUserProperty(name, object)
getUserProperties() Method
Use the
getUserProperties()
method to retrieve the URL properties/values where the property starts with arg
. Example:
req.getUserProperties().get("argName")
The apiKey Object Methods
The
apiKey
object has the following methods:The getUserIdentifier() Method
You can retrieve the login ID (userIdentifier) from the authentication token using the
getUserIdentifier()
method. The following code example illustrates how you can get the name for an API user name within the authentication token:
var apiKey = req.getApiKey(); // apiKey as objectvar login =apiKey.getUserIdentifier();log.debug("** Get the login ID: " + login); // gets the login ID as string
The getDataObjects() Method
You can access information about the API user that your authentication provider passes in using the the
getDataObjects()
method.The following code example illustrates how to retrieve name/value pair information for an API user that is stored in the
userData
object using this method:var temp = req.apiKey.getDataObjects().get("abc");log.debug("** The abc user data: " + temp);
The hasRole() Method
You can retrieve a user role using the
hasRole()
method. This method uses the following syntax:req.apiKey.hasRole('rolename')
This method returns
true
if the caller has the requested rolename
.Example:
var isAdmin = req.apiKey.hasRole('admin');
The getRoleNames() Method
You can retrieve a collection of user role name strings using the
getRoleNames()
method. This method uses the following syntax:req.apiKey.getRoleNames()
Example:
var roles - req.getApiKey().getRoleNames()
Access the Authentication Token using the apiKey Object
You can access the authentication token that
CA Live API Creator
generated to authorize the request using the apiKey
object from the request. The apiKey
object contains information about the API user (caller of the API) that are typically passed in from your authentication provider. The following code example illustrates how you can get the
apiKey
object from the request:var apiKey = req.getApiKey(); // apiKey as objectlog.debug("** The apiKey: " + apiKey.getApiKey()); // gets apiKey as string
HTTP Arguments
You can access arguments supplied in the HTTP request by way of the
request
Java object. The request
object represents the raw HTTP request of type HttpServletRequest
. You can particularize your update requests by testing these arguments in your logic.For more information:
- About the
object, see the Oracle documentation.request - About how to provide arguments for transactions, see the Transaction Parameters (Give Raise) and Deep Copy examples in the Reactive Logic Tutorial.
- About how to provide arguments for transactions, see Transaction Parameters Example.
Supply HTTP arguments, for example:
arg.argName=true
Access HTTP arguments in your rules using the following syntax:
req.getUserProperties().get("argName");
Examples
The following code snippet rejects requests that do not originate from the allowed IP range:
// Reject requests that do not originate from the allowed IP rangeif ( ! req.clientAddress.match(/^12\.34\.56\./g)) throw "Requests are not allowed from this IP address";
The following code snippet requires deletes to be over HTTPS:
// Deletes must be over HTTPSif (req.verb == "DELETE" && !req.clientUsesHttps) throw "Delete must be over HTTPS";
The following code snippet requires that you provide a special parameter to create a widget:
// We require a special parameter to create a new Widgetif (req.verb == "POST" && req.resourceName == "Widget") { var special = req.urlParameters.specialParam; if (special != "Please") throw "You forgot the magic word.";}
log.debug("clone event start");if (req.urlParameters.clone !== null) { log.debug("cloning: " + row); var deepCopy = ["lineitemsList"]; SysLogic.copyTo("orders", logicContext, deepCopy, false); }
In the following example, you get an API user's name by way of their login. The
request
object provides access to the auth token. You can retrieve the login ID (userIdentifier
) using this auth token so that you can query the employees
table. You can substitute this code into the Audit Purchase Order amount changes
event rule in the Demo
API sample, and then observe its effect in the log.For this request to work in the
API sample, you must update theDemo
auth token to User IdentifierBroad Access
.sam
if ("INSERT" != logicContext.initialVerb && row.amount_total != oldRow.amount_total) { // for (var i in req) { log.debug("Audit Purchase Order - req " + i); } var apiKey = req.getApiKey(); // apiKey as object log.debug("Audit Purchase Order with apiKey: " + apiKey.getApiKey()); // gets apiKey as string // for (var i in apiKey) { log.debug("Audit Purchase Order - apiKey " + i); } var login = apiKey.getUserIdentifier(); log.debug("Audit Purchase Order with userName: " + login); // gets apiKey as string sql = "select * from employee where login = " + "'" + login + "'"; var employee = logicContext.getBeanByUniqueAttributes("demo:employee", ["login"], [login]); log.debug("Audit Purchase Order for Employee: " + employee); // row has user's name, etc.. // or, use Globals (you must set them first [Role > Globals], may require ApiKeys > User Identifier) employee = logicContext.transactionContext.permissionContext.getData("current_employee_row"); log.debug("Audit Purchase Order for Employee from Global: " + employee); // <=== hmm, it's null var newPurchaseorder_audit = logicContext.createPersistentBean("purchaseorder_audit");newPurchaseorder_audit.amount_total = oldRow.amount_total; // set attributes from old values newPurchaseorder_audit.paid = oldRow.paid; newPurchaseorder_audit.customer_name = oldRow.customer_name;newPurchaseorder_audit.order_number = oldRow.order_number; // set the foreign keylogicContext.insert(newPurchaseorder_audit); // saves (fires logic)}// an alternative when the new values are wanted// if ("INSERT" != logicContext.initialVerb && row.amount_total != oldRow.amount_total)// SysLogic.insertChildFrom("purchaseorder_audit", logicContext);
Explore the Contents of the Req Object
You can explore the
request
object's contents using code. For example:var json = JSON.parse(req.json);for (var i in req) {log.debug("****req " + i); }for (var i in JSON.parse(req.json)) {log.debug("!!!!!json " + i);}var custName = json.customer; // a value in the requestlog.debug("***custName: " + custName);var options = { filter: "name = '" + custName + "'"};log.debug("***options: " + options);var custAccount = SysUtility.getResource("cust", options);for (var i in custAccount){log.debug("@@@@ " + i);}log.debug("***sending message" + JSON.stringify(custAccount[0]));
For more information about how to use the
json
object, including the stringify(<value>)
json
object function, see JavaScript.You can debug by way of logging information or using the
debug
option.For more information about how to output messages to the log, see View Logging Information.
For more information about how to use the JSON object, including the
stringify(<value>)
JSON object function, see JavaScript.