B2B API Sample

This Business to Business (B2B) sample is a data integration example that illustrates a small but non-trivial system, built using
Layer7 Live API Creator
. This article provides a high-level overview of
Layer7 Live API Creator
and covers beginning functionality and concepts.
lac53
This Business to Business (B2B) sample is a data integration example that illustrates a small but non-trivial system, built using
Layer7 Live API Creator
. This article provides a high-level overview of
Layer7 Live API Creator
and covers beginning functionality and concepts.
The B2B sample includes the
B2B Pavlov
and the
B2B Northwind
API samples. These samples are included with the single-user demonstration package of
Layer7 Live API Creator
that is based on Jetty and with the
Layer7 Live API Creator
Docker container installation. No additional steps are required to load these API samples.
If you have installed
Layer7 Live API Creator
on another Java container, you can also load this API sample.
In this article:
3
The B2B sample illustrates a typical API Server that:
  • Processes requests, such as a partner order POST, from multiple (omni-channel) sources.
    The API definition is not the same as the B2B schema, therefore mapping and transformation logic are required. The
    B2B Northwind
    API demonstrates various concepts using the following variations of the
    PartnerOrder
    resource–the
    PartnerOrder
    ,
    PartnerOrderUsingLookups
    , and
    PartnerOrderWithEvents
    resources.
  • Enforces business logic.
    Layer7 Live API Creator
    helps enforce business logic and security. This includes internal processing, such as credit checks on the customer, that are implemented as rules.
  • Integrates with other systems.
    For example, it alerts the shipper by way of a POST to an external system.
The following diagram shows the flow for this system:
imageLikeEmbed.png
The implementation consists of several rules and a few lines of JavaScript. The B2B sample uses the Northwind sample database as the underlying database.
The server for the single-user demonstration package of
Layer7 Live API Creator
that is based on Jetty and the installation of
Layer7 Live API Creator
on Apache Tomcat are pre-configured for the Northwind sample database. No additional configuration steps are required to access this database.
Resource Definitions & Illustrated Concepts
The following table lists the resources that are defined in the
B2B Northwind
API and explains what each resource attempts to illustrate:
Resource
Concept
AccountSummary
Illustrates a multi-level join of table-based resources.
EmployeesWithRaises
Illustrates the
FullNameVirtual
virtual resource attribute, the
FullNameNPA
non-persistent attribute (NPA) added as the
FullNameNPA
entity resource attribute, the
MgrLastName
parent resource attribute, and a GET event reference to the
logicRow
variable's NPA.
For simple calculations such as FirstName + LastName, you can use NPAs or virtual resource attributes.
For more information:
OrderSummary
Illustrates the following:
  • The
    SalesRep
    resource's
    fullName
    virtual resource attribute.
  • A resource that includes
    ProductName
    as a parent resource attribute.
PartnerOrder
Illustrates resource attribute aliasing, request pipeline driven by extended properties to insert metadata action tags into request, to look up
ProductNumber
from
ProductName
.
For more information about how to define aliases for resource attributes, see Manage Resource Attributes.
PartnerOrderUsingLookups
Illustrates declarative lookups, to find foreign key values from the
Shipper
and
Items.Product
parent resource attributes.
For more information about parent resource attributes, see Manage Resource Attributes.
PartnerOrderWithEvents
Illustrates a PUT/POST event that performs a "fuzzy" lookups.
For more information about how to add virtual resource attributes that perform "fuzzy" lookups during PUT/POST events, see Manage Resource Attributes.
ShipperAPIDef
Illustrates a manual join across two databases. The
ShipperMemos
subresource uses join syntax to do a "fuzzy” join of child records using the
PromoPhone
virtual resource attribute.
For more information about how to add virtual resource attributes that are used in manual entity joins of "fuzzy" children, see Manage Resource Attributes.
ShipperAPIDefHiddenVirtuals
Illustrates the following:
  • "Fuzzy" foreign key lookup scenario.
    For more information about how to set virtual resource attributes with lookup values using "fuzzy" foreign key in GET events, see Manage Resource Attributes.
  • Virtual resource attributes that are hidden, so that you can use manual joins but not return the computed keys.
SupplierAlert
Illustrates using resources to transform data to alert business partners (Suppliers) within the
Post SupplierAlert to accrued Supplier WebHooks
event rule.
For more information about webhooks, see Integrate Data and Systems.
SupplierInfo
Illustrates the following:
  • Integrating multiple databases, joining data from the
    Promotions
    data source.
  • Row-level security. (In the REST Lab, call this resource using the
    Pavlov Supplier
    authentication token).
    For more information about how to call resources using the REST Lab, see Test your API Using the REST Lab.
SupplierSelfServices
Illustrates row-level security and creating or updating data using the
MERGE_INSERT
metadata tag (by way of the
Insert_Lookup_Merge
request pipeline and the extended properties that are defined for this resource.
For more information about this resource, see the "Insert Metadata Action Tags within a Request Pipeline" section.
For more information about data integration and resources to define partner object mappings, see Logic Patterns.
Resource Mapping and Transformation
Resources provide a data independence layer where you can choose attributes and related objects, and alias them, so that your request data can match predefined API agreements instead of your schema.
Layer7 Live API Creator
maps requests to your underlying schema, with full automation for the REST operations.
Use resources for mapping and transformation of requests. For example, the
Process Shipper Webhook
commit event rule uses the
ShipperAPIDef
resource as a mapping definition to transform a (table) order row into the format that the shipper expects:
var shipper = row.Shippers; // object model (row) provides accessors to related objects
var db = "Process Shipper WebHook - ";
var shipperAlert = logicContext.
transformCurrentRow("ShipperAPIDef")
; // ShipperAPIDef resource: transformation
logicContext.logDebug(db + "shipperAlert:\n" + shipperAlert);
if (shipper === null || shipper.OrderChangeWebHook === null) {
logicContext.logDebug(db + "empty / null shipper webhook URL - would have sent\n" + shipperAlert);
} else {
SysUtility.
restPost
(shipper.OrderChangeWebHook, {}, ConstantsLib.supplierAuth, shipperAlert); // find with Control-Space, or Examples (above)
}
For more information about the transformCurrentRow() method, see transformCurrentRow Method.
Key Handling - Generated Keys, Cascade Adds, Lookups
The
PartnerOrderUsingLookups
resource processes incoming
Orders
and
Order Details
. In exploring the schema, note that the foreign key from
Order Details
to
Orders
and
Products
are numbers and that the database generates the
OrderID
.
The following key services address key handling requiring code:
  • Generated keys:
    Layer7 Live API Creator
    obtains the
    OrderID
    from the database, automatically (and return it in the request response to the client).
    For more information about how API Creator returns the key, see Automatic Key Generation.
  • Cascade Add:
    Since the
    Order Details
    are contained within the
    Items
    subresource with a known join clause,
    Layer7 Live API Creator
    inserts the
    OrderID
    into the foreign key of each
    Order Detail
    . This process is automatic, based on schema information about keys and the join definition of the resources that you define explicitly in API Creator. Clients cannot know the
    OrderID
    beforehand and supply their values to link items to orders.
    For more information about the resources that you define explicitly using API Creator, see Customize your API.
  • Lookups:
    Since the
    Product
    resource is designated as a parent resource attribute,
    Layer7 Live API Creator
    uses the supplied value to find the item’s parent, a product, obtain its primary key, and inserts that into each
    Order Detail
    .
Multi-Database Integration using Fuzzy Keys
The
SupplierInfo
resource contains the
PromotionsList
subresource. This subresource includes data from more than one database and can be based on one of the following:
  • Virtual relationships (see table
    Suppliers
    )
    For more information about how to define virtual relationships, see Database Relationships.
  • When the keys do not exactly match (“fuzzy” keys), computed matching keys by way of virtual resource attributes.
    For example,
    Layer7 Live API Creator
    computes the
    ShipperAPIDef.ShipperMemos
    subresource using the
    PromoPhone
    hidden virtual resource attribute.
Logic
The resources that you define explicitly using API Creator reuse the logic that is on the underlying tables. Logic ensures the integrity of your data when update requests are made. For example, we want to:
  • Verify that orders do not exceed customers' credit limits.
  • Provide discounts for healthy orders.
  • Post requests to the
    Pavlov
    supplier when orders are received for their products.
The following sections illustrate how to perform this type of multi-table logic and integration with other systems.
Layer7 Live API Creator
does the logic by way of spreadsheet-like reactive logic that you can extend with server-side JavaScript.
For more information about reactive logic rules, see the conceptual background of Logic.
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 do not need to call them.
The following executable rules apply to all of the resources that you explicitly define using API Creator. Rules can reduce server-side integrity enforcement by over an order of magnitude. Rules provide clear and concise user-readable logic instead of tedious code. The requirements are captured as topics (in the following image, as colored boxes) and linked to the logic for traceability:
B2B_Rules.png
Request Transformation
To transform the API, you can manipulate/transform the request data using request pipelines. API Server invokes request pipelines for every request, after it receives the request but before it processes request/row mapping and reactive logic.
Response pipelines enable you to reformat the response data after system processing.
For more information about response pipelines, see Pipeline Events.
Insert Metadata Action Tags within a Request Pipeline
When integrating with systems that own certain data, you may find it necessary to process data by inserting it (if it does not already exist), or updating it (if it does). Because it is often impractical to request that clients supply such information in their request data, you can define request pipelines that insert metadata action tags. As best practice, define extended properties in your resources, so that you can reuse a request pipeline over multiple resources to help insert metadata action tags into the incoming request.
The
Insert_Lookup_Merge
request pipeline (and the extended properties that are defined for the
SupplierSelfService
resource) is an example of a request pipeline that inserts metadata action tags.
It uses the
insertActions
shared library routine. You can use the metadata injection logic included in this library routine in other APIs.
Other API Styles
API styles are not limited to basic create, read, update, and delete (CRUD) operations. The B2B API samples illustrate the following
Layer7 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 (the first name is
    login
    and the 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
Supplier
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 (use any password). A supplier is returned, unlike the result when you log in as the
demo
API user or the
admin
TeamSpace 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:
DataExplorer_AuthorMode.png
You can:
  • Create a menu of frequently-used tables using the application settings.
  • Navigate to related information, 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.
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.
Script API Deployment
You can use the B2B sample scripts to pattern API deployments, for example, to move source control system (SCS) artifacts into a production environment.
For more information about the B2B sample scripts, see B2B API Sample Scripted Deployment.