Message template
How to configure a Message template policy to create a mock API response for the DataPower® API Gateway in the assembly editor.
Before you begin
| Gateway | Policy version |
|---|---|
| DataPower API Gateway | 2.0.0 |
This topic describes how to configure the policy in the assembly editor. For details about how to configure the policy in your OpenAPI source, see message-template.
About this task
You can configure a Message template policy to create a mock API response for the DataPower API Gateway. Usually, an API response is obtained by creating an Invoke policy in your API that interacts with a backend service. However, you can use the Message template policy to produce a mock response internally by using the assembly logic, without needing to interact with a separate backend service. This mock response can return a simple literal response, such as a JSON document, or it can include dynamic content such as values that are derived from the request, or from other parts of the assembly context.
You can complete this task either by using the API Designer UI application, or by using the browser-based API Manager UI.
Procedure
Examples
- Example 1: Static mock API response
- A Handlebars template with no expressions, which means that the output from executing the
template is just the template contents. In this example, the output is a JSON
document.
{ "orderNumber": "OU812", "orderItems": [ { "itemCode": "7013-520", "quantity": 1 }, { "itemCode": "7013-590", "quantity": 1 } ] } - Example 2: API response with dynamic content
- This example expands on Example 1, with the addition of a value taken from the request.
{ "customerId": "{{?request.parameters.customerId}}", "orderNumber": "OU812", "orderItems": [ { "itemCode": "7013-520", "quantity": 1 }, { "itemCode": "7013-590", "quantity": 1 } ] }Here, the
customerIdvalue is obtained by using a simple Handlebars expression that reads a property value from the input context. The result is that thecustomerIdproperty value that's returned in the response, is the value from the parameter in the API request. Expressions like this example can be used to insert the data of any form, not just JSON property values. - Example 3: Conditional logic within the template
- This example uses the built-in capability of the Handlebars template language to use conditional
expressions.
{ {{#if request.headers.app-context}} "context": "{{?request.headers.app-context}}", {{/if}} "customerId": "{{?request.parameters.customerId}}", "orderNumber": "OU812", "orderItems": [ { "itemCode": "7013-520", "quantity": 1 }, { "itemCode": "7013-590", "quantity": 1 } ] }Here, a
contextproperty is included in the generated response by using the value of theapp-contextheader, if this value is present in the request. Handlebars also includes built-in support for loops, if-then-else, and so on.