0% found this document useful (0 votes)
12 views

IBM API Connect - Development Best Practices

Uploaded by

kngb145
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

IBM API Connect - Development Best Practices

Uploaded by

kngb145
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 56

IBM App Connect – Development Best Practices

Development Best Practices - IBM API


Connect

Revision control:

Date Version Author Changes/Comments


09/01/2025 1 Nagababu and Vasu
IBM App Connect – Development Best Practices

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

9. Test and Validate the Transformation....................................................................................................


10. Adhere to XSLT Standards...................................................................................................................
3.4 Schema definitions for a REST API:......................................................................................................
3.4.1. Clearly Define Data Structure...............................................................................................................
3.4.2. Use Validations and Constraints...........................................................................................................
3.4.3 Versioning and Backward Compatibility................................................................................................
3.4.4. Use Reusable Components...................................................................................................................
3.4.5. Support for Arrays and Nested Objects................................................................................................
3.4.6. Clear and Consistent Naming Conventions...........................................................................................
3.5 Understand Policy Types and Their Use Cases.......................................................................................
Apply Policies Based on Specific API Use Cases..............................................................................................
1. Secure Your APIs with Authentication and Authorization Policies..........................................................
2. Implement Rate Limiting and Throttling.................................................................................................
3. Ensure High Availability and Scalability..................................................................................................
4. Monitor API Performance and Usage.....................................................................................................
5. Manage Error Handling Gracefully..........................................................................................................
6. Use the API Gateway for Centralized Management...............................................................................
7. Versioning and Backward Compatibility.................................................................................................
8. Test Policies in Development & Staging Environments...........................................................................
9. Document Policies..................................................................................................................................
10. Update and Review Policies Regularly................................................................................................
11. Optimize for Performance..................................................................................................................
12. Use Contextual Policies.......................................................................................................................
3.6 Logging and Monitoring...............................................................................................................................
3.7 Testing Practices...........................................................................................................................................
3.8 Documentation.............................................................................................................................................
3.9 Best Practices when Integrating API Connect with APP CONNECT...........................................................
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!

3.1 Designing APIs/Services:

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.

3.2 Gateway Script Coding Practices:

When writing a Code Gateway Script in API Connect:

 Keep the code clean, modular, and reusable.


 Ensure performance, security, and error handling are top priorities.
 Leverage the power of the context object to interact with the request/response flow effectively.
 Test and debug the script thoroughly to ensure that it works as expected under all conditions.

1. Understand the Context and Requirements

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

2. Best Coding Practices-

 Each module or function should perform a single responsibility.

 better use "buffer" datatype (works for up to 1GB size) than "buffers" datatype (has no size limit,
list of buffer objects internally)

 Prefer Const and Let:


o Use const for constants and let for mutable variables; avoid var.

 Use Meaningful Names:


o Name variables, functions, and classes clearly and descriptively.
o Example: Use getUserById() instead of getData().

 Avoid Nested Callbacks:


o Use Promises or async/await instead of deeply nested callbacks (callback hell).

 Use Comments Sparingly:


o Comment why a piece of code exists, not what it does if it's self-explanatory.

 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.`);

 Avoid Requiring Modules Dynamically:


o Use require or import at the top of the file.

 Use Dependency Injection:


o Pass dependencies as arguments instead of hardcoding them.

 Remove Dead Code:


o Regularly clean unused imports and functions.

 Avoid console.log in Production:


o Use structured logging libraries like winston or pino.

 Don’t Use Global Variables:


IBM App Connect – Development Best Practices

o Minimize the use of globals; prefer local variables or configurations.

 Promises and async/await:

o Use Promises or async/await for asynchronous operations.

 Use shorthand syntax for properties and methods in objects.

javascript
Copy code
const age = 25;
const person = { name: 'John', age, greet() { return 'Hi!'; } };

 Avoid importing unused modules.


 Wrap require in try-catch for dynamic imports.

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.

 Always use === instead of == to avoid type coercion issues.


 Avoid using eval() as it is a security risk and slow.

 Use Number.isNaN() instead of isNaN() to check for NaN.

 Avoid exposing sensitive data (e.g., API keys).


 Choose and stick to a naming convention, such as:

 CamelCase: For variables and functions (getUserData).


 PascalCase: For classes and constructors (UserController).
 SCREAMING_SNAKE_CASE: For constants (MAX_TIMEOUT).

 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

 Limit the number of parameters (ideally 2–3).

 Refactor deeply nested logic into smaller functions

 Use action verbs to describe what the function does:

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;

 Replace long if-else chains with switch when applicable:

 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.

 Minimize Runtime Changes: Avoid modifying runtime variables or configurations dynamically


without a clear rollback mechanism.
 Performance Monitoring: Use DataPower’s monitoring tools to track script performance in
production.

 Environment Configuration: Keep environment-specific configurations (e.g., URLs, credentials)


separate from code.

 Avoid Hardcoding Secrets: Store secrets and sensitive configurations in a secure store, not in code.

Do not use trailing or leading underscores.

// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
this._firstName = 'Panda';

// good
this.firstName = 'Panda';
IBM App Connect – Development Best Practices

 Use single quotes '' for strings. eslint: quotes

// bad
const name = "Capt. Janeway";

// bad - template literals should contain interpolation or newlines


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 === and !== over == and !=. eslint: eqeqeq

 Conditional statements such as the if statement evaluate their expression


using coercion with the ToBoolean abstract method and always follow these
simple rules:
o Objects evaluate to true
o Undefined evaluates to false
o Null evaluates to false
o Booleans evaluate to the value of the boolean
o Numbers evaluate to false if +0, -0, or NaN, otherwise true
o Strings evaluate to false if an empty string '', otherwise true

if ([0] && []) {


// true
// an array (even an empty one) is an object, objects will evaluate to
true
}

 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

Why? This improves readability and clarifies the developer’s intention.


// bad
const foo = a && b < 0 || c > 0 || d + 1 === 0;

// 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.

// Using promises for async operations


async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
context.setVariable('response.body', JSON.stringify(data));
} catch (error) {
console.error('Error fetching data:', error);
}
}
5. Use the API Connect Context Object Effectively

 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.

6. Avoid Global Variables

 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.

9. Testing and Debugging

 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.

10. Security Considerations

 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.

11. Monitor and Log Important Information

 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.

12. Adhere to API Connect Rate Limits and Quotas

 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.

3.3 XSLT Coding Practices:

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.

1. Understand the Use Case and Requirements

 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.

2. Best Coding Practices


1. Include external files the right way:
There are three use cases for including external files in your xsl:
1a. You have additional HTML files that you want to include in the documentyou're producing.
If you have an HTML file that you want to include in your output, in exactly the form
you want to include it in your output, probably the simplest way to get this into your
output is to simply include it as an external parsed entity in the stylesheet. This
involves declaring and referencing the entity within your stylesheet:
IBM App Connect – Development Best Practices

---- header.html ----


<table>
<tr>
<td><a href="/">Home</a></td>
<td><a href="/movies/">Movies</a></td>
<td><a href="/shop/">Shop</a></td>
</tr>
</table>
----
---- data.xsl ----
<?xml version="1.0"?>
<!DOCTYPE xsl:stylesheet [
<!-- declares header.html as an external parsed entity
-->
<!ENTITY header SYSTEM "header.html">
]>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head><title>People</title></head>
<body>
<!-- includes header.html directly -->
&header;
<xsl:apply-templates />
</body>
</html>
</xsl:template>
</xsl:stylesheet>
----
IBM App Connect – Development Best Practices

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()&lt;5]"/>
<xsl:for-each select="$ns1[count(.|$ns2)=count($ns2)]">
IBM App Connect – Development Best Practices

Intersection: <xsl:value-of select="."/>


</xsl:for-each>
<xsl:for-each select="( $ns1[count(.|$ns2)!=count($ns2)]
| $ns2[count(.|$ns1)!=count($ns1)] )">
Difference: <xsl:value-of select="."/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
2b. Use Wendel Piez method of non-recursive looping
The Wendel Piez method demonstrates a way to avoid XSLT recursion when
implementing loops.
Example:
--Source--
<Tag ID="1">
<Value>4</Value>
</Tag> <Tag ID="2">
<Value>2</Value>
</Tag>
Required Output
<TABLE>
<TR ID="1">
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
</TR>
</TABLE>
<TABLE>
<TR ID="2">
<TD> </TD>
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() &lt;= 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() &lt;= 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

the equivalent of subroutines or private methods.


Example:
Say you want to process 'item' elements, and you want to have one
template for when item’s 'type' attribute is 'Book', one template for when
it's 'CD', and one template for all other 'items:
<xsl:template match="item[@type='Book']"/>
<xsl:template match=" item [@type='CD']"/>
<xsl:template match="item"/>
And these are in addition to the built-in template that matches "*" (any
element). The templates with the greater degree of specificity will have
higher priority for matching.
6. Automate XSL documentation.
Programmers usually hate documentation and hence usually don’t do justice to
writing it. Javadocs in java provided great relief to the programmer community
by providing a way to auto generate the documentation. There is a similar tool
that was written for XSL called xsldoc. It is available for free download at:
www.xsldoc.org
This will provide an automated, standard and reliable way to generate
documentation about your XSL files and since it is command line based it could
also be made a part of your build process.
7. Don’t reinvent the wheel by using the XSLT library.
XSLT library is an open source repository of XSL templates that have been written as
tested. The library has a lot of templates for string manipulation, date handling, node
processing , etc that can be effectively used in your xsl files. So save yourself some time
by resing this library. The library is available at http://xsltsl.sourceforge.net
8. Decrease the size of your HTML documents
Decrease the size of your HTML documents by using the indent=”no” in the
<xsl:output> tag. The attribute tells the XSLT processor not to indent the
HTML document , which typically results in smaller HTML files that download
faster.
IBM App Connect – Development Best Practices

Eg. <xsl:output method=”html” indent=”no” />


9. Use Descriptive Names: Use meaningful names for templates, variables, and parameters.
10. Comment Your Code: Add comments to explain complex logic or specific templates to improve
readability.
11. Indent and Format Code: Properly indent your XSLT for readability and maintain a consistent style
throughout.
12. Avoid Redundancy: Reuse templates and avoid duplicating logic
13. Avoid XSLT Named Templates; Use Template Match
The first coding practice that leads to code bloat and hard to read XSLT is using named templates
everywhere. Named templates give a procedural feel to coding. (You define templates with names, pass
parameters as needed and do some stuff). This may feel familiar to most coders, but it really misses the
elegance and flexibility of XSLT.
So, instead of this:
<xsl:template name="CreateLink">
<xsl:param name="product" />
<-- create the link here based on the product parameter -->
</xsl:template>
<-- The above would be called from elsewhere using this: -->
<xsl:call-template name="CreateLink"<>
<xsl:with-param name="product" select="./product" />
</xsl:call-template>
Far neater would be this:
<xsl:template match="product">
<-- create the link here based on the product parameter -->
</xsl:template>
<-- The above would be called from elsewhere using this: -->
<xsl:apply-templates select="./product" />
The above example doesn’t look like much on its own. When you have a real stylesheet with lots of
template matches, (and modes, which we look at later) this gets a lot easier to read, and cuts a LOT of
code, especially when calling/applying these templates.
(Of course, each tip has exceptions; named templates can be useful for utility functions. Sometimes XSLT
extension objects can be useful for that too, depending on your parser and runtime requirements. A
subsequent post on XSLT performance tips will cover that.)
IBM App Connect – Development Best Practices

14. Avoid xsl:for-each; Use Template Match


xsl:for-each is another programming construct that would appeal to many coders. But again, it is rarely
needed. Let the XSLT processor do the looping for you (it has potential to be optimised further, too).
There are some instances or XSLT parsers that may perform a bit quicker using xsl:for-each because for-
each avoids the XSLT processor having to determine which of possibly many matched templates is the
suitable one to execute. However, matched templates that use modes can overcome those issues to
most extents, and lend to highly elegant, reusable XSLT.
15. You don’t have to use xsl:element or xsl:attribute
You can use xsl:element and xsl:attribute, but it leads to very bloated code.
Here are a few examples of what you can do instead. In each example we will just assume we are
working with some XML that represents some kind of product (it is not important what this structure is
for this discussion).
Use the element name itself rather than xsl:element
Instead of
<xsl:element name="p">
<xsl:value-of select="$product/name" />
</xsl:element>
This is a lot cleaner to read:
<p>
<xsl:value-of select="$product/name" />
</p>
Sometimes I prefer this:
<p><xsl:value-of select="$product/name" /></p>
16. Use the { } shorthand for writing values inside of attributes
Using xsl:value-of for many attributes can get verbose very quickly. There is more code to read. So the
code just looks uglier and more bloated. For attributes only then, with most XSLT parsers, you can use
the shorthand { as a replacement for <xsl:value-of select=” and } as a replacement for ” />.
In between { and } you just put in your normal select expression.
So, instead of
<h3>
<xsl:attribute name="class">
<xsl:value-of select="$product/@type" /></xsl:value-of>
</xsl:attribute>
IBM App Connect – Development Best Practices

<xsl:value-of select="$product/name" />


</h3>
This is a lot cleaner to read:
<h3 class="{$product/name}">
<xsl:value-of select="$product/name" />
</h3>
Or, instead of
<xsl:element name="img">
<xsl:attribute name="src" select="$product/image/@src" />
<xsl:attribute name="width" select="$product/image/@width" />
<xsl:attribute name="height" select="$product/image/@height" />
<xsl:attribute name="alt" select="$product/image" />
<xsl:attribute name="class" select="$product/@type" />
</xsl:element>
This is a lot cleaner to read:
<img
src="{$product/image/@src}"
width="{$product/image/@width}"
height="{$product/image/@height}"
alt="{$product/image}"
class="{$product/@type}"
/>
The above is only put onto multiple lines for this web page. In a proper editor sometimes a one-liner is
even easier to read:
<img src="{$product/image/@src}" width="{$product/image/@width}"
height="{$product/image/@height}" alt="{$product/image}" class="{$product/@type}" />
The above is also looking a lot like some templating languages now, and you might see why I am
wondering why there are so many proprietary ones people have to learn, when XSLT is an open, widely
supported, standard with transferable skills!
The above also doesn’t show how clean the code would really be, because someone using xsl:attribute is
likely to use xsl:element as well, so really we should compare the legibility of this:
<xsl:element name="h3">
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

20. Use in-built functions: boolean()


How many times have we seen code like this:
<xsl:if test="$new = 'true'"> ... </xsl:if>
While it works, it is not ideal using string comparison, especially if this kind of test is going to be repeated
in a template.
It would be better to create a variable using this kind of syntax:
<xsl:variable name="isNew" select="boolean($new = 'true')" />
Then, in your code, when you need to use it, you can do things like:
<xsl:if test="$isNew"> ... </xsl:if>
or
<xsl:if test="$isNew = true()"> ... </xsl:if>
or
<xsl:if test="$isNew = false()"> ... </xsl:if>
or
<xsl:if test="not($isNew)"> ... </xsl:if>
These above variations are down to style/preference, but is better from a coding perspective than
constant testing of strings. (Sometimes the calculation of what true or false means may require testing
many values, such as true, True, 1, Y, etc. This can all be hidden away in that one variable declaration,
and the rest of the code is unchanged.)
(Update: Azat rightly notes in a comment below that the variable declaration can be made smaller by
omitting the actual boolean function so it is just this: <xsl:variable name="isNew" select="$new =
'true'">. I find the explicit use of boolean can aid with readability, especially for those new to XSLT so
might be useful to retain under such situations.)
21. Use in-built functions: string()
Instead of this:
<xsl:variable name="mystring">my text</variable>
Consider this:
<xsl:variable name="mystring" select="'my text'" />
Or this:
<xsl:variable name="mystring" select="string('my text')" />
Or, more importantly, instead of this:
<xsl:variable name="bookTitle"><xsl:value-of select="./title" /></xsl:variable>
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.

Example of using xsl:key to optimize lookups:

xml
Copy code
<xsl:key name="orderKey" match="order" use="order/id" />
IBM App Connect – Development Best Practices

7. Keep the XSLT Compact and Maintainable

 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.

8. Ensure Compatibility with API Gateway Context

 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.

Example of converting XML to JSON using XSLT:

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.

10. Adhere to XSLT Standards

 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.

3.4 Schema definitions for a REST API:


IBM App Connect – Development Best Practices

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:

3.4.1. Clearly Define Data Structure

 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.

"required": ["name", "email"]

 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:

"age": { "type": "integer", "minimum": 18 }

 String Formats: Use standard string formats like email, uri, date-time, hostname, etc., for better
validation.

"email": { "type": "string", "format": "email" }

 Length Constraints: For string fields, define length restrictions to ensure data integrity. For example:

"username": { "type": "string", "minLength": 3, "maxLength": 15 }


3.4.3 Versioning and Backward Compatibility

 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

3.4.4. Use Reusable Components

 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.

3.4.5. Support for Arrays and Nested Objects

 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.

3.5 Understand Policy Types and Their Use Cases

API Connect provides several types of policies, including:

 Security policies: for authentication, authorization, and encryption.


 Traffic management policies: for controlling and shaping the traffic, rate limiting, etc.
 Routing and transformation policies: for modifying and routing requests and responses.
 Analytics and monitoring policies: for tracking and logging API calls.
IBM App Connect – Development Best Practices

 Fault handling policies: for managing errors and graceful degradation.

It's critical to understand the purpose and best use case for each policy to apply them effectively in the
API flow.

Apply Policies Based on Specific API Use Cases

 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.

1. Secure Your APIs with Authentication and Authorization Policies

 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.

2. Implement Rate Limiting and Throttling

To prevent misuse or overuse of your API resources:

 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.

3. Ensure High Availability and Scalability

 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

4. Monitor API Performance and Usage

 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.

5. Manage Error Handling Gracefully

 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.

6. Use the API Gateway for Centralized Management

 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.

7. Versioning and Backward Compatibility

 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.

8. Test Policies in Development & Staging Environments

 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

10. Update and Review Policies Regularly

 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

11. Optimize for Performance

 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.

12. Use Contextual Policies

 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.

3.6 Logging and Monitoring

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.7 Testing Practices

Conduct Comprehensive Testing: Perform unit, integration, and performance testing to


validate functionality and performance under various conditions.
Testing and Optimizing Work Flows
• Test flows in isolation
IBM App Connect – Development Best Practices

• Use real data where possible


• Use a controlled environment – access, code, software, hardware
• Take a baseline before any changes are made
• Make ONE change at a time.
• Where possible retest after each change to measure impact
• Start with a single flow instance/server and then increase to measure scaling and
processing characteristics of your flow
Message Flow Standard Unit Test Conditions
• The following are the standard Unit Test Conditions that should be considered by a
developer while performing Unit Test on an interface:
• When a valid Test Data is passed through the API one or more output message(s) are
created on the output queue(s).
• When an invalid Test Data is passed through the API the message is propagated to the
error handling queue for error processing.
• All fields of the output message are of correct length and have been correctly formatted
according to the requirements.
• Where the message has repeating fields or structure, the interface works correctly for
both single and multiple instances of the field or structure.
• Where the message has an optional field or structure, the interface works correctly for
both with and without the field or structure in the message.

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

When trying to communicate with a provider service which needs a complex


cryptographic operations to be performed for either authentication or encryption it’s better
to implement the code at App Connect since it provides more feasibility that includes
integrating with different programming languages such as java,.Net etc

9. Transformation and Enrichment


o Use the APP CONNECT for complex data transformations and enrichment since it offers
more advanced capabilities for these operations.
o Keep the API Connect’s transformation capabilities minimal to avoid performance
overhead.
10. Routing and Load Balancing
IBM App Connect – Development Best Practices

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

20. Message Queue Integration


o Integrate message queues (e.g., RabbitMQ, Kafka) at the APP CONNECT level for
asynchronous communication and improved resilience.
o Use the API Connect to route requests to App Connect incase need to create a Queue
based API.
21. Traffic Segmentation
o Segment traffic based on business logic or client attributes at the API Connect to route
requests to dedicated APP CONNECT instances or clusters.
o Apply priority-based routing to ensure critical traffic is handled with minimal latency.
22. Testing and Validation
o Regularly test API Connect configurations with automated tools to ensure reliability and
security.
o Validate APP CONNECT integration workflows with end-to-end testing to detect and
address bottlenecks or failures.
23. Dynamic Configuration Management
o Use dynamic configuration capabilities in the API Connect for features like API key
rotation, policy updates, and routing changes.
o Leverage APP CONNECT’s configuration management for backend service
orchestration and integration updates.
24. Traffic Shaping
o Use traffic shaping techniques at the API Connect to optimize resource usage and ensure
consistent performance.
o Implement weighted routing or priority-based routing to handle different types of traffic
appropriately.
25. Observability
o Enable distributed tracing across both the API Connect and APP CONNECT to monitor
end-to-end request flows.
o Use metrics and analytics to analyze system performance and detect anomalies in real-
time.
o Integrate tools like Prometheus, Grafana, or ELK for advanced observability.
26. Backup and Disaster Recovery
o Implement backup strategies for API Connect configurations and APP CONNECT data
to ensure service continuity during failures.
o Test disaster recovery plans periodically to validate readiness for unexpected scenarios.
27. Hybrid Cloud Integration
o Ensure the API Connect and APP CONNECT can handle communication between on-
premises and cloud systems seamlessly.
o Use secure tunnels or VPNs to connect hybrid environments.
28. API Lifecycle Management
o Use the API Connect to manage the full lifecycle of APIs, including publishing,
versioning, deprecating, and retiring.
IBM App Connect – Development Best Practices

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

o Enable asynchronous request-response mechanisms at the API Connect using Webhooks


or WebSockets.
o Use the APP CONNECT for backend processing of asynchronous messages and event
triggers.
IBM App Connect – Development Best Practices

39. Global Traffic Management

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

o Use APP CONNECT for deeper and more complex modifications.


68. IoT and Device Management
o Use API Connect to manage IoT device registration, updates, and secure communication.
o Leverage APP CONNECT to process data streams and integrate with IoT platforms.
69. Fallback APIs
o Configure fallback mechanisms at the API Connect to redirect requests to backup APIs
during primary API downtime.
o Use the APP CONNECT to provide backup service endpoints.
70. Data Compression and Optimization
o Use compression (e.g., GZIP) at the API Connect for large payloads to optimize
bandwidth usage.
o Configure APP CONNECT to handle decompression for backend processing.
71. API Policy Simulation
o Simulate API policies at the Gateway level to test new configurations without affecting
live traffic.
o Use the APP CONNECT for testing downstream effects of policy changes.
72. Support for GraphQL APIs
o Enable GraphQL at the API Connect to query multiple backend services in a single
request.
o Use the APP CONNECT to orchestrate and resolve GraphQL queries efficiently.
73. Multi-Language Support for APIs
o Localize error messages and responses at the API Connect for global audiences.
o Use APP CONNECT to manage locale-specific data transformations.
74. Blockchain Integration
o Use API Connect to expose APIs for interacting with blockchain systems.
o Leverage APP CONNECT to process and validate blockchain transactions.

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.

You might also like