Getting Started‎ > ‎

Business to Business Example

This Business to Business (B2B) example is a data integration example that illustrates a small but non-trivial system, built using Live API Creator. The concepts described are intermediate. Complete this example to confirm you have the key product concepts and are ready to begin an API.

This document covers:

  • How to install the B2B example.
  • The Readiness Lab. Download and run a series of fun exercises.
  • How to test the B2B example.
  • Concepts. This API illustrates many key Live API Creator features. For background information, see the referenced links.
  • Advanced topics. Extends the basic B2B example to illustrate advanced extensibility.

For more information:

Prerequisites:
  • You have the self-contained, single-user version of Live API Creator based on Jetty up and running.
For more information about installing this demonstration package, see Install the Single-User Demonstration Package.
  • You have a basic understanding of Live API Creator and have completed the basic training for logic, API creation, and JavaScript extensibility.
For more information about Live API Creator, see Getting Started.

APIs: Modern Application Architecture

The following diagram illustrates a typical B2B system and 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. The B2B example uses

Select the Attributes to be Returned by your Resource

 Northwind as the central system. This system:

  1. Processes omni-channel requests. API server accepts requests from multiple channels, such as mobile devices, partners, WebHooks, and Web apps. The API definition is not the same as the B2B schema, providing mapping and transformation logic.

  2. Enforces Business Logic. Business policy for logic and security includes internal processing such as Credit Checks, and external processing such as sending alerts to Shippers, by posting a request in an agreed-upon API format. As in item 1, this API does not match the B2B schema.

  3. Integrates multiple databases. Provides an API for a device that shows a Supplier only their promotions, drawn from two different databases.

  4. Provides UI. Enables partners (Shippers, Suppliers) to view their information on a tablet, PC, etc.
Such systems are complex and time-consuming to build, using traditional approaches based on interface documentation (for example, RAML), frameworks (for example, Jersey, Jackson, JPA, etc), and IDEs to build a substantial amount of business logic. Use this example to explore the Live API Creator alternative, which requires about a dozen lines of JavaScript, a dozen rules, and five point-and-click resources.

Install the B2B Example

During development, you often may import API definitions using API Creator. This example uses an install script that automates deployment, just as you might from a source control system. This install script:
  • Creates APIs for B2B and Pavlov (including shared libraries and authentication providers).
  • Performs self-diagnostics, as described in the following sections.

These instructions apply to the self-contained, single-user version of Live API Creator, which is a downloadable demonstration package based on Jetty. This example is suitable for evaluations and training, so we encourage you to download it.

For more information about downloading the B2B example, see the CA Live API Creator trial page.

  1. Download and unpack the b2b.zip file to a local directoryWe recommend creating a directory (for example, LAC) to contain your Live API Jetty install and your APIs, in particular Live API Creator. This containing directory is important for the Node Install step.
    The following image shows the suggested directory structure
    : (Click the image to enlarge.)

    The zip expands into a source control system-directory structure (scs). The src folder contains the API export files (for example, b2b/scs/projects/b2b/src/b2bnwderby.json), shared library code, build scripts, and test programs.
  2. cd to your unzipped b2b folder.
  3. Install the various utilities in Node.js by completing the following steps:
    1.  Install Node.js and all of the Live API Creator npm packages.
      Important! Install the npm packages in a folder that contains your B2B folder.
      For more information about how to install Node.js and npm packages, see Install NodeJS.
    2. Verify your Node install and that it is current by executing the following command:
      (Mac) Execute the following script in Terminal:
      lacadmin --version
      (Windows) Execute the following command from a Command window:
      lacadmin -v
      The supported version is >2.2.3. For more information about the versions of Node.js that Live API Creator supports, see Supported Platforms.
    3. Run the install script by executing the following command:
      (On Mac) Execute the following script in Terminal:
      sh install.sh derby
      (On Windows) Execute the following command from a Command window:
      install.cmd derby
      These install procedures also perform self-diagnostics. The install script invokes a Node.js program (and optionally, if you have installed it, Python) to post an order and verify it was successful.
A confirmation screen similar to the following appears: (Click the image to enlarge.)

Recap

Explore this Business to Business Example to see all the code/rules used to create the B2B Derby NW API. Let's review some highlights.

The post/verify programs execute the flow shown in the "Modern Application Architecture" diagram:
  1. An order is posted through the resource named PartnerOrder. This provides the mapping and transformation logic to process the order from a partner.
  2. The post activates the business logic. You can compute order totals with product-based discounts, adjust the customer balance, and ensure that the credit limit is not exceeded using about 10 rules. One of these rules (Supplier Alert) alerts the supplier Pavlov. It's a JavaScript event (about 12 lines) to check what was ordered, and if it's a product supplied by Pavlov, post an alert to the API b2bderbypavlov (representing Pavlov). The SupplierAlert custom resource is used for mapping and translation logic.

While this application contains only a few dozen lines of logic and code, it illustrates many other patterns common to B2B systems. For example, the SupplierInfo resource integrates multiple databases and enforces row-level security that enables safe and direct access by partners to view their data.

For more information about the SupplierInfo resource, see the b2b/scs/projects/test/node/verifySupplier.js JavaScript source code file.

At the operational level, the install script illustrates a typical team development scenario. The scs folder mimics how you might maintain API Creator objects in a source control system. It includes loadable libraries used for extensibility. The installation scripts provide examples of command line scripting, and API access from Node, Python and PHP programs, or test it in the REST Lab, as explained in the SupplierInfo resource comments.

The B2B is a key resource in understanding what Live API Creator can do and how to use it. The following sections walk you through the concepts illustrated in the B2B sample.

After exploring, you can work through the Readiness Lab, which are the exercises that we believe indicate that you are ready to join a project.

For more information:

Readiness Lab

You can then verify your project-readiness to use Live API Creator using the set of labs built using this API. The labs are located in the b2b/readinessLabs/readinessLabs/Readiness - Live API Creator.docx file (and in the PDF file). You unzipped this file when you installed the B2B example.

Note: You have completed the first lab by installing the B2B Example and testing the API.

Test the B2B Example

A key strength of the API architecture is that you can call APIs in a variety of ways, across languages and architectures. You can test B2B in the using:

  • The REST Lab
  • cURL
  • The Command Line Interface
  • Node.js programs
  • Python
  • PHP

Your API is therefore useful not only for integration, but web apps, scripting, and a host of other applications. Examples of each of the testing methods are provided in your install zip.

For more information about how to test the B2B example, see Test B2B.

Concepts Illustrated

The B2B system provides an excellent study in creating an API back end. It typically follows a process like this:
  1. API creation. Connect to your database for a default API - point-and-click customization - nested docs, aliases, etc. This addresses your SQL and Rest handling.
  2. Logic. Ensure the integrity of your data with spreadsheet-like reactive logic, extensible with server-side JavaScript.
  3. Security. Protect data security down to the row and column level by defining table permissions for a role. Integrate authentication with existing corporate security.
  4. Data Explorer. See/update your data with automatically created interfaces providing Filtering, Master/Detail, navigation to related data, etc. Data Explorer is suited for Testing, Prototypes, and Back Office Data Maintenance.
  5. DevOps. See how to save API definitions to a source control system, and build scripts to recreate them
The following sections provide a walk-through of these services.

API Creation and Customization

The first step is to create your API and customize ("shape") it as required. Swagger documentation is always available. Use it with various tools to generate objects in C#, Java, etc.

Connect to Create Default API

The B2B system connects to the database and creates end points for each table, view, and stored procedure. There is no code generation or deploy. The B2B system was created using the install scripts.

Resources: Mapping and Transformation

The default API is a good start, but it conforms to your schema. In most cases, you will want to "shape" your API.

For example, API agreements with partners typically do not match internal schema definitions. Custom resources provide key services to map API agreements onto your database and logic:
  • Choose/rename columns, which is a simple approach to mapping and transformation logic. In this image, PartnerOrder.OrderID is aliased to OrderNumber.
  • Specify resource nesting so that B2B requests can include multiple kinds of data, such as the Order and Items.
  • You can use non-persistent attributes (NPA) in resources. For example, in the OrderSummary resource, the SalesRep's fullName is an NPA.
  • You can combine parent subresources into the containing resource. For example, in the OrderSummary resource, the Product information appears with the Order_DetailList properties.
  • Custom resources reuse the logic on the underlying tables.
For more information:

Metadata Tags for Parent Lookup

Examine the JSON in the B2B Test for inserting Order Details. It does not look like this:

"Items": [
  {
    "ProductNumber": 16,
    "Quantity": 1
  },

This would be a typical request, but how would a partner know ProductNumbers?

API Server supports requests that look like this:

  "Items":[  
     {  
         "Product":{  
                 "@metadata":{  
                     "action":"LOOKUP",
                       "key":"ProductName"
                    },
            "ProductName":"Pavlova"
            },
         "Quantity":1
         }, ...

You can link child rows to parent rows by inserting @metadata action tagswithout the requirement for the client to supply autonum identifiers (which they may not known) using services. For example, with the Lookup function, you can use Request Events 200 to automatically insert @metadata tags.

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 using related services.

For more information:

  • About linking child rows to parent rows by inserting the @metadata action tags, see Complex Transaction Processing.
  • About the engine services for additional interaction, such as the LogicContext object, see Quick Reference.
  • About the Lookup metadata action, see Lookup Metadata Action.
    Note: In addition to lookup, 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 create a new Skill, all in one transaction.
  • About the Request Events 200, see Extensibility.

Multi-database Resources

The Resource SupplierInfo joins data from two different data sources. Explore the Data Sources page, and observe the relationship nw:Suppliers -> promos:promotions, based on tables in two different databases. You can test this in the REST Lab, as explained in the SupplierInfo resource comments.

Resources: leverage with SysUtility

You can manipulate resources using SysUtility services. This is illustrated in the Alert Pavlov event.

For more information about how to manipulate resources using the SysUtility object, see The SysUtility Object.

Logic

Logic ensures the integrity of your data when update requests are made. For example, we want to:
  • Verify orders do not exceed customers' credit limits.
  • Provide discounts for healthy orders.
  • Post requests to our supplier Pavlov when orders are received for their products.
The following sections illustrate how to perform such multi-table logic, and integration with other systems, by way of spreadsheet-like reactive logic, extended with server-side JavaScript.

Declarative Reactive Rules

Rules are spreadsheet-like expressions (coded in JavaScript) defined on tables and columns. API Server automatically applies them (reacts) to all submitted updates. You don't need to call them. The following executable rules apply to all custom resources.

Rules can reduce server-side integrity enforcement by over an order of magnitude, with clear and concise user-readable logic instead of tedious code. The requirements are captured as Topics (in the following image, as blue, green, and red boxes), and linked to the logic for traceability.

The following rules ensure that:
  • Check Credit. Rolls up items and orders to verify that the customer's credit limit is not exceeded (if a validation is exceeded, the request results in an exception and the transaction is rolled back)
  • Healthy Food Discount. Provides a discount to customers ordering things like fruits and fish
  • Supplier Alert. When orders are detected for supplier Pavlov, our business agreement requires that we post the order to Pavlov.
  • Shipper Alert. When orders have an assigned shipping company, alert them to order changes

For more information:

Extensibility: Table Events

Reactive logic is powerful. Extensibility is provided by server-side JavaScript, to ensure there are no limits.

For more information:

  • About viewing an example of Bill of Materials solved with a few rules, see the Reactive Logic Tutorial.
  • About a list of the JavaScript extension points, including their supplied context, see Quick Reference.
The following Orders commit event posts a web hook to alert Shippers of order changes. The following image shows the commit event on the Manage, Rules, By topic tab:

Where the commit event code is:

var shipper = row.FK_Orders_Shippers;
if (shipper !== null) {    // resource defines transform: cols, aliases, related objects
   var transform = logicContext.transformCurrentRow("ShipperAPIDef");
   B2B.sendToWebHook(transform, shipper.webHookURL);
}

This code posts an order and OrderDetails to the Suppliers WebHook. This illustrates several key patterns of B2B Integration:

  • Transformation logic. The format of the post is defined by the custom resource ShipperAPIDef. It is a common integration pattern to use resources for mapping and translation, leveraging their ability to choose/rename attributes and related objects.
  • Event handling. Events are a powerful way to react to database changes, regardless of the execution path.
  • Posting. The post is done in sendToWebHook.
  • WebHook target. Shippers can register for web hooks by way of self-service APIs that set shipper.webHookURL, as described in the following "Security" section.
For more information:

Extensibility: Loadable Libraries

If you detect patterns in your logic, you can provide reusable solutions that rules can invoke. The following code provides a re-usable function that implements the "web hook" pattern (shown in the following image of the Create, API Properties, Libraries, Your libraries tab):

This is a generic service. You can use your own applications to transform a table row into a business object (as defined by a resource) and post it to the registered web hook (the supplier's URL).

You can load logic libraries (such as transformToHebHook), as described in the following "Scripted API Project Deployment" section.

For more information about how to load logic libraries, see Logic Libraries.

Security

You can secure the data 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 install zip contains and installs the RESTAuthSecurityProvider.js custom authentication provider. This custom authentication provider authenticates:
  • Admin and demo (to simplify testing).
  • Any user defined in the employees table (first name is login, last name is password. Try Janet Leverling).
  • The user Pavlov. This returns User Data (the ID) used in role permission role filters.

This configuration is part of the API export, so occurs when you ran the install script. The authentication provider code is located in the zip in the sharedlibs/src directory. The configuration is installed in the script in the sharedlibs/build directory. You can create your own authentication providers for corporate security providers, such as Active Directory (AD) and Lightweight Directory Access Protocol (LDAP).

Note: Admin users are used for signing in to Live API Creator. Application users are used for signing in to API Server for data access. Custom authentication providers address app users.

For more information:
  • About how to use a custom authentication provider, see Authentication.
  • About how to use Admin users to sign in to Live API Creator, including the difference between admin and application security, see Security.

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 auth provider:

myUserData = {'ID''7'};  //  for multiple globals:  ,{...}

You can verify this in Data Explorer by logging in as Pavlov (any password). One supplier is returned, unlike the result when you login as demo or admin.

You can apply the same technique to Shippers, to self-service-register their web hook.

Data Explorer: Automatic, Customizable UI

You can customize your user interface using Data Explorer in Author Mode. The following image shows Data Explorer in Author Mode (click the thumbnail to see the full screen):


Note: These features are also shown on the Employees screen, which includes images as well.

The Customer object illustrates the use of attribute grouping and form titles. The Supplier object illustrates the conditional display of the Region attribute.

  • You can create a menu of frequently-used tables using the application settings.
For more information about adding and defining the layout for a table, see App Settings.
  • You can explore related data, such as show part information for item within an order, using the Show Parent option.
  • You can auto hide the main grid panel when you navigate to related data using Panel Control. Given sufficient screen space, this often reveals a multi-column display panel. Much more data becomes visible.
For more information about attribute grouping (grouping form fields), form titles (controlling form titles), and controlling the display of columns, see Author Mode.

Scripted API Project Deployment

It is a common requirement to script the deployment of an API, for example to move source control system artifacts into production. You can pattern your own deployments by exploring the scripts in the zip.

For more information:

Custom Endpoints that Return HTML

You can define custom endpoints that are not based on database objects. They can return a variety of response types, such as JSON or HTML. You can build and deploy simple menus, without worrying about app deployment. For an example, click the following link: localhost http://localhost:8080/http/default/b2bderbynw/B2B.

In addition, you can configure custom endpoints to not require authentication. For example, you might accept a request, re-authorize, re-format the JSON, and then re-issue the request onto a custom resource.

For more information about custom endpoints that return HTML, see Custom Endpoints 200.

Code Samples

The sample installs and runs code samples for Node.js, Python, and PHP. You can find these and explore them, under b2b/scs/projects/test.

Advanced Topics

The following sections extend the B2B example to illustrate JavaScript control over requests:

Request Transformation

The requirement in this example is for the Pavlov API to transform the request JSON received in the POST. With this API, you can use request events to manipulate/transform the request data.

For more information about request events and JavaScript extension points, see Quick Reference.

The code shown in the following image performs such a translation. You can use the logs to view its operation.

The following code snippet is the request data submitted:

[  
   {  
      "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 following code snippet is the transformed request, illustrating control over the hierarchy, attribute presence/absence, etc.:

[{"ProductName":"Pavlova",
"CompanyName":"Vins et alcools Chevalier"}]

The most common usage of Request Events is to insert Metadata tags (discussed above).
Subpages (1): Test B2B