Docs‎ > ‎CA Live API Creator‎ > ‎Create‎ > ‎Resources‎ > ‎REST APIs‎ > ‎Data Integration‎ > ‎

Business to Business Example

This Integration example illustrates a small but non-trivial system, built using API Creator. The concepts here are advanced, so you should explore this only after you have completed basic training for logic, API creation, and JavaScript extensibility.  

This document describes 
  • Installation: how to install the sample

  • Test: how to run it

  • Concepts: this project illustrates many key product features - follow the provided links for background information

  • Advanced Topics: extends the basic sample to illustrate advanced Extensibility

APIs: Modern Application Architecture

The diagram below illustrates typical aspects in the Application Economy: connecting multi-channel transaction sources with logic that governs multiple databases and partner interactions.  APIs play a central role in enabling such systems to interact.

In this example, we use Northwind as a system that:
  1. Processes Multi-channel Business: the API server accepts inputs from mobile devices and partners.

  2. Enforces Credit Limit checks: the business logic to ensure that customer balance <= credit limit, over many User Stories (Place Order, Pay Order, Move Order to new Customer, Change Order Products, Change Order Quantities, etc.)

  3. Issues Partner Alerts: if parts are ordered for supplier Pavlov, Post a request in an agreed-upon API format (e.g., does not match the Northwind schema)
Such systems are complex and time-consuming to build using traditional approaches based on interface documentation (e.g., RAML), frameworks (e.g., Jersey, Jackson, JPA, etc), and IDEs.


B2B Installation

The Jetty version already contains the 2 Derby Databases for this sample: Northwind and Pavlov.  Click on the diagram shown here.
   

Manul Import vs Automated Script

During development, you may often Import using the API Creator.  Here, however, we will use a script that automates deployment as you might from a source control system.  This script:
  • Creates API projects for Northwind-B2B and Pavlov, and 
  • Loads and configures some shared libraries and authentication providers


Install the Business to Business (B2B) API projects as follows:
  1. First, download and unpack this zip.  

    As shown at the right, the zip expands into a typical source control directory structure.  The src folders contain the json export files from the API projects (e.g., scs/projects/b2b/src/Northwind-B2B.json). 

  2. If you've not already done so, install the Admin CLI

    • Important: if you have already installed this, ensure you are at version 2.0.68 or higher:
      lacadmin --version

  3. Run the install procedure.  Open a Terminal / Command Window, and:
  • On the Mac
  1. cd to the zip folder created, above

  2. Run the script below in a Terminal window:
sh install.sh


  • On the PC, run install.cmd, either from the file explorer, or (to see output) from a Command window:
install.cmd




Test

You can test this as described below.  After running the test, verify that:
  1. a row was added to the only table on the Pavlov API

  2. the credit check rules adjusted the order and customer, as shown in the screen shot
When you have succeeded, you will see "statusCode":201, ....

Using the REST Lab

in the Northwind-B2B API, use the REST Lab to Post this to the Resource PartnerOrder:

{
   "CustomerNumber": "VINET",
    "Items": [
              {
                 "ProductNumber": 16,
                 "Quantity": 1
               }
         ]

}


        Note: be sure to select End Point Type = Resource, and Resource = PartnerOrder


Using Curl

Open a command window, and enter the following, to simulate the receipt of an order from a remote partner:

curl -H "Authorization: CALiveAPICreator Bzn8jVyfOTiIpW6UQCgy:1" -H "Content-type: application/json" -d '{"CustomerNumber": "VINET","Items": [{"ProductNumber": 16,"Quantity": 1}]}' -X POST http://localhost:8080/rest/default/nwindb2b/v1/PartnerOrder


On some versions of curl (e.g., many PC versions), you must escape quote the command:

curl -H "Authorization: CALiveAPICreator Bzn8jVyfOTiIpW6UQCgy:1" -H "Content-type: application/json" -d "{\"CustomerNumber\": \"VINET\",\"Items\": [{\"ProductNumber\": 16,\"Quantity\": 1}]}" -X POST "http://localhost:8080/rest/default/nwindb2b/v1/PartnerOrder"

When you have succeeded, you will see "statusCode":201, .

Using Command Line (NodeJS)

If you have not already done so, you will need to install the Node Command Line.

This example is using MAC shell.  For Windows, precede the command with 'call lac' (an alias for liveapicreator).  

#! /bin/bash
#login to 2 different servers (For WAR change to localhost:8080/APIServer)
liveapicreator login -u demo -p Password1 http://localhost:8080/rest/default/nwindb2b/v1 -a localnw
liveapicreator login -u demo -p Password1 http://localhost:8080/rest/default/pavlov/v1 -a pavlov
liveapicreator status
#Show current state
liveapicreator use pavlov
liveapicreator get main:PARTNERORDERS 

#swtich projects
liveapicreator use localnw

#Post an order to northwinds b2b Partner
liveapicreator post PartnerOrder -j '{ "CustomerNumber": "VINET","Items": [ {"ProductNumber": 16, "Quantity": 1 } ] }'

#Switch Projects and show new partner orders 
liveapicreator use pavlov
liveapicreator get main:PARTNERORDERS 

Verify the script runs without error, and the last line returns data.

Using Data Explorer

You can also use the Data Explorer (see the diagram below):
  1. Start the Data Explorer, using the new tab as shown below
    1. Login as user Janet, password Leverling (this tests the Custom Authentication Provider)
  2. Select the table Orders
  3. Select an Order as shown below
  4. Insert a new Order Details row
  5. Click the ^ in the Product Name to Lookup a Product
    1. use the ProductName field
    2. enter Pav
    3. Click Search
    4. Select that Product to return to the original form
  6. Click Save
If you check the Pavlov data, you'll see a new entry.


Readiness Training

The zip file contains a document (readinessLabs/Readiness - Live API Creator), describing a set of labs you can use to verify your readiness to use CA Live API Creator.  Before executing the lab, be sure you have a Basic understanding.

You gain practical exposure to: 
  • Extensibility – how do I extend rules, and utilize existing libraries?

  • Debugging – how do I diagnose and correct bugs?

  • Manageability – since there is no code gen, how do I address SCS (Source Code Control Systems) and DevOps deployment?
Note: with the Install and Test instructions above, you have already completed the first Lab.

Concepts Illustrated

This application illustrates several key concepts below. 

Basic Services: API and Logic Creation

The B2B system was built by connecting to the database, and entering the several Reactive Logic rules shown here.  These rules apply to the data, so address all the User Stories noted above.


Resources: mapping and transformation

API agreements with partners typically do not match internal schema definitions.  Custom Resources provide key services to map API agreements on to your database, and logic:
  • Choose / rename columns, a simple approach for mapping and transformation logic (note, for example, that PartnerOrder.OrderID is aliased to OrderNumber)

  • Specify resource nesting, so B2B requests can include multiple kinds of data, such as the Order and Items, above

  • And, of course, Custom Resources automatically reuse the logic on the underlying tables

Resources: leverage with SysUtility

Use SysUtility services to manipulate resources.  This is illustrated in the code snippet shown below.


Extensibility: Table Events

The Commit Event shown here is a good example of JavaScript extensibility.  The following code creates a resource instance for the current order (with mapping / transformation logic as noted above), and posts it to the supplier Pavlov.



Extensibility: Loadable Libraries

Or, if you detect patterns in your logic, you can provide re-usable solutions which can be invoked from rules.  The following code has the same effect as above:

if (row.FK_Order_Details_Products.FK_Products_Suppliers.CompanyName == "Pavlova, Ltd." ) {
var response =  postResourceTo("SupplierReport", 
        { sysfilter: "equal(OrderID:'" + row.OrderID + "')" },          // filter
        req.baseUrl.replace("nwindb2b","pavlov") + "v1/SalesReports",   // supplier URL
        { headers: { Authorization: "CALiveAPICreator supplier:1" }});  // supplier auth
    logicContext.logDebug("***Pavlov - POST SupplierReport to Pavlov - " + response ); 
}

You can load logic libraries (such as postResourceTo) like this.  

Data Explorer Author Mode

Data Explorer provides not only a default User Interface, but provides Author Mode to customize your UI:


Custom Authentication Provider

Security involves Authentication (who can login in) and Authorization (what resources and data they can access).  Default Authentication (intended mainly for development) enables you to define Users in the API Creator.  In most cases, production will use Custom Authentication, where you can authorize users using existing security data such as LDAP, Active Directory etc.

A Custom Authentication Provider is a plug-in JavaScript module that the system calls when a user authenticates using the special end point @authenticate.  It is passed the credentials (user, login, etc), and returns the list of Roles used for Authorization.  (Note: when you use a Custom Auth Provider, Users you define in the API Creator are not used.)

The install zip above contains and installs a Custom Authentication Provider called RESTAuthSecurityProvider.js.  It authenticates admin and demo, and also any user defined in the employees table (first name is login, last name is password).

This configuration is part of the API Export, so occurs when you ran the install script.  The actual Auth Provider code is also in the zip (under sharedlibs/src), and is also configured in the install script (sharedlibs/build).

Explore Custom Authentication Providers here.  You might create your own Authentication Providers for AD, LDAP, etc.

Note: do not confuse Admin Users (used to sign in to the API Creator) and App Users (used to sign in to the API Server for data access).  Custom Authentication Providers address App Users.

Scripted API project deployment

It is a common requirement to script the deployment of an API project, for example to move Source Control System (scs) artifacts into production.  The Scripted Creation (described above) uses techniques described in Import.  You can explore the scripts in the zip, to pattern your own deployments.

Using Request Events to transform requests

You can use Request Events to manipulate/transform the request data.  This enables you to impose your own style on the JSON, and to adapt any external JSON to the dialect automated by the API Server.

@metadata tags to resolve foreign keys

API Server provides services to Insert @metadata action tags.  Typical uses:
  • Link child rows to parent rows (as shown below in Advanced Topics)

  • Direct the system that supplied data should be treated as either an update or on insert (depend on whether the data already exists)

Recap

The material above shows all the code / rules used to create the Northwind-B2B API, that satisfy our requirements noted at the top of this page:
  • a few resources, for mapping and transformation logic
  • 5 rules, for Check Credit
  • a short JavaScript event handler, to post an message to a supplier
These used 2 loadable libraries.  The entire implementation was therefore these API Export, and these 2 libraries.  These were packaged into the src tree of the zip, with a script to load them into your API Server.

Advanced Topics

We now extend the example to illustrate JavaScript control over requests.

metadata Tags

In our example above, the partner Posted a request that included the ProductID.  This may be reasonable, but sometimes this key is unknown.  Instead, it might be required to supply the ProductName.

You can use Services to Insert @metadata action tags to link child rows to parent rows, without the requirement for the client to supply autonum identifiers (which they may not know).  Related services enable you to designate that request rows can result in either an update of an existing row, or (if not present, the insertion of a new row.

Put the following to PartnerOrder_noID:

 
   "CustomerNumber":"VINET",
   "@metadata":{  
      "action":"INSERT"
   },
   "Items":[  
      {  
         "Quantity":1,
         "Product":{  
            "@metadata":{  
               "action":"LOOKUP",
               "key":"ProductName"
            },
            "ProductName":"Pavlova"
         }
      }
   ]
}



Request Transformation

The requirement here is for the Pavlov API to transform the request json received in the Post.   This project illustrates a powerful feature whereby you can use Request Events to manipulate/transform the request data.
 
The code shown at right performs such a translation.  You can use the logs to view its operation.

Here is the request data provided:

 
   "OrderID":2004,
   "ProductID":16,
   "Quantity":1,
   "@metadata": 
      "href":"http://localhost:8080/rest/default/nwind/v1/SupplierReport/2004~16",
      "checksum":"A:4fd7e1dbbf365ade"
   },
   "Product": 
      "ProductID":16,
      "ProductName":"Pavlova",
      "@metadata": 
         "href":"http://localhost:8080/rest/default/nwind/v1/SupplierReport.Product/16",
         "checksum":"A:b0cff00a40a1e611"
      }
   },
   "Order": 
      "OrderID":2004,
      "CustomerID":"VINET",
      "@metadata": 
         "href":"http://localhost:8080/rest/default/nwind/v1/SupplierReport.Order/2004",
         "checksum":"A:94f30334a748cea0"
      },
      "Customer": 
         "CustomerID":"VINET",
         "CompanyName":"Vins et alcools Chevalier",
         "@metadata": 
            "href":"http://localhost:8080/rest/default/nwind/v1/SupplierReport.Order.Customer/VINET",
            "checksum":"A:74542944863a7aa2"
         }
      }
   }
}


And here is the transformed request, illustrating control over the hierarchy, attribute presence / absence, etc.

 
   "ProductName":"Pavlova",
   "CompanyName":"Vins et alcools Chevalier"
}


ċ
b2bscripts.zip
(6121k)
Val Huber,
Feb 18, 2016, 5:23 PM