IBM API Connect - Development Best Practices
IBM API Connect - Development Best Practices
Revision control:
Table of Contents
1. Purpose.............................................................................................................................................................
2. Summary..........................................................................................................................................................
3. Best Practices:..................................................................................................................................................
3.1 Designing APIs/Services:.........................................................................................................................
3.2 Gateway Script Coding Practices:............................................................................................................
1. Understand the Context and Requirements.................................................................................................
2. Best Coding Practices-...................................................................................................................................
3. Handle Errors and Exceptions Gracefully....................................................................................................
4. Optimize Performance................................................................................................................................
5. Use the API Connect Context Object Effectively.........................................................................................
6. Avoid Global Variables................................................................................................................................
7. Follow Coding Standards and Documentation............................................................................................
8. Avoid Synchronous Code............................................................................................................................
9. Testing and Debugging...............................................................................................................................
10. Security Considerations............................................................................................................................
11. Monitor and Log Important Information..................................................................................................
12. Adhere to API Connect Rate Limits and Quotas........................................................................................
3.3 XSLT Coding Practices:.........................................................................................................................
1. Understand the Use Case and Requirements.........................................................................................
2. Best Coding Practices..............................................................................................................................
3. Handle Missing or Optional Data Gracefully...........................................................................................
4. Efficient Use of Variables and Parameters..............................................................................................
5. Handle Errors Gracefully.........................................................................................................................
6. Optimize for Performance......................................................................................................................
7. Keep the XSLT Compact and Maintainable.............................................................................................
8. Ensure Compatibility with API Gateway Context....................................................................................
IBM App Connect – Development Best Practices
1. Purpose
The purpose of this document is to provide best practices for the IBM API Connect
development where the developers can refer and follow the same for development in
projects.
2. Summary
Developing integration solutions with IBM API Connect (APIC) requires adherence to best
practices to ensure efficient, maintainable, and high-performing applications. Below are
some of the points to consider while developing the APIs using IBM APP Connect
Enterprise.
3. Best Practices:
IBM API Connect is a sophisticated product– There are often several ways to do things…
which is the best? – Understanding how API Connect works allows you to write more
efficient Workflows and debug problems more quickly
It’s better to design your APIs to be as efficient as possible from day one– Solving bad design
later on costs much more– Working around bad design can make the problem worse!
Here are some best practices for designing APIs in IBM API Connect:
Use a model-driven approach: Use IBM API Connect Manager to build APIs as
integration flows using a code-free, model-driven approach.
Use the REST API Editor: Use the REST API Editor to graphically define resources,
models, and operations in a REST API.
HTTP Methods: Utilize HTTP methods correctly for CRUD (Create, Read, Update,
Delete) operations. GET for retrieving data, POST for creating resources, PUT or
PATCH for updating resources, and DELETE for deleting resources.
URL Structure: Keep URLs hierarchical and predictable. Use all are small latter’s
and versioning including the Query parameters and other.
Implement Version Control: Implement versioning to manage changes to your API
over time. This ensures backward compatibility and allows clients to adapt to changes
gradually. Versioning can be done through URL versioning (e.g., /v1/resource) ,API
version and Swagger versioning.
Security:
Manage Access Controls: Define and enforce appropriate access controls to restrict
unauthorized access .
Apply the Roles and Permissions to restrict the Unauthorized access to integration
resources.
IBM App Connect – Development Best Practices
Allow the messages from the valid source, check whitelisting of the source IP
whenever request initiates.
Implement proper authentication and API security: Secure your API by implementing
authentication mechanisms such as OAuth, JWT (JSON Web Tokens), API keys, or
basic authentication.
Secure Data in Transit and at Rest: Implement encryption and secure protocols to
protect sensitive data. Additionally, Implement the schema validations to validate the
message format and tags whether it’s in expected format of the provider.
Rate Limiting: Implement rate limiting to prevent abuse and ensure fair usage of your
API resources. Define limits on the number of requests allowed per time interval for
each client or API key.
Standardize error messages: Improve the API consumer's experience by providing
proper error handling.
Screen everything servers accept: Screen everything servers accept and reject any
large data or content transmissions, create a specific object which can allowed lengths
in the respective content allow.
Processing Logic:
Various options available– GatewayScript– Mapping– XSL
• Performance characteristics of the different options is rarely an issue– Choose
an option based on skills, ease-of-use and suitability for the scenario
• Think carefully before mixing transformation options in the same message
flow.
Before writing any code, make sure you fully understand the problem you're trying to solve and the
requirements of the API. This will help you write efficient scripts and avoid unnecessary complexity.
Determine Input/Output: Know what data you’ll receive in the request and what you need to send back
in the response.
Identify the Stage of the Request: Know whether the script is being applied before the request reaches
the backend (e.g., transformation, validation) or after the response is returned (e.g., post-processing).
IBM App Connect – Development Best Practices
better use "buffer" datatype (works for up to 1GB size) than "buffers" datatype (has no size limit,
list of buffer objects internally)
better use "buffer" datatype (works for up to 1GB size) than "buffers" datatype (has no
size limit, list of buffer objects internally)
Use Template Literals:
o Instead of string concatenation:
javascript
Copy code
console.log(`User ${name} has ${count} messages.`);
javascript
Copy code
const age = 25;
const person = { name: 'John', age, greet() { return 'Hi!'; } };
javascript
Copy code
try {
const config = require('./config.json');
} catch (error) {
console.error("Config file not found");
}
Use meaningful variable names: Make variable names descriptive and consistent.
Follow indentation and spacing: Use a consistent code format to make your code easy to read.
Comment wisely: Add comments to explain why certain decisions were made, not what the code
does.
Write Idempotent Code - Ensure that code produces the same result when executed multiple times with the
same input. This is crucial in APIs and database operations.
Keep functions short (e.g., 20–30 lines). If a function grows too long, break it into smaller helper functions.
IBM App Connect – Development Best Practices
javascript
Copy code
// Poor
function data() {}
// Better
function fetchData() {}
ariable names should clearly indicate their purpose:
javascript
Copy code
// Poor
let x = 10;
// Better
let userAge = 10;
Leverage Native APIs: Use GatewayScript’s built-in APIs (e.g., session, context, hm for headers
and metadata) for better integration with DataPower features.
JSON Parsing: Use JSON.parse() and JSON.stringify() effectively for JSON transformations.
Avoid Hardcoding Secrets: Store secrets and sensitive configurations in a secure store, not in code.
// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
this._firstName = 'Panda';
// good
this.firstName = 'Panda';
IBM App Connect – Development Best Practices
// bad
const name = "Capt. Janeway";
// good
const name = 'Capt. Janeway';
Strings that cause the line to go over 100 characters should not be written
across multiple lines using string concatenation.
Why? Broken strings are painful to work with and make code less searchable.
// bad
const errorMessage = 'This is a super long error that was thrown because \
of Batman. When you stop to think about how Batman had anything to do \
with this, you would get nowhere \
fast.';
// bad
const errorMessage = 'This is a super long error that was thrown because ' +
'of Batman. When you stop to think about how Batman had anything to do ' +
'with this, you would get nowhere fast.';
// good
const errorMessage = 'This is a super long error that was thrown because of
Batman. When you stop to think about how Batman had anything to do with this,
you would get nowhere fast.';
Use shortcuts for booleans, but explicit comparisons for strings and numbers.
IBM App Connect – Development Best Practices
// bad
if (isValid === true) {
// ...
}
// good
if (isValid) {
// ...
}
// bad
if (name) {
// ...
}
// good
if (name !== '') {
// ...
}
// bad
if (collection.length) {
// ...
}
// good
if (collection.length > 0) {
// ...
}
When mixing operators, enclose them in parentheses. The only exception is the
standard arithmetic operators: +, -, and ** since their precedence is broadly
understood. We recommend enclosing / and * in parentheses because their
precedence can be ambiguous when they are mixed. eslint: no-mixed-operators
// bad
const bar = a ** b - 5 % d;
// bad
// one may be confused into thinking (a || b) && c
if (a || b && c) {
return d;
}
// bad
const bar = a + b / c * d;
// good
const foo = (a && b < 0) || c > 0 || (d + 1 === 0);
IBM App Connect – Development Best Practices
// good
const bar = a ** b - (5 % d);
// good
if (a || (b && c)) {
return d;
}
// good
const bar = a + (b / c) * d;
3. Handle Errors and Exceptions Gracefully
Use Try/Catch for Exception Handling: Always wrap potentially error-prone code in try/catch blocks
to prevent unexpected crashes and provide clear error messages.
Return Meaningful Error Responses: Provide meaningful error messages and appropriate HTTP status
codes to help clients understand the nature of the issue.
try {
// Code that might throw an error
let result = someOperation();
} catch (error) {
context.setVariable('response.status.code', 500);
context.setVariable('response.body', JSON.stringify({ message: 'Internal
server error', error: error.message }));
throw error; // Re-throw the error to halt processing
}
4. Optimize Performance
Minimize Heavy Computation: Avoid performing heavy computations or synchronous operations that
could slow down the request/response cycle.
Asynchronous Operations: If you need to perform external API calls or database operations, make them
asynchronous using JavaScript's Promise API to avoid blocking.
Access Request and Response Variables: The context object in API Connect provides access to the
request and response data. Use it to read input parameters, headers, and bodies, and to set output
values.
o Read incoming request parameters: context.getVariable('request.query.param')
o Set response variables: context.setVariable('response.body', '{"message":
"success"}')
IBM App Connect – Development Best Practices
Leverage Built-in Context Variables: Use context variables such as request, response, identity,
and environment for access control, response manipulation, and logging.
Scope Variables: Always define variables within the local scope of the function to avoid unintended side
effects. This helps maintain modularity and reduces the risk of bugs.
function processData(input) {
let processedData = input.trim(); // Local variable
return processedData;
}
7. Follow Coding Standards and Documentation
Consistency: Follow a consistent naming convention for variables, functions, and files. This makes it
easier for others to understand and maintain the code.
Commenting: Write meaningful comments to explain complex logic or sections of code that may be
difficult to understand at first glance.
Documentation: Provide documentation for your code, particularly if the code will be used by other
developers. Document the inputs, outputs, and any side effects.
/**
* Transforms the input data to uppercase
* @param {string} input - The string to be transformed
* @returns {string} The transformed uppercase string
*/
function transformToUpperCase(input) {
return input.toUpperCase();
}
8. Avoid Synchronous Code
API Gateway scripts should be designed to be non-blocking and efficient. Avoid blocking calls that may
delay the response to the client. If you're calling external services (e.g., a database or another API), use
asynchronous patterns such as async/await or callbacks.
Use API Connect's Debugging Tools: Utilize API Connect’s debugging and logging features to
troubleshoot issues during script execution. Check the logs for information about request/response data
and errors.
Unit Testing: If possible, write unit tests for your scripts (e.g., using a JavaScript testing framework). This
is particularly useful for validating business logic and ensuring the script behaves as expected.
Sanitize Input: Always validate and sanitize input to avoid injection attacks (e.g., SQL injection, XSS).
Avoid Sensitive Information in Logs: Do not log sensitive information such as passwords, API keys, or
tokens in your scripts.
IBM App Connect – Development Best Practices
Secure Data Handling: When working with sensitive data, ensure it’s handled securely and consider
encrypting it before storing or transmitting.
Error Logging: Log errors with meaningful messages to make debugging easier. Use
context.setVariable() to set custom error messages in the response body if needed.
Request/Response Logging: Optionally log request/response data for auditing or debugging purposes,
but avoid logging sensitive information like passwords or tokens.
Ensure that your scripts are optimized to prevent abuse. For example, avoid excessive logging or
operations that might trigger rate limits on the gateway itself.
When writing XSLT scripts for API Connect or any other API Gateway:
Keep it simple and modular: Organize your code into manageable templates and functions.
Optimize for performance: Use efficient XPath expressions and reduce unnecessary
computation.
Handle errors gracefully: Always return meaningful errors when data is missing or invalid.
Test thoroughly: Validate your transformations with different input scenarios to ensure
robustness and correctness.
Identify Input and Output Data: Know what XML data you will be transforming (e.g., incoming request
data, response data) and what format the transformed data should be in (e.g., XML, JSON, or another
XML structure).
Know the Structure of XML: Familiarize yourself with the source XML structure (input) and the target
XML structure (output). Understanding both will help you design efficient XSLT transformations.
1b. You have additional XML files that you want to transform and include in
the document you're producing.
If you have a xml file that you want to include in your output, you need to
use the document() function to access this information and you need to have
templates in your stylesheet to transform it and include it in your output:
---- header.xml ----
<menu>
<item href="/">Home</item>
<item href="/movies/">Movies</item>
<item href="/shop/">Shop</item>
</menu>
----
---- data.xsl ----
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head><title>People</title></head>
<body>
<!-- applies templates to the information contained in
header.xml -->
<xsl:apply-templates select="document('header.xml')"
/>
<!-- applies templates to the input file -->
<xsl:apply-templates />
</body>
</html>
</xsl:template>
<!-- transforms the XML in header.xml into the table we
IBM App Connect – Development Best Practices
want -->
<xsl:template match="menu">
<table>
<tr>
<xsl:for-each select="item">
<td><a href="{@href}"><xsl:value-of select="."
/></a></tr>
</xsl:for-each>
</tr>
</table>
</xsl:template>
</xsl:stylesheet>
----
1c. You have additional XSLT files that you want to use to transform your input:
If you have an input XML document that includes some information that you
want as well as the data for the rest of the page, you want to import or include this
stylesheet so that the templates that are defined within it are processed as if they
were part of your general stylesheet. Whether you want to use xsl:import or
xsl:include depends on whether you want to override (some of) the
templates that are defined in the imported stylesheet: if you do, then use
xsl:import, otherwise, use xsl:include.
---- data.xml ----
<?xml version="1.0"?>
<doc>
<menu>
<item
href="/">Home</item>
<item
href="/movies/">Movies</item
---- header.xsl ----
IBM App Connect – Development Best Practices
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/X
SL/Transform">
<xsl:template match="menu">
---- data.xsl ----
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/X
SL/Transform">
<!-- includes the templates from the
>
<item
href="/shop/">Shop</item>
</menu>
<people>
<person age="50"
name="larry"/>
<person age="50"
name="larry"/>
</people>
</doc>
----
<table>
<tr>
<xsl:for-each select="item">
<td><a
href="{@href}"><xsl:value-of
select="." /></a></tr>
</xsl:for-each>
IBM App Connect – Development Best Practices
</tr>
</table>
</xsl:template>
</xsl:stylesheet>
----
header.xsl stylesheet -->
<xsl:include href="header.xsl" />
<xsl:template match="/">
<html>
<head><title>People</title></head>
<body>
<!-- applies templates to the menu
definition to create the header
- the templates come from
header.xsl -->
<xsl:apply-templates
select="doc/menu" />
<!-- applies templates to the data
to create the rest of the document
-->
<xsl:apply-templates
select="doc/people" />
</body>
</html>
</xsl:template>
...
</xsl:stylesheet>
You should also have a stylesheet that contains templates to transform this
header information into the output that you want:
2.Use XSL Design Patterns.
IBM App Connect – Development Best Practices
2a. Use the Kaysian method for set intersection, difference and symmetric
difference
The only set operation provided in XSLT is the Union -- and it can be specified
using the XPath and XSLT union operator "|".It is possible to express the
intersection of two node-sets in pure XPath. This technique was discovered by
Michael Kay and is known as the Kaysian method.
<xsl:variable name="intersection" select="$ns1[count(.|ns2)=count(ns2)]"/>
<xsl:variable name="set-difference" select="$ns1[count(.|ns2)!=count(ns2)]"/>
Example:
<?xml version="1.0"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:data="crane"
version="1.0">
<xsl:output method="text"/>
<data:data> <!--data source for testing purposes-->
item>1</item><item>2</item><item>3</item>
<item>4</item><item>5</item><item>6</item>
</data:data>
<xsl:template match="/"> <!--root rule-->
----Output----
Intersection: 2
Intersection: 3
Intersection: 4
Difference: 1
Difference: 5
Difference: 6
<xsl:variable name="ns1" select="//item[position()>1]"/>
<xsl:variable name="ns2" select="//item[position()<5]"/>
<xsl:for-each select="$ns1[count(.|$ns2)=count($ns2)]">
IBM App Connect – Development Best Practices
<TD> </TD>
</TR>
</TABLE>
In other words, I want to create a set of new nodes, the count of which is based
upon a *value* contained in the document. Below I present a small generalization
which is independent of the number of nodes in the XML source document and uses
the number of nodes in the stylesheet instead:
<xsl:template match="TAG">
<TABLE>
<TR ID="@ID">
<xsl:for-each select="(document('')//*)[position() <= Value]">
<TD> </TD>
</xsl:for-each>
</TR>
</TABLE>
</xsl:template>
This uses the capacity of the stylesheet for element nodes only. This capacity will
be considerably increased if we test for more types of nodes like this:
<xsl:for-each select="($st//node()| $st//@* | $st//namespace::*) [position() <= Value]">
where $st has been defined as document('') -- that is the root node of the
stylesheet.
2c. Oliver Becker's method of conditional selection
Xpath’s ablility to select a node-set based on complex conditions is very powerful.
However it lacks the capabilities for specifying a string as opposed to a nodeset.
Often you have to use a verbose multi-line xsl:choose construct just to specify that
"in case1 use string1, in case2 use string2, ..., in caseN use stringN"?
In all such cases we feel the need of a technique, which would allow us to specify in
a single XPath expression a string, which depends on condition(s).
Here's how to do it:
We want an XPath expression, which returns a string when some given condition is
IBM App Connect – Development Best Practices
true, and returns the empty string if this same condition is false.We can think of
"true" as "1" and of "false" as "0".But how to fit "1" to any string? Which string -
handling function can we use? substring() seems quite convenient. And here's the
trick: we can use substring() with only two arguments : substring(str,nOffset) will
return the (remainder of the) string str starting at offset nOffset.
In particular:
substring(str,1) returns the whole string
substring(str, nVeryLargeNumber) will return the empty string, if nVeryLargeNumber
is guaranteed to be greater than any possible string length.
So, the expression we might use would be:
concat(
substring(str1,exp(Condition)),
substring(str2,exp(not(Condition))
)
and we want exp(Condition) to be 1 if Condition is true, and exp(Condition) to be
Infinity if Condition is false.
We express exp(Condition) as:
1 div Condition because a boolean expression is first converted to a number (true ->
1, false -> 0), we get exactly:
exp(true) = 1
exp(false) = Infinity.
To summarise:
The XPath expression returning Str1 if a condition Cond is true and returning Str2 if
this same condition Cond is false -- this is:
concat(
substring(Str1,1 div Cond),
substring(Str2,1 div not(Cond))
)
This was first used by (Oliver?) Becker and is being quoted as the method of Becker.
Example:
IBM App Connect – Development Best Practices
I want to have a template, which generates the text: "My department" when it is
passed a parameter "IT" and to generate the text "Some other department" if the
value of the parameter is not "IT".
Of course, no xsl:if or xsl:when -s are allowed.
Here's the code, and when applied to any xml source document, it generates:
IT:
My department
Finance:
Some other department
Example stylesheet:
------------------
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:data="crane"
version="1.0">
<xsl:output method="text"/>
<xsl:template match="/">
IT:
<xsl:call-template name="whoIs">
<xsl:with-param name="department" select="'IT'" />
</xsl:call-template>
<br/>
Finance:
<xsl:call-template name="whoIs">
<xsl:with-param name="department" select="'Finance'" />
</xsl:call-template>
</xsl:template>
<xsl:template name="whoIs">
<xsl:param name="department" select="someDepartment" />
<br/>
IBM App Connect – Development Best Practices
<xsl:value-of
select="concat(substring('My department',
1 div ($department = 'IT')),
substring('Some other department',
1 div not(($department = 'IT'))
))" /><br/>
</xsl:template>
</xsl:stylesheet>
2d. Use the Muenchian method for grouping.
Grouping is often inefficiently implemented in XSL. A common situation in which
this issue arises is when you are getting XML output (ungrouped) from a database
which needs to be grouped by XSL. The database usually gives you results that
are structured according to the records in the database. For example let us
consider an employee table, which returns the following xml:
<data>
<employee no="1">
<name>Prathit Bondre</name>
-- Required Output --
Finance
Adheet Bondre
<department>IT</department>
</employee>
<employee no="2">
<name>Adheet Bondre</name>
<department>Finance</department>
</employee>
<employee no="3">
<name>Sinan Edil</name>
<department>IT</department>
</employee>
IBM App Connect – Development Best Practices
<employee no="4">
<name>Jeremy King</name>
<department>Finance</department>
</employee>
</data>
Jeremy King
IT
Prathit Bondre
Sinan Edil
The problem is how to turn this flat input into a number of lists grouped by
department to give the required output shown above.
There are two steps in getting to a solution:
! Identifying what the departments are.
! Getting all the employees that have the same department.
Identifying what the departments are involves identifying one employee with
each department within the XML, which may as well be the first one that appears
in . One way to find these is to get those employees that do not have a
department that is the same as a department of any previous employee.
employee[not(department = preceding-sibling::employee/department)]
Once these employees have been identified, it's easy to find out their
departments, and to gather together all the employees that have the same
deaprtment:
<xsl:apply-templates select="/data/employee[department = current()/department]" />
The trouble with this method is that it involves two XPaths that take a lot of
processing for big XML sources. Searching through all the preceding siblings with
the 'preceding-siblings' axis takes a long time if you're near the end of the
records. Similarly, getting all the contacts with a certain department involves
looking at every single employee each time. This makes it very inefficient.
The Muenchian Method is a method developed by Steve Muench for
performing these functions in a more efficient way using keys. Keys work by
IBM App Connect – Development Best Practices
assigning a key value to a node and giving you easy access to that node through
the key value. If there are lots of nodes that have the same key value, then all
those nodes are retrieved when you use that key value. Effectively this means that
if you want to group a set of nodes according to a particular property of the node,
then you can use keys to group them together.
In the example above, we want to group the employees according to their
department, so we create a key that assigns each employee a key value that is the
department given in the record. The nodes that we want to group should be
matched by the pattern in the 'match' attribute. The key value that we want to use
is the one that's given by the 'use' attribute:
<xsl:key name="employees-by-deparment" match="employee" use="department" />
Once this key is defined, if we know a department, we can quickly access all the
employees that have that department.
For example:
key(‘employees-by-department’, ‘IT’) will give all the records that have the
department of ‘IT’.
<xsl:apply-templates select="key(‘employees-by-department’, department)" />
The first thing that we needed to do, though, was identify what the departments
were, which involved identifying the first employee within the XML that had a
particular department. We can use keys again here. We know that a employee will
be part of list of nodes that is given when we use the key on its department: the
question is whether it will be the first in that list (which is arranged in document
order) or further down? We're only interested in the records that are first in the
list.
Finding out whether a employee is first in the list returned by the key involves
comparing the employee node with the node that is first in the list returned by the
key. This technique can also be used for getting distinct elements in the XML
file.There are a couple of generic methods of testing whether two nodes are
identical:
1. compare the unique identifiers generated for the two nodes (using generate-id()):
IBM App Connect – Development Best Practices
2. employee[generate-id() =
3. generate-id(key('employees-by-department', department)[1])]
4. see whether a node set made up of the two nodes has one or two nodes in it -
nodes can't be repeated in a node set, so if there's only one node in it, then they
must be the same node:
5. employee[count(. | key('employees-by-department', department)[1]) = 1]
Once you've identified the groups, you can sort them in whatever order you like.
Similarly, you can sort the nodes within the group however you want. Here is a
template, then, that creates the output that we specified from the XML we were
given from the database:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method = "html" encoding="Windows-1252" />
<xsl:key name = "employees-by-department" match ="employee" use = "department" />
<xsl:template match="data">
<html>
<head></head>
<body>
<xsl:for-each select = "employee[count(.|key('employees-bydepartment',department)[1])=1]">
<xsl:sort select="department" />
<b><u><xsl:value-of select="department" /></u></b><br/>
<xsl:for-each select="key('employees-bydepartment',department)">
<xsl:sort select="name"/>
<xsl:value-of select="name" /><br/>
</xsl:for-each>
</xsl:for-each>
</body>
</html>
</xsl:template></xsl:stylesheet>
The Muenchian Method is usually the best method to use for grouping nodes
IBM App Connect – Development Best Practices
together from the XML source to your output because it doesn't involve trawling
through large numbers of nodes, and it's therefore more efficient. It's especially
beneficial where you have a flat output from a database, for example, that you
need to structure into some kind of hierarchy. It can be applied in any situation
where you are grouping nodes according to a property of the node that is
retrievable through an XPath.
The downside is that the Muenchian Method will only work with a XSLT Processor
that supports keys. In addition, using keys can be quite memory intensive,
because all the nodes and their key values have to be kept in memory. Finally, it
can be quite complicated to use keys where the nodes that you want to group are
spread across different source documents.
2. Usage of XSL:IMPORT
Use <xsl:import> to import common, general-purpose rules into a stylesheet
designed to handle the specific transformation. If you can help it, don't
xsl:import any more xsl than you need.
3. Using static HTML
For any "static" html portions of the page (such as headers, footers, nav
bars), it's definitely more efficient to store the snippets as external xml files
& copy them to the output tree using xsl:copy-of and the document()
function, rather than using a named template and xsl:import.
4. Understand the difference between call and apply templates.
Call-template, unlike apply-templates, doesn't change the context node. Also,
a select attribute is only meaningful on apply-templates, not on call-template.
5. Code reuse and refactoring.
The problem with using one template with many conditionals is that the
code gets nasty and unreadable and unmaintainable very quickly. The
problems with many templates are that you often replicate code. The happy
medium is to use many templates and when you need to replicate code,
use calls to named templates, sometimes with parameters if there are
slight variations that need to be accounted for. Named templates provide
IBM App Connect – Development Best Practices
<xsl:attribute name="class">
<xsl:value-of select="$product/@type" /></xsl:value-of>
</xsl:attribute>
<xsl:value-of select="$product/name" />
</xsl:element>
… versus this:
<h3 class="{$product/name}">
<xsl:value-of select="$product/name" />
</h3>
17. Use template modes
Often, you will want to use a template match for totally different purposes. Rather than pass unnecessary
parameters or resort to different named templates, a mode attribute on the template can do the trick.
For example, suppose you are showing an order history for some e-commerce site. Suppose you want a
summary of orders at the top that anchor to the specific entries further down the page.
You can have more than one template have the same match, and use mode to differentiate or indicate
what they are used for.
Consider this example. First, here is a starting point in the XSLT. The idea is to reuse the Orders element,
one for summary purpose, the next for details.
<!-- starting point -->
<xsl:template match="/">
<h1>Order summary</h1>
<h2>Summary of orders</h2>
<p><xsl:apply-templates select="./Orders" mode="summary-info" /></p>
<h2>Table of orders</h2>
<xsl:apply-templates select="./Orders" mode="order-summary-details" />
</xsl:template>
Next, we match Orders with the summary-info mode:
<xsl:template match="Orders" mode="summary-info">
<xsl:value-of select="concat(count(./Order), ' orders, from ', ./Order[1]/@date, ' to ',
./Order[last()]/@date)" />
</xsl:template>
IBM App Connect – Development Best Practices
We can also match Orders for the order-summary-details mode. Note how the variable has also re-used
the other mode to get the summary for the table’s summary attribute.
<xsl:template match="Orders" mode="order-summary-details">
<xsl:variable name="summary">
<xsl:apply-templates select="." mode="summary-info" />
</xsl:variable>
<table summary="{normalize-space($summary)}">
<thead>
<tr>
<th scope="col">Order number</th>
<th scope="col">Amount</th>
<th scope="col">Status</th>
<tr>
</thead>
<tbody>
<xsl:apply-templates select="./Order" mode="order-summary-details" />
</tbody>
</table>
</xsl:template>
Note how the same mode name can be used for additional matches. This is a neat way to keep related
functionality together:
<xsl:template match="Order" mode="order-summary-details">
<tr>
<td><a href="/order/details/?id={./@id}"><xsl:value-of select="./@id" /></a></td>
<td><xsl:value-of select="./amount" /></td>
<td><xsl:value-of select="./status" /></td>
</tr>
</xsl:template>
In many real XSLTs I have written these modes can be re-used many times over. They help with
performance, while maintaining this elegance/reduction of code because the XSLT processor can use that
to narrow down which possible template matches to select from when looking for the one to execute.
IBM App Connect – Development Best Practices
The use of modes (and other features such as importing other XSLTs and overriding moded templates)
has allowed us to create multiple sub-sites in parallel (e.g. an ecommerce site that sells books,
entertainment products (CDs, DVDs, computer games, etc) that all run off the same XSLTs with some
minor customisation in each sub-site. Although the actual data is different, they fall into the same XML
structure — they are products after all! — thus making the XSLTs highly reusable. A future post will
describe arranging XSLTs in an almost object-oriented fashion).
18. Use in-built functions: concat()
The concat() function allows you to remove unnecessary and excessive uses of <xsl:value-of />
statements one after the other (and with the accompanying <xsl:text> </xsl:text> type of trick to get a
white space in there).
Code looks easier to read, in most cases, and typically performs better too.
Example:
Instead of this:
<xsl:value-of select="$string1" /><xsl:text> </xsl:text><xsl:value-of select="$string2" />
This is much cleaner to read:
<xsl:value-of select="concat($string1, ' ', $string2)" />
Or,
Instead of this:
<a>
<xsl:attribute name="href">
<xsl:value-of select="$domain" />/product/?<xsl:value-of select="$someProductId" />
</xsl:attribute>
<xsl:value-of select="$productDescription" />
</a>
This is much cleaner to read:
<a href="{concat($domain, '/product/?', $someProductId}">
<xsl:value-of select="$productDescription" />
</a>
Storing a string resulting from a concat into a variable is also efficient from a performance point of view
(storing node-sets does not cache the result, as in most DOM and XSLT implementations, node-sets are
live collections. More on that in a future post).
(Update: Azat notes in a comment below that the above href attribute can be even further simplified into
this: href="{$domain}/product/?{$someProductId}".)
IBM App Connect – Development Best Practices
Consider this:
<xsl:variable name="mystring" select="string(./title)" />
Why?
Code is cleaner to read.
But it is also more optimal; casting to a string instead of storing the node will result in the variable value
being cached in most XSLT processors, rather than being re-evaluated each time it is accessed. (XML
nodes are live collections according to W3C which means they may change. Hence references to nodes
require evaluation each time they are accessed.)
Use in-built functions: number()
For similar reasons as above to use string(), number() should be used too.
22. Use in-built functions: other
XPath functions such as starts-with(), string-length() are handy.
For example, it is common to see code to test for the presence of strings by testing if a variable equals
the empty string (”). But as most programmers should know, it is more efficient to test for the presence
of a string by testing its length. In XPath expressions you can use string-length() function for this.
23.DontUseDoubleSlashOperatorNearRoot: Avoid using the operator // near the root of a large tree.
24.DontUseDoubleSlashOperator: Avoid using the operator // in XPath expressions.
25.SettingValueOfVariableIncorrectly: Assign value to a variable using the 'select' syntax if assigning a
string value.
26.EmptyContentInInstructions: Don't use empty content for instructions like 'xsl:for-each' 'xsl:if'
'xsl:when' etc.
27.DontUseNodeSetExtension: Don't use node-set extension function if using XSLT 2.0.
28.RedundantNamespaceDeclarations: There are redundant namespace declarations in the xsl:stylesheet
element.
29.UnusedFunction: Stylesheet functions are unused.
30.UnusedNamedTemplate: Named templates in stylesheet are unused.
31.UnusedVariable: Variable is unused in the stylesheet.
32.UnusedFunctionTemplateParameter: Function or template parameter is unused in the
function/template body.
33.TooManySmallTemplates: Too many low granular templates in the stylesheet (10 or more).
34.MonolithicDesign: Using a single template/function in the stylesheet. You can modularize the code.
35.OutputMethodXml: Using the output method 'xml' when generating HTML code.
IBM App Connect – Development Best Practices
36.NotUsingSchemaTypes: The stylesheet is not using any of the built-in Schema types (xs:string etc.),
when working in XSLT 2.0 mode.
37.UsingNameOrLocalNameFunction: Using name() function when local-name() could be appropriate
(and vice-versa).
38.FunctionTemplateComplexity: The function or template's size/complexity is high. There is need for
refactoring the code.
39.NullOutputFromStylesheet: The stylesheet is not generating any useful output. Please relook at the
stylesheet logic.
40.UsingNamespaceAxis: Using the deprecated namespace axis, when working in XSLT 2.0 mode.
41.CanUseAbbreviatedAxisSpecifier: Using the lengthy axis specifiers like child::, attribute:: or
parent::node().
42.UsingDisableOutputEscaping: Have set the disable-output-escaping attribute to 'yes'. Please relook at
the stylesheet logic.
43.NotCreatingElementCorrectly: Creating an element node using the xsl:element instruction when could
have been possible directly.
44.AreYouConfusingVariableAndNode: You might be confusing a variable reference with a node
reference. (contributed by, Alain Benedetti)
45.IncorrectUseOfBooleanConstants: Incorrectly using the boolean constants as 'true' or 'false'.
(contributed by, Tony Lavinio)
46.ShortNames: Using a single character name for variable/function/template. Use meaningful names for
these features.
47.NameStartsWithNumeric: The variable/function/template name starts with a numeric character
48.Avoid the use of very long xpath queries (i.e. more than a screen width long). It makes the XSLT logic
difficult to read.
49.Set the indent attribute in the output declaration to off when outputting XML or HTML. Not only will
this reduce the size of the file you generate, but it will also decrease the processing time.
<xsl:output method="xml" indent="no"/>
50.Try to use template matching (push method) instead of named templates (pull method). Named
templates are fine to use for utility functions like the padding template listed above. However, template
matching will create cleaner and more elegant code.
51. Make use of built in XSLT functions whenever possible. A good example of this is when you are trying
to concatenate strings. One approach to accomplish this would be to utilize several xsl:value-of
instructions. However, it is much cleaner to use the xsl concat() function instead.
52. Where there's a need to iterate over a set of nodes, and for each node, lookup or access other nodes,
using XSLT Key can greatly optimize transformation. This approach avoids the inefficiency of repeated
IBM App Connect – Development Best Practices
traversal and avoids the O(n2) problem. Else, each node requires O(n) search through all other nodes,
leading to quadratic performance issue.
Define an XSL Key as <xsl:key name="name" match="match" use="use"/>
name: The name of the key.
match: The XPath expression that selects the nodes to be indexed.
use: The XPath expression that defines the value to index by (value to search on).
Use the key with key (name, search) function to quickly find nodes that match a particular search value.
53.When you are creating variables, <xsl:variable name="abcElem" select="abc"/> is usually faster than
<xsl:variable name="abcElem"><xsl:value-of-select="abc"/></xsl:variable>
54.xsl:for-each is fast because it does not require pattern matching
55.xsl:sort prevents incremental processing
56.Use of index predicates within match patterns can be costly in terms of performance
57.Decoding and encoding are costly in terms of performance
58.If the XSLT is cached, the performance is improved because the XSLT is not parsed every time it is
used;
3. Handle Missing or Optional Data Gracefully
Use <xsl:if> and <xsl:choose> for Conditional Logic: Handle cases where expected data might be
missing or empty by using conditional logic.
xml
Copy code
<xsl:choose>
<xsl:when test="order/discount">
<xsl:value-of select="order/discount" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="'0'" />
</xsl:otherwise>
</xsl:choose>
Provide Default Values: If certain fields or elements are missing, provide default values to ensure the
output is complete.
xml
Copy code
<xsl:value-of select="order/discount" />
<xsl:if test="not(order/discount)">0</xsl:if>
4. Efficient Use of Variables and Parameters
Declare Variables for Reused Values: When certain values or expressions are used multiple times,
declare them as variables to reduce redundant XPath calculations.
IBM App Connect – Development Best Practices
xml
Copy code
<xsl:variable name="orderDate" select="order/date" />
<xsl:value-of select="$orderDate" />
Use Parameters for External Data: Pass dynamic data from the API Gateway context (e.g., headers,
environment variables, or request data) as parameters to the XSLT, making your transformation more
flexible.
xml
Copy code
<xsl:param name="currency" select="'USD'" />
5. Handle Errors Gracefully
Provide Meaningful Error Messages: Ensure that if your XSLT encounters an error, it fails gracefully by
returning appropriate error messages or default values.
xml
Copy code
<xsl:choose>
<xsl:when test="order">
<xsl:value-of select="order/total"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="'Error: Order not found.'" />
</xsl:otherwise>
</xsl:choose>
Use <xsl:message> for Debugging: During development or troubleshooting, you can use the
<xsl:message> element to log custom messages for debugging.
xml
Copy code
<xsl:message select="'Processing order: '"/>
6. Optimize for Performance
Minimize Template Matching: Keep your XSLT code efficient by using specific match
patterns and avoiding broad ones like match="*" that can result in unnecessary processing of all
elements.
Avoid Redundant Loops: Minimize repeating the same transformation logic multiple times on
the same data, as this can negatively affect performance.
Use xsl:key and xsl:use-attribute-sets for Efficiency: If you're dealing with large XML
documents, xsl:key and xsl:use-attribute-sets can improve performance by indexing data
and reducing repetitive processing.
xml
Copy code
<xsl:key name="orderKey" match="order" use="order/id" />
IBM App Connect – Development Best Practices
Comment the Code: Write comments to explain the purpose of each template and logic block,
particularly if the transformation is complex.
Follow Consistent Naming Conventions: Use clear and consistent names for templates, variables, and
parameters to make the code easy to read and maintain.
Limit Nested Logic: Avoid deeply nested <xsl:choose>, <xsl:if>, or <xsl:for-each> statements,
as they can make the code harder to read and debug.
Use the Gateway Context: In API Connect, you can pass runtime data (like headers or request
parameters) to the XSLT using context variables. Ensure that your XSLT handles these external
data sources effectively.
XML to JSON Transformation: If you need to convert XML data into JSON, remember that
API Connect has built-in tools for handling this, but using XSLT for XML to JSON
transformations can be useful for custom mappings or complex scenarios.
xml
Copy code
<xsl:template match="/order">
<json>
<xsl:value-of select="concat('{"total": "', total, '"}')"/>
</json>
</xsl:template>
9. Test and Validate the Transformation
Test with Multiple Sample Inputs: Ensure your XSLT works across a variety of inputs and edge cases.
Use unit tests to check if the transformation behaves as expected.
Handle Invalid XML Gracefully: Ensure the XSLT handles invalid or unexpected XML input gracefully.
This could mean providing meaningful error messages or falling back to default values if certain data is
missing.
Use XSLT 1.0 or 2.0 as Appropriate: Most API Gateways (like IBM API Connect) support XSLT 1.0 by
default, but some also support XSLT 2.0 for more advanced features. Always check which version of
XSLT is supported by your API Gateway and use the appropriate syntax and functions.
Avoid Deprecated Features: Stay updated with XSLT standards and avoid using deprecated features or
non-portable extensions that might not be supported in all environments.
When implementing schema definitions for a REST API, it’s important to follow best practices and rules
to ensure data consistency, clarity, and maintainability. Below are key rules and guidelines you should
consider:
Use Explicit Types: Always specify the exact data types (e.g., string, integer, boolean, array,
object) to ensure clarity. This helps prevent ambiguity and promotes data integrity.
Avoid Ambiguity: Each field should have a clear, unambiguous definition. For instance, if you define a
field like created_at, make it clear whether it’s a string representing a date or a timestamp (e.g., ISO
8601 format).
Use Required Fields: Identify which fields are required in the request and response. For example, in user
registration, fields like username and email are typically required.
Minimize Additional Properties: To avoid issues with unintentional data being sent, define
additionalProperties: false if the schema should not accept extra fields not explicitly defined in
the schema.
"additionalProperties": false
3.4.2. Use Validations and Constraints
Type Constraints: Specify valid values for data types when applicable. For example, an integer field for
age might have a minimum or maximum value:
String Formats: Use standard string formats like email, uri, date-time, hostname, etc., for better
validation.
Length Constraints: For string fields, define length restrictions to ensure data integrity. For example:
Versioning Your Schemas: When changes are made to your API, version your schema to ensure
backward compatibility. This could involve adding new fields while keeping old ones intact, or even
introducing new versions of the API (e.g., /v1/users, /v2/users).
Deprecation Strategy: If you are removing or changing fields, clearly mark them as deprecated in your
schema and provide a transition path for consumers.
IBM App Connect – Development Best Practices
Schema References: When your API grows larger, avoid duplication by using references to shared
schema components. This can help to maintain DRY (Don't Repeat Yourself) principles.
"properties": {
"user": { "$ref": "#/definitions/user" }
}
Reuse Common Structures: Common structures, like addresses or timestamps, can be reused across
multiple parts of the schema by referencing them.
Arrays: When defining arrays, make sure you clearly specify the items in the array and their types. For
example, a list of tags for a blog post might look like:
"tags": {
"type": "array",
"items": { "type": "string" }
}
Nested Objects: Ensure that nested objects are well-defined and properly referenced in your schema.
"address": {
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string" },
"zipcode": { "type": "string" }
}
}
3.4.6. Clear and Consistent Naming Conventions
Use Meaningful Field Names: Choose names that accurately describe the data. For example, use
firstName and lastName instead of ambiguous terms like name1 and name2.
Consistent Naming: Stick to consistent naming conventions across your schema. You might choose
camelCase, snake_case, or PascalCase, but be consistent throughout the schema to avoid confusion.
Avoid Abbreviations: Unless they are well-known and widely accepted, avoid abbreviations that could
confuse developers.
It's critical to understand the purpose and best use case for each policy to apply them effectively in the
API flow.
Security: Always apply security policies like OAuth, API key validation, or JWT validation to secure your
API endpoints. If your API is public, use OAuth 2.0 or OpenID Connect for secure authentication.
Traffic Management: Use rate limiting and quota policies to prevent abuse, especially for public APIs.
Define quotas for different tiers (e.g., free, paid) to manage how much traffic each tier can consume.
Transformation: Use transformation policies for tasks like payload conversion (XML to JSON, JSON to
XML), header manipulation, or modifying request/response content. This is helpful for integrating with
different back-end systems with varying data formats.
Routing: Apply routing policies to forward requests to different backends or microservices based on
conditions such as the HTTP method, headers, or paths.
Fault Handling: Ensure that policies like Fault, Retry, and Timeout are in place to handle and
mitigate any errors or issues that arise during API invocation.
OAuth 2.0 / OpenID Connect: Always use OAuth 2.0 or OpenID Connect to secure your APIs when
needed. Implement authorization policies to control access based on roles and scopes.
API Keys: For simpler use cases, API key validation is a good first step in securing your APIs.
IP Whitelisting: In scenarios where only specific IP addresses are allowed to access your API, use IP
filtering policies.
Apply rate-limiting policies to restrict the number of API calls a user or client can make within a given
time period.
Use throttling policies to protect your backend services from overload by enforcing limits on incoming
requests.
Use Load Balancing: Apply policies that allow your API to route traffic intelligently based on the
availability or performance of backend systems.
Implement Retry policies to handle transient issues and ensure the API has automatic recovery from
failures.
IBM App Connect – Development Best Practices
Use Analytics and Logging policies to monitor API performance and get insights into usage patterns,
error rates, and system health.
Audit logging can help track and monitor sensitive actions, such as changes to configurations or data
access.
Custom Analytics: Configure policies to report custom data to external analytics systems.
Use Fault Handling policies to ensure that errors do not expose sensitive system information. Instead,
return user-friendly error messages or fallback responses.
Use Circuit Breaker and Timeout policies to prevent cascading failures when backend systems are
unavailable.
Apply common policies at the API Gateway level to standardize API behavior across multiple APIs. This
simplifies maintenance and provides consistent security, logging, and traffic management.
As your APIs evolve, implement versioning policies to ensure backward compatibility. Use the routing
policies to ensure that different versions of your API can coexist without breaking clients.
Utilize transformation policies to handle version-specific differences in request/response formats.
Always test policies in a controlled environment before deploying them in production. Ensure that traffic
management, security, and error handling policies work as expected under different conditions.
Use Mock APIs to simulate backend services and test API behaviors without affecting live systems.
9. Document Policies
Clearly document your policies, especially custom ones. Documentation should include:
o What each policy does
o Where it's applied (API level or product level)
o Any specific configurations or parameters
o How to troubleshoot or diagnose issues related to policies
As your API evolves, periodically review your policies to ensure they align with your current security
requirements, business needs, and performance goals.
Keep policies updated in response to any new security vulnerabilities or API lifecycle changes.
IBM App Connect – Development Best Practices
Avoid excessive use of transformation or routing policies that could degrade API performance. For
example, complex data transformation might introduce latency.
Make sure caching policies are applied effectively, reducing unnecessary backend calls and improving
response times.
Apply policies conditionally based on headers, parameters, or client characteristics. For instance,
applying stricter security or rate limits to external clients compared to internal ones can improve both
security and performance.
Log API activities and errors for debugging and auditing purposes. Monitor API
performance, usage patterns, and error rates to identify issues and optimize performance. For
such logging and monitoring purposes we use Audit and error logs. --can be added as
recommended in logging section or designing part. Use monitoring tools to track the health
and performance of integration solutions, enabling proactive issue resolution.
Error Handling
Each interface shall have a mechanism to handle errors/exceptions. These errors/exceptions
refer to both Systems generated ones as well as User Generated ones.
Incorporate robust error handling within work flows to manage exceptions gracefully and
provide meaningful error messages.
Connect these terminals to handle exceptions appropriately, ensuring that errors are logged
and managed without disrupting the entire flow.
It is recommended to have a common Error Handling Scripts/policy to handle all
errors/exceptions that arise during execution of an interface
This Script/policy shall be extensively re-used by all interfaces of the project
3.8 Documentation
Create comprehensive and up-to-date documentation for your API. Document endpoints,
request and response formats, authentication methods, error codes, and usage examples.
Tools like Swagger or OpenAPI Specification can help automate documentation generation.
Maintain all documents in a drive/shared storage like Scope, Architecture, Inventory,
Understanding, Low level design, High level design, Release documents, etc.
3.9 Best Practices when Integrating API Connect with APP CONNECT
1. Cryptography
o Perform encryption and decryption at the API Connect level to ensure illegal or malicious
traffic is blocked before reaching the APP CONNECT.
o Use TLS (Transport Layer Security) for all communications to and from the API
Connect.
o Ensure API Connect supports modern cryptographic algorithms and configurations (e.g.,
TLS 1.3, strong cipher suites).
2. Schema Validation
IBM App Connect – Development Best Practices
o Implement schema validation at the API Connect to reject malformed requests before
they propagate to the APP CONNECT.
o Utilize API Connect’s built-in support for OpenAPI/Swagger specifications for defining
and validating request/response payloads.
o Avoid duplicating schema validation in both API Connect and APP CONNECT to reduce
redundancy and overhead.
3. Authentication and Authorization
o Centralize authentication (e.g., OAuth 2.0, JWT) at the API Connect to enforce security
policies before forwarding requests to the APP CONNECT.
o Use API Connect’s role-based access control (RBAC) to define access policies for
different APIs and consumer groups.
4. Rate Limiting and Throttling
o Configure rate limiting and throttling policies in the API Connect to prevent excessive
traffic from overwhelming the APP CONNECT.
o Apply usage quotas and burst limits at the Gateway level to ensure fair use and protect
backend systems.
5. Error Handling
o Standardize error responses at the API Connect for consistency and better user
experience.
o Configure the Gateway to handle generic errors (e.g., 400, 401, 403, 500) and provide
meaningful error messages to clients.
6. Database Communication
o Offload database interactions to the APP CONNECT, which typically offers better tools
for integrating with various database systems.
o Use APP CONNECT’s support for connection pooling, transaction management, and
database-specific adapters for optimized performance.
7. Logging and Monitoring
o Enable detailed request and response logging at the API Connect level for audit and
troubleshooting purposes.
o Leverage the APP CONNECT for deeper logging of backend processing and integrations.
o Use centralized monitoring tools to aggregate logs from both the API Connect and APP
CONNECT for end-to-end visibility.
8. Backend Encryption
o Configure routing rules in the API Connect to direct traffic to the appropriate APP
CONNECT services based on URL paths, headers, or query parameters.
o Use load balancing at the Gateway level to distribute traffic across multiple APP
CONNECT instances.
o If orchestration is involved and it involves multiple providers implement routing at App
Connect.
11. Security Policies
o Enforce API-specific security policies at the API Connect, such as IP
whitelisting/blacklisting and CORS (Cross-Origin Resource Sharing).
o Implement additional backend-specific security measures within the APP CONNECT for
internal services.
12. Versioning
o Manage API versions in the API Connect to ensure backward compatibility for clients.
o Keep the APP CONNECT backend services decoupled from API versioning logic.
13. Fault Tolerance and Retry
o Handle transient failures at the API Connect with retry logic and appropriate backoff
strategies.
o Use the APP CONNECT’s capabilities for long-running retries, compensations, and error
recovery for downstream systems.
14. Caching
o Implement caching at the API Connect for frequently accessed resources to reduce
latency and backend load.
o Use cache invalidation mechanisms to ensure data consistency for dynamic content.
15. Content-Based Routing
o Use content-based routing at the API Connect to direct requests to the appropriate APP
CONNECT services based on payload content.
o Define routing rules that can evaluate request headers, query parameters, or body content.
16. Service Discovery
o Leverage App Connect’s integration with service discovery tools (e.g., Consul, Eureka)
to dynamically resolve backend service endpoints.
o Use the APP CONNECT’s service orchestration capabilities to integrate with multiple
microservices seamlessly.
17. DevOps and Automation
o Automate the deployment and configuration of the API Connect and APP CONNECT
using Infrastructure as Code (IaC) tools (e.g., Terraform, Ansible).
o Implement CI/CD pipelines to streamline updates and ensure consistency across
environments.
18. Scalability and High Availability
o Ensure the API Connect is deployed in a highly available setup (e.g., multi-region, multi-
AZ deployment).
o Use horizontal scaling for both the API Connect and APP CONNECT to handle
increasing traffic demands.
19. Compliance and Auditing
o Ensure the API Connect and APP CONNECT comply with industry standards (e.g.,
GDPR, HIPAA, PCI-DSS).
IBM App Connect – Development Best Practices
o Enable detailed auditing for all API transactions, including timestamps, requestors, and
responses.
o Leverage Pronteff’s custome logging mechanism for detailed auditing in both API
connect and App Connect
oProvide proper documentation for APIs through the Gateway for better developer
adoption.
29. Event-Driven Architecture
o Leverage APP CONNECT’s support for event-driven patterns to integrate with real-time
streaming platforms like Apache Kafka or AWS EventBridge.
o Use the API Connect as a wrapper for such requirements.
30. Latency Optimization
o Minimize latency by ensuring API Connect and APP CONNECT configurations are
optimized for low response times.
o Use lightweight payloads and efficient processing mechanisms at both layers.
31. Network Security
o Configure firewalls, WAF (Web Application Firewall), and private endpoints to secure
communication between API Connect and APP CONNECT.
o Use network segmentation to isolate sensitive traffic.
32. Role-Based Access Control (RBAC)
o Implement granular RBAC policies at both the API Connect and APP CONNECT levels
to restrict access based on roles and responsibilities.
o Regularly review and update access control policies to prevent unauthorized access.
33. Load Testing
o Conduct periodic load testing to ensure API Connect and APP CONNECT can handle
peak traffic volumes.
o Use tools like JMeter or Gatling for simulating real-world traffic scenarios.
34. Data Masking
o Mask sensitive data (e.g., PII, credit card information) in logs at both the API Connect
and APP CONNECT levels to enhance security.
o Implement policies to prevent accidental data leakage.
35. Redundancy Strategies
o Deploy redundant instances of API Connect and APP CONNECT to avoid single points
of failure.
o Use traffic failover mechanisms to switch to backup instances during outages.
36. Middleware Decoupling
o Ensure that API Connect and APP CONNECT configurations are decoupled to allow
independent updates and scaling.
o Avoid hard dependencies between the Gateway and ESB to enhance system flexibility.
37. Session Management
oHandle session management at the API Connect level for stateless backends.
oUse APP CONNECT for session persistence when dealing with long-running
transactions.
38. Asynchronous API Handling
oUse global traffic management capabilities at the API Gateway for multi-region
deployments.
o Route requests to the nearest APP CONNECT instance to reduce latency for global users.
40. Data Residency Compliance
o Ensure API Connect and APP CONNECT are configured to meet regional data residency
and sovereignty regulations.
o Route and process data based on geographic boundaries to comply with laws.
41. Policy Enforcement Points (PEP)
Use API Connect as the primary policy enforcement point for security, rate limits, and
o
access controls.
o Configure APP CONNECT to support secondary policy enforcement for internal
compliance needs.
42. Dynamic Scaling
oImplement dynamic scaling for both API Connect and APP CONNECT based on traffic
patterns.
o Use auto-scaling groups or serverless deployment models for handling traffic spikes.
43. Message Replay Prevention
oUse API Connect to detect and block replay attacks by enforcing unique request IDs or
timestamps.
o Implement APP CONNECT mechanisms for tracking and rejecting duplicate messages in
workflows.
44. Dependency Management
o Ensure API Connect and APP CONNECT dependencies are up-to-date with security
patches and compatibility updates.
o Regularly audit third-party libraries and plugins used in both components.
45. Integration Patterns
oLeverage Enterprise Integration Patterns (EIPs) like Routing Slip, Content Enricher, and
Aggregator at the APP CONNECT for complex workflows.
o Keep API Connect integrations simple and focused on connectivity and security.
46. Sandbox Environment
oCreate a sandbox environment at the API Connect for testing and onboarding new API
consumers.
o Use APP CONNECT to simulate backend responses in the sandbox for better developer
experience.
47. Event Logging and Correlation
IBM App Connect – Development Best Practices
o Implement request/response correlation IDs at the API Connect to trace calls through the
APP CONNECT and backend systems.
o Use APP CONNECT’s event logging capabilities for deeper insights into transactional
workflows.
48. Circuit Breaker Patterns
Use circuit breaker patterns at the API Connect to handle service failures gracefully and
o
avoid cascading failures.
o Configure the APP CONNECT to provide fallback mechanisms for failed integrations.
49. API Monetization
oEnable API monetization capabilities in the API Connect for subscription-based or pay-
per-use APIs..
50. Latency SLA Enforcement
Define latency SLAs at the API Connect level to ensure high responsiveness for
o
consumers.
o Use the APP CONNECT to optimize backend processing and meet SLA requirements.
51. Debugging and Root Cause Analysis
oEquip the API Connect with tools to capture detailed request traces and performance
metrics.
o Use APP CONNECT logs and diagnostic tools for root cause analysis of complex
integration issues.
52. API Productization
Group APIs into products in the API Connect to enhance discoverability and usability.
o
Ensure the APP CONNECT can handle requests from various API products seamlessly.
o
53. Green/Blue Deployment
o Use the API Connect for traffic splitting during green/blue deployments to test new APP
CONNECT versions.
o Configure routing rules to gradually shift traffic to the new version for smooth rollouts.
54. Service Virtualization
oLeverage the API Connect for virtualizing APIs during development or testing.
oUse the APP CONNECT to simulate backend responses for virtualized services.
55. Zero Trust Architecture
oImplement zero-trust security principles at the API Connect, ensuring every request is
authenticated and verified.
o Use the APP CONNECT for policy enforcement and deeper security checks for internal
services.
56. API Connects in Multi-Cloud Environments
o Configure API Connects to operate seamlessly across multi-cloud setups, ensuring
consistent policies and routing.
IBM App Connect – Development Best Practices
oUse the APP CONNECT to unify backend integrations across multiple cloud providers.
57. Custom Authentication Mechanisms
o Implement custom authentication plugins at the API Connect for unique business
requirements.
o Use the APP CONNECT to support custom token validation or authentication for
backend workflows.
58. Token Revocation Support
o Ensure the API Connect integrates with token revocation lists to prevent the use of
invalidated access tokens.
59. Granular Quotas by Consumer Type
o Implement quotas and rate limits at the API Connect based on consumer type (e.g.,
internal vs. external clients).
60. On-Demand Scaling Strategies
o Design the API Connect to automatically scale during high-traffic events, such as flash
sales or promotions.
o Use APP CONNECT’s event-driven architecture to handle increased backend processing
dynamically.
61. Legacy System Support
o Use the APP CONNECT to abstract and modernize legacy systems while exposing APIs
through the API Connect.
o Transform and map legacy data formats (e.g., XML, COBOL) to modern standards like
JSON.
62. Time-to-Live (TTL) for Requests
o Use TTL settings at the API Connect to drop stale or delayed requests before reaching the
APP CONNECT.
o Configure APP CONNECT to honor TTLs in multi-step processing workflows.
63. API Aggregation at Gateway Level
o Implement API aggregation at the API Connect to combine multiple API responses into a
single payload.
o Use the APP CONNECT for advanced aggregation logic when needed.
64. Advanced Load Balancing Techniques
o Configure the API Connect for session-aware or sticky load balancing for specific APIs.
o Use the APP CONNECT to distribute backend traffic evenly based on dynamic criteria.
65. Dynamic Endpoint Updates
o Enable API Connect to dynamically update backend endpoints without downtime using
DNS-based routing. We can do this by keeping hostname instead of IP and setting the
URL at catalog scope.
o Use APP CONNECT to register and manage backend service endpoints dynamically.This
can be done using configuration files or Database.
66. Graceful API Deprecation
o Implement deprecation warnings at the API Connect for clients using outdated APIs.
o Use the APP CONNECT to support old APIs temporarily while migrating backend
systems.
67. Dynamic Request/Response Modifications
o Modify headers or payloads dynamically at the API Connect for personalization or
business logic.
IBM App Connect – Development Best Practices
Summary
By adhering to these best practices, you can ensure a secure, scalable, and efficient integration between
your API Connect and APP CONNECT. This separation of concerns maximizes performance and
maintainability while leveraging the strengths of both components.