Dynamic Endpoints in WSO2 API Manager

From WSO2 APIM 1.10.0, we have introduced new feature to define dynamic endpoints through synapse default endpoints support. In this blog article, I am going to show how we can create an API with dynamic endpoints in APIM.

Assume that you have a scenario where depending on the request payload, the backend URL of the API differs. For instance, if the value of "operation" element in the payload is "menu", you have to route the request to endpoint1 and else you need to route the request to endpoint2.


{
 "srvNum": "XXXX",
 "operation": "menu"
}

In APIM, dynamic endpoints are achieved through mediation extension sequences. For more information about mediation extensions refer this documentation.

For dynamic endpoints we have to set the "To" header with the endpoint address through a mediation In-flow sequence. So let's first create the sequence which sets the "To" header based on the payload. Create a file named dynamic_ep.xml with below content.

<sequence xmlns="http://ws.apache.org/ns/synapse" name="dynamic_ep">
   <property expression="json-eval($.operation)" name="operation" />
   <filter regex="menu" source="$ctx:operation">
      <then>
         <header name="To" value="https://localhost:9448/am/sample/pizzashack/v1/api/menu" />
      </then>
      <else>
         <header name="To" value="https://localhost:9448/defaultep" />
      </else>
   </filter>
   <property expression="get-property('To')" name="ENDPOINT_ADDRESS" />
</sequence>

Supporting Destination based usage tracing for dynamic endpoints.
In here note that we have to set "ENDPOINT_ADDRESS" additional property with the "To" header value which is required for populating destination address for statistics (API Usage by Destination). So if you have statistics enabled in your APIM setup, you have to set this property as well with the endpoint value in order to see the destination address in the statistic views.

Now let's assign this sequence to the API. For that go to the "Implement" tab of the API creation wizard.

  • Select "Dynamic Endpoint" as the "Endpoint Type"
  • Upload dynamic_ep.xml to the "In Flow" under message mediation policies. 
  • Save the API

Now let's try out the API.

With Payload containing "menu"



Wire log showing request going to endpoint 1.


With Payload NOT containing "menu".


Wire log showing request going to endpoint 2.

This way you can write your own logic using mediation extensions and dynamic endpoints in APIM to route your requests to dynamic destinations. 

Comments

Popular posts from this blog

Manually install a maven dependency

PHP-SOAP web service with out a WSDL

Axis 2 web services in eclipse: Exception java.lang.NoClassDefFoundError: org/apache/http/HttpResponseFactory thrown when Services link clicked