Skip to content

Route Requests based on Message Content

What you'll build

In this tutorial, we are creating the mediation artifacts that can route a message to the relevant endpoint depending on the content of the message payload.

When the client sends the appointment reservation request to the Micro Integrator, the message payload of the request contains the name of the hospital where the appointment needs to be confirmed. The HTTP request method that is used for this is POST. Based on the hospital name sent in the request message, the Micro Integrator should route the appointment reservation to the relevant hospital's back-end service.

Concepts and artifacts used

  • REST API
  • HTTP Endpoint
  • Property Mediator
  • Call Mediator

Let's get started!

Step 1: Set up the workspace

The following software and configurations are required to proceed with this tutorial:

  • Visual Studio Code (VS Code): with the Micro Integrator extension installed.
  • Java Development Kit (JDK): Version 11 or 17 is required. Ensure the JDK is properly configured in your system's PATH environment variable.
  • Apache Maven: Ensure Apache Maven is installed and its path is correctly set within the system's PATH environment variable.

Info

Follow the Install Micro Integrator for VS Code documentation for a complete installation guide.

Step 2: Develop the integration artifacts

Follow the instructions given in this section to create and configure the required artifacts.

Create an integration project

The Integration project will contain all the required artifacts for the integration solution.

  1. Launch VS Code with the Micro Integrator extension installed.

  2. Click on the Micro Integrator icon on the Activity Bar of the VS Code editor.

    MI VS Code Extension

  3. Click Create New Project on Design View.

    Design View Pane Create New Project

    Next, the Project Creation Form will be opened.

  4. In the Project Creation Form, enter SampleServices as the Project Name.

  5. Provide a location under the Select Project Directory.

  6. Click Finish.

You will now see the projects listed in the Project Explorer.

Create endpoints

In this tutorial, we have three hospital services hosted as the backend:

  • Grand Oak Community Hospital: http://localhost:9090/grandoaks/
  • Clemency Medical Center: http://localhost:9090/clemency/
  • Pine Valley Community Hospital: http://localhost:9090/pinevalley/

The request method is POST and the format of the request URL expected by the back-end services is http://localhost:9090/grandoaks/categories/{category}/reserve.

Let's create three different HTTP endpoints for the above services.

  1. Go to Micro Integrator Project Explorer > Endpoints. This will open the Endpoint Form, from which you can select the HTTP Endpoint.

  2. Enter the information given below to create the new endpoint.

    Property Value Description
    Endpoint Name GrandOakEP The name of the endpoint representing the Grand Oaks Hospital service.
    URI Template http://localhost:9090/grandoaks/categories/{uri.var.category}/reserve The template for the request URL expected by the back-end service.
    Method POST Endpoint HTTP REST Method.

    Grand Oak endpoint

  3. Click Create.

  4. Similarly, create the HTTP endpoints for the other two hospital services using the URI Templates given below:

Endpoint Name Type URI Template Method
ClemencyEP HTTP http://localhost:9090/clemency/categories/{uri.var.category}/reserve POST
PineValleyEP HTTP http://localhost:9090/pinevalley/categories/{uri.var.category}/reserve POST

You have now created the three endpoints for the hospital back-end services that will be used to make appointment reservations.

Tip

You can also create a single endpoint where the differentiation of the hospital name can be handled using a variable in the URI template. See the tutorial on Exposing Several Services as a Single Service.

Using three different endpoints is advantageous when the back-end services are very different from one another and/or when there is a requirement to configure error handling differently for each of them.

Create a REST API

  1. Go to MI Project Explorer > APIs.

    create new api

  2. Hover over APIs and click the + icon that appears to open the API Form.

    add API

  3. Enter the details given below to create a new REST API.

    Property Value Description
    Name HealthcareAPI The name of the REST API.
    Context /healthcare Here you are anchoring the API in the /healthcare context. This will become part of the name of the generated URL used by the client when sending requests to the Healthcare service. For example, setting the context to /healthcare means that the API will only handle HTTP requests where the URL path starts with http://host:port/healthcare.

    Synapse API artifact

  4. Click Create.

  5. On the Service Designer, click on the default API resource to access the Properties tab to edit the default API resource.

    Edit API resource

  6. Enter the following details:

    Property Description
    URI Template /categories/{category}/reserve
    URL Style URI_TEMPLATE
    Methods POST

    Edit API resource

  7. Click Update.

Define the mediation flow

You can now start configuring the API resource.

  1. Open the Resource View of the API resource.

  2. Click on the + icon to open the Palette.

    open palette

  3. Select Property mediator under Mediators > Generic.

  4. Specify the following values.

    Info

    This is used to extract the hospital name that is sent in the request payload.

    Property Description
    Property Name Hospital
    Property Action set
    Property Scope DEFAULT
    Property Value

    Follow the steps given below to specify the expression value:

    1. Click the EX button next to the Property Value field. This specifies the value type as expression.
    2. Now, click the pen icon to open the Expression Editor.
    3. Enter json-eval($.hospital) as the Expression Value.
    Note: This is the JSONPath expression that will extract the hospital from the request payload.
    Click Save.

    Property pane

  5. Click Submit.

  6. Next, add a Switch mediator from the palette just after the Property mediator.

  7. In the Switch pane, specify the details for Source XPath:

    1. Add get-property('Hospital') as the Source XPath.

    2. Click the EX button next to the Source XPath value field. This specifies the value type as expression.

  8. Specify the details for Case Branches:

    We have three different hospital endpoints, which corresponds to three switch cases. Therefore, add three Case Branches with the below details.

    1. Click Add Parameter under Case Branches to add a branch.

    2. Change the Case RegEx value for the switch cases as follows:

      Case 1: grand oak community hospital
      
    3. Click Save.

    4. Similarly, add two other branches and change the Case RegEx value for the respective switch cases as follows.

      Case 2: clemency medical center
      Case 3: pine valley community hospital 
      
  9. Click Submit to save the values for Switch mediator.

  10. Add a Log mediator to the first Case box of the Switch mediator and name it Grand Oak Log.

    grandoak case box

    Info

    This prints a message indicating to which hospital the request message is being routed.

  11. With the Log mediator selected, access the Properties tab and give the following details:

    Property Value Description
    Log Category INFO Indicates that the log contains an informational message.
    Log Level CUSTOM Only specified properties will be logged by this mediator.
    Log Separator (blank) Since there is only one property that is being logged, we do not require a separator. Therefore, this field can be left blank.
    Properties Follow the steps given below to extract the stock symbol from the request and print a welcome message in the log:
    1. Click Add Parameter under Properties.
    2. Add the following values:
      • Property Name : message
      • Prperty Value : fn:concat('Routing to ', get-property('Hospital'))
        Next, click on the EX icon, because the required properties for the log message must be extracted from the request, which we can do using an XPath expression.)
      Note: This XPath expression value gets the value stored in the Property mediator and concatenates the two strings to display the log message: Routing to <hospital name>.
    3. Click Save.

  12. Click Submit.

  13. Add a Call Endpoint mediator from the palette after the Log mediator.

    add call mediator

  14. On the Call Endpoint pane, select GrandOakEP from Select Endpoint dropdown.

  15. Provide GrandOak Log as the Description.
  16. Click Submit.

  17. Similarly, add Log mediators in the other two Case boxes in the Switch mediator and then enter the same properties. Make sure to name the two Log mediators as follows:

    • Clemency Log
    • Pine Valley Log
  18. Add Call mediators after these log mediators and add the ClemencyEP and PineValleyEP endpoints respectively from the Defined Endpoints palette.

    Info

    You have now configured the Switch mediator to log the Routing to <Hospital Name> message when a request is sent to this API resource. The request message will then be routed to the relevant hospital back-end service based on the hospital name that is sent in the request payload.

  19. Add a Log mediator to the Default case of the Switch mediator and configure it the same way as the previous Log mediators.

    default case

    Note

    Make sure to name this Fault Log and change its Property Expression as follows:fn:concat('Invalid hospital - ', get-property('Hospital'))

    The default case of the Switch mediator handles the invalid hospital requests that are sent to the request payload. This logs the message (Invalid hospital - <Hospital Name>) for requests that have the invalid hospital name.

  20. Add a Respond mediator just after the Switch mediator to return the response from the health care service back to the client.

You have successfully created all the artifacts that are required for routing messages to a back-end service depending on the content in the request payload.

Resource view

Step 3: Build and run the artifacts

Prerequisites

Before you begin, install Micro Integrator on your machine:

  1. Go to the WSO2 Micro Integrator web page, click Download, provide necessary details, and then click Zip Archive to download the Micro Integrator distribution as a ZIP file.

  2. Extract the ZIP file. The extracted folder will be referred as the <MI_HOME> folder.

Once you have downloaded and set up the Micro Integrator locally, follow the steps given below. Use one of the below two methods.

  1. Click on the Command Palette on the top of the VS Code.

  2. Type > to show the available commands.

  3. Select MI: Add MI server.

  4. Select Add MI server.

  5. Select the folder where <MI_HOME> is located. This wll be set as the current server path.

    Current server path

  6. Run the project.

Use one of the following two options to build and run the project:

Option 1

  1. Click on the Command Palette on the top of the VS Code.
  2. Type > to show the available commands.
  3. Select MI: Build and Run.

Option 2

Click the Build and Run icon located on the top right corner of the VS Code.

Build and run

The artifacts will be deployed in the Micro Integrator server and the server will start.

  • See the startup log in the Console tab.
  • See the URLs of the deployed services and APIs in the Runtime Services tab.

Step 4: Test the use case

Let's test the use case by sending a simple client request that invokes the service.

Start the back-end service

  1. Download the JAR file of the back-end service from here.
  2. Open a terminal, navigate to the location where your saved the back-end service.
  3. Execute the following command to start the service:

    java -jar Hospital-Service-JDK11-2.0.0.jar
    

Send the client request

Let's send a request to the API resource to make a reservation. You can use Postman application as follows:

  1. Open the Postman application. If you do not have the application, download it from here : Postman

  2. Add the request information as given below and click the Send button.

    Method POST
    Headers Content-Type=application/json
    URL http://localhost:8290/healthcare/categories/surgery/reserve

    • The URI-Template format that is used in this URL was defined when creating the API resource: http://host:port/categories/{category}/reserve.
    Body
    { "patient": { "name": "John Doe", "dob": "1940-03-19", "ssn": "234-23-525", "address": "California", "phone": "8770586755", "email": "[email protected]" }, "doctor": "thomas collins", "hospital_id": "grandoaks", "hospital": "grand oak community hospital", "appointment_date": "2025-04-02" }

    • This JSON payload contains details of the appointment reservation, which includes patient details, doctor, hospital, and data of appointment.




If you want to send the client request from your terminal:

  1. Install and set up cURL as your REST client.
  2. Create a JSON file named request.json with the following request payload.
    {
        "patient": {
        "name": "John Doe",
        "dob": "1940-03-19",
        "ssn": "234-23-525",
        "address": "California",
        "phone": "8770586755",
        "email": "[email protected]"
        },
        "doctor": "thomas collins",
        "hospital_id": "grandoaks",
        "hospital": "grand oak community hospital",
        "appointment_date": "2025-04-02"
    }
    
  3. Open a terminal and navigate to the directory where you have saved the request.json file.
  4. Execute the following command.
    curl -v -X POST --data @request.json http://localhost:8290/healthcare/categories/surgery/reserve --header "Content-Type:application/json"
    

Analyze the response

You will see the following response received to your HTTP Client:

{"appointmentNumber":1,
    "doctor":
         {"name":"thomas collins",
          "hospital":"grand oak community hospital",
          "category":"surgery","availability":"9.00 a.m - 11.00 a.m",
          "fee":7000.0},
    "patient":
        {"name":"John Doe",
         "dob":"1990-03-19",
         "ssn":"234-23-525",
         "address":"California",
         "phone":"8770586755",
         "email":"[email protected]"},
    "fee":7000.0,
"confirmed":false,
"appointmentDate":"2025-04-02"}

Now check the Console tab and you will see the following message: INFO - LogMediator message = Routing to grand oak community hospital

This is the message printed by the Log mediator when the message from the client is routed to the relevant endpoint in the Switch mediator.

You have successfully completed this tutorial and have seen how the requests received by the Micro Integrator can be routed to the relevant endpoint using the Switch mediator.