Explore the B2B API Sample

This article covers intermediate and advanced  functionality and concepts using the Business to Business (B2B) sample.
lac42
This article covers intermediate and advanced 
CA Live API Creator
 functionality and concepts using the Business to Business (B2B) sample.
In this article:
 
 
4
 
 
Verify the Prerequisites
Before you explore the intermediate and advanced functionality and concepts that are covered in this article, ensure that you have completed the following prerequisites:
  • You have explored the key introductory 
    CA Live API Creator
     concepts that are covered in the "Explore B2B (Fundamentals)" section of the B2B API Sample.
  • You understand service logic and business logic.
    A key objective of the B2B API sample is to provide practical examples of service logic and business logic. A solid understanding of service logic and business logic is critical to the effective use of 
    CA Live API Creator
    .
    For more information:
Interface Logic
You can think of your update processing as consisting of interface logic and business logic:
Logic
Defined On
Facilities
Typical Uses
 
Interface
 
Resources
Resources that you define explicitly (including multiple data sources) in API Creator.
Extend with request event handlers and metadata action tags.
Provide APIs for API consumers with more interface logic to optimize output and reduce latency.
Match external API agreements, particularly in the request and response formatting, for both retrievals and updates.
 
Business
 
Entities (Tables and Views)
Spreadsheet-like validations and derivations, such as formulas, sums, counts.
Row permissions.
Extend with row event handlers.
Business logic and security, automatically invoked and re-used across resources.
Validations and row event handlers fire only on update operations.
The interface logic that is defined in the B2B API sample are described in this section, summarized in the following diagram:
  Screen Shot 2017-09-09 at 4.06.34 PM.png  
The following connections and their approaches describe the key elements of the diagram:
Connection
Approach
1. API agreement
Agree with partners to provide APIs of a particular format.
2. Request event handler
Look up product IDs from product names that partners supply by injecting metadata action tags, as illustrated in the following code snippet:
var actions = [
{resource: "PartnerOrder", path: "$..Product", insertActions: "LOOKUP"},
{resource: "PartnerOrder", path: "Shipper", insertActions: "LOOKUP"},
{resource: "SupplierSelfService", path: "", insertActions: "MERGE_INSERT"}
];
json = insertActions.insertActions(req, json, actions); // API Server processes this...
// log.debug("requestEvent json: " + json);
3.
Messages
resource processing
Create the 
PartnerOrder
 resource and define the resource/row mapping to the underlying 
Orders
 and 
Order Details
 rows. 
CA Live API Creator
 automatically does the processing (persistence, mapping, and business rules). You do not have to code.
4. Business logic
Business logic rules react automatically on the 
Orders
 and 
Order Details
 rows to, for example, price the order. The following code snippet shows how the 
Process Shipper Webhook
 commit event rule on the 
Orders
 table alerts the supplier:
var shipper = row.Shippers; // object model (row) provides accessors to related objects
if (shipper !== null) { // resource defines transform: cols, aliases, related objects
var transform = logicContext.transformCurrentRow("ShipperAPIDef"); // find with code completion
B2B.sendToWebHook(transform, shipper.webHookURL); // loadable library
}
The 
B2B Northwind
 API sample includes the 
B2BLib
 and the 
InsertActionsLib
 logic libraries. The 
B2BLib
 library includes the 
sendToWebHook
 JavaScript wrapper function, which can call out to Java or other services. These libraries illustrate how you can create your own for common tasks. These libraries can invoke your existing Java code and web services.
For more information about logic libraries, see Logic Libraries.
Resources
The B2B API samples include several resources that provide key functionality that is traditionally coded into a service. These resources are described in this section. 
Leverage with SysUtility
You can manipulate resources using the 
SysUtility
 JavaScript object. The 
Supplier Alert
 event rule illustrates using this service. This rule alerts the 
Pavlov
 supplier, checks what was ordered. If it is a product that is supplied by the 
Pavlov
 supplier, this rule posts an alert to the 
B2B Pavlov
 API.
For more information about how to manipulate resources using the 
SysUtility
 object, see The SysUtility Object.
Mapping and Transformation
You can choose columns and related tables, and can provide aliases, when you define resources explicitly in API Creator. For example, the 
PartnerOrder
 resource that is defined in the B2B Northwind API. These resources provide a database abstraction layer.
Multi-Database Resources
The 
SupplierInfo
 resource joins data from two different data sources. In API Creator, open the B2B Northwind API and explore the Data Sources page. Observe the 
nw:Suppliers -> promos:promotions
 relationship that is based on tables in two different databases. 
For more information about how to integrate multiple databases, see Integrate Multiple Databases.
Test the access for the Pavlov 
Suppliers
 role to the 
SupplierInfo
 resource in the REST Lab.
 
Follow these steps:
 
  1. With the 
    B2B Northwind
     API open, in the Execute section, click 
    REST Lab
    .
    The Request page opens by default.
  2. Complete the following steps, and then send your request by clicking 
    GET
    :
    1. Select 
      Resource
       as the endpoint on which you want to operate.
    2. Select 
      SupplierInfo
       as the named resource.
    3. Select 
      Pavlov Supplier
       as the authentication token.
Automatic Generated Key Handling
Consider inserting a 
PartnerOrder
. When order details are finally inserted into the database, their OrderID foreign keys must be valid. But partners cannot and should not provide OrderIDs. OrderIDs are internal implementation. Order numbers are generated by the database management system (DBMS) on INSERT. Clients cannot know them before-hand and supply their values as OrderIDs to link items to orders.
This Cascade Add pattern is common. API Server obtains the order number and cascades the value into the 
Order Details
 rows. This process is automatic, based on schema information about keys and the join definition of the resources that you define explicitly in API Creator.
For more information about how API Creator returns the key in update responses, see Automatic Key Generation.
Request Transformation
To transform the API, you can manipulate/transform the request data using request event handlers. API Server invokes request event handlers for every request, after it receives the request but before it processes request/row mapping and reactive logic.
For more information about how API Server processes update requests, including how rules integrate with request event handlers, see Logic Execution.
The following sections show some typical examples.
Event Request Transformation
The B2B API samples illustrates request transformation in the following ways:
  • The 
    PartnerOrder
     resource. This resource injects 
    @metadata
     tags to look up ProductIDs, given product names.
    For more information, see the "Metadata Tags for Parent Lookup" section.
  • The 
    SalesReports
     request event handler in the 
    B2B Pavlov
     API: B2B "throws" (sends) a webhook to the 
    B2B Pavlov
     API by way of this resource. The 
    B2B Pavlov
     API must reformat the request.
    The sample code that is shown in the 
    Remove tags from json
     request event handler performs this translation for the 
    SalesReports
     resource. The following image shows this request event handler in the 
    B2B Pavlov
     API:
  worddavbfa8d4ee2fea992e4a03e635cf6979a5.png  
You can use the logs to view its operation. Test the 
TestB2BOrder
 function in the REST Lab.
The following code snippet is the request data that is submitted to the 
B2B Pavlov
 API:
[ { "OrderID":2103, "OrderDate":null, "@metadata":{ }, "CompanyName":"Vins et alcools Chevalier", "Order_DetailsList":[ { "OrderID":2103, "ProductID":7, "Quantity":2, "@metadata":{ }, "ProductName":"Uncle Bob's Organic Dried Pears", "SupplierName":"Grandma Kelly's Homestead" }, { }, { }, { }, { "OrderID":2103, "ProductID":16, "Quantity":1, "@metadata":{ }, "ProductName":"Pavlova", "SupplierName":"Pavlova, Ltd." } ] }
The request event handler in the 
B2B Pavlov
 API transforms the JSON:
[{"ProductName":"Pavlova",
"CompanyName":"Vins et alcools Chevalier"}]
For more information:
Response Transformation
After transaction processing is complete, API Creator returns a response showing the changes to all rows. This response is useful for client applications to refresh their displays to show update effects. Sometimes, you might override this standard response. For example, you can return an account summary for a posted order.
For more information:
Metadata Action Tags
Request JSON can include 
@metadata
 action tags to active system processing.
For more information about metadata action tags, see Complex Transaction Processing.
Metadata Action Tags for Parent Lookup
ProductIDs
 link Items to products. But partners should not need to know the internal implementation details. Partners can provide product names but not ProductIDs. 
Examine the JSON in the B2B test scripts for inserting order details. The JSON does not look like this:
"Items": [ { "ProductNumber": 16, "Quantity": 1 },
 
CA Live API Creator
 provides lookup processing to provide 
ProductIDs
, given the product names. You specify this by way of the 
LOOKUP
 metadata action tag. Therefore, you can POST requests that look like this:
"Items":[ { "Product": { "@metadata":{ "action":"LOOKUP", "key":"ProductName" }, "ProductName":"Pavlova" }, "Quantity":1 }, ...
But even that does not go far enough. It is unreasonable to ask partners to insert 
@metadata
 action tags. Instead, you can define request event handlers that insert 
@metadata
 action tags in a reusable fashion.
The B2B API samples illustrates how you can inject action tags in a generic manner using the extended properties for a resource and request event handlers. The actions argument specifies a resource name, and subresource path, and which 
insertAction
 to insert. Line 2 results in the 
LOOKUP
 previous insertion, so the client simply provides:
{
"CustomerNumber": "VINET",
"Items": [
{
"Product": {
"ProductName": "Pavlova"
},
"Quantity": 1
},
{
"Product": {
"ProductName": "Uncle Bob's Organic Dried Pears"
},
"Quantity": 2
}, ...
The following image shows the extended properties for the 
PartnerOrder
 resource in the B2B Northwind API that implements this translation:
  Screen Shot 2018-07-20 at 6.50.59 AM.png  
The 
Insert_Lookup_Merge
 request event handler processes these extended properties, as shown in the following image:
  Screen Shot 2018-07-20 at 6.52.40 AM.png  
This request event handler uses the 
insertActions
 shared library routine. You can use the metadata injection logic included in this library routine in other APIs.
For more information:
  • About how to create request event handlers that insert 
    @metadata
     action tags, see Event Handlers.
  • About extended properties, see Extended Properties 
  • About the 
    LOOKUP
     metadata action, see LOOKUP Metadata Action Tag.
     In addition to the 
    Lookup
     metadata action tag, you can also insert/update rows depending on whether they already exist. This works across relationships, for example, you can insert/update an 
    Employee
    , an 
    EmployeeSkill
    , and can create a new skill in a single transaction.
Metadata Action Tags for Merge-Insert
You can also designate that request rows can result in an update of an existing row or, if not present, the insertion of a new row.
For example, you can provide the following JSON using the 
SupplierSelfService
 resource:
{
"CompanyName": "New Supplier",
"ContactName": "New Contact"
}
Because the request event handler inserts the 
MERGE_INSERT
 metadata action tag, the result is that the JSON can update a supplier if it already exists or insert as a new supplier if it does not. You can test this in the REST Lab by calling the 
testMergeInsert
 function:
Sometimes, a provider of data (such as a supplier) may want to send information that may be new, or updates to previously sent information. It is reasonable to ask: Is this a POST or a PUT? It is unwieldy to GET the information first, to determine POST compared to PUT.
Use the 
MERGE_INSERT
 metadata action tag to have 
CA Live API Creator
 determine the operation. 
CA Live API Creator
 activates the metadata action tag using the 
Insert_Lookup_Merge
 request event handler, for the 
SupplierSelfService
 resource. This data owner (the supplier) can create or update their information.
For more information:
Other API Styles
API styles are not limited to basic create, read, update, and delete (CRUD) operations. The B2B API samples illustrate the following 
CA Live API Creator
 functionality and concepts.
Functions
You can create functions as endpoints and functions that operate on resources. For example, you can provide a function to send an email to a designated employee. Even better, you can give an employee a raise using a function, as illustrated in the following image of the function definition:
  worddav373c2c89b05cf5361dfd3a2b9489d546.png  
Test the function using the following call (for example, in the REST Lab):
http://localhost:8080/rest/default/b2bderbynw/v1/EmployeesWithRaises/1/giveRaise?percentRaise=10
You can also:
  • Call resource-oriented functions from Data Explorer.
  • Create functions that are not related to database objects. For example, you can explore the functions that are provided to test the B2B API samples.
For more information:
RPC-style APIs
You can create more explicit APIs. For example, in addition to an 
Employee
 row, you might have a series of child rows of 
Employee
 changes. You can create a more explicit API using functions or using the event sourcing pattern.
For more information:
Security
You can secure the data that is served by your API at the row and column level, and leverage corporate security providers, as described in the following sections.
Custom Authentication Provider
The 
AdminAuthProvider.js
 custom authentication provider sample that is included with the 
B2B Northwind
 API sample authenticates the 
demo
 API user, the system administrator (
sa
) user, and the 
admin
 TeamSpace user (to simplify testing).
Explore the following users:
  • Any user defined in the Employees table (first name is 
    login
    , last name is 
    password
    . Try 
    Janet Leverling
    ).
  • The
    Pavlov
    API user. This user returns user data (the
    ID
    ) used in role permission role filters.
This sample is located in the 
<Live API Creator install>/samples/b2b/devops/libs
 directory. You can also create your own authentication provider for corporate security providers, such as Active Directory (AD) and Lightweight Directory Access Protocol (LDAP).
For more information about how to create custom authentication providers, see Configure Authentication.
Row-Level Security
To ensure that suppliers see only their own data, the 
Suppliers
 role defines a role permission on the
Suppliers
table. In the following row filter:
"SupplierID" = @{ID}
The ID value is returned in the custom authentication provider:
myUserData = {'ID': '7'}; // for multiple globals: ,{...}
You can verify the security in Data Explorer by logging in as the 
Pavlov
 API user (any password). A supplier is returned, unlike the result when you log in as the demo user or the administrator user. You can apply the same technique to Shippers to self-service-register their webhook.
Data Explorer: Automatic, Customizable UI
You can customize your user interface (UI) using Data Explorer in Author Mode. The following image shows Data Explorer in Author Mode:
  Screen Shot 2017-01-06 at 5.57.52 PM.png  
You can:
  • Create a menu of frequently-used tables using the application settings.
  • Explore related data, such as show part information for item within an order, using the Show Parent option.
  • Hide the Main Grid when you navigate to related data by selecting your preferred layout. Given sufficient screen space, hiding the Main Grid reveals a multi-column display panel (the Form and Child Grid). More data becomes visible.
    For more information about how to select your layout, see Data Explorer.
  • Provide explanatory text, such as instructions for end users, in the Info section of the Form.
These options are also available on the Employees screen, which includes images. The 
Customer
 object illustrates the use of attribute grouping and form titles. The 
Supplier
 object illustrates the conditional display of the Region field.
For more information about how to control the order of the fields that are displayed in the Form, how to change the title of the Form, and how to control when fields display in the Form, see Author Mode.
Scripted API Deployment
It is a common requirement to script the deployment of an API, for example to move source control system artifacts into a production environment. You can pattern your own deployments by exploring the scripts that are in the ZIP file.
For more information:
Custom Endpoints That Return HTML
You can create custom endpoints that are not based on database objects and that can return a JSON or HTML response. You can build and deploy simple menus, without worrying about application deployment. For example, you can run a custom endpoint by entering the following URL in your browser:
http://localhost:8080/http/default/b2bderbynw/B2B
You can indicate that requests to your custom endpoint do not require authentication. For example, you might accept a request, reauthorize, reformat the JSON, and then reissue the request onto a resource that you define explicitly.
For more information about how to create custom endpoints that return HTML, see Manage Custom Endpoints.
Code Samples
For more information about code samples for Node.js, Python, and PHP, see Other B2B API Sample Test Scripts.