fb
API Management 6 min

WSO2TORIAL: Creating a custom handler for the WSO2 API Manager 2.1.0

Rob Blaauboer
Rob Blaauboer
Integration Consultant & WSO2 Trainer
WSO2Torial witruimte 2
Scroll

The WSO2 API Manager is the solution for management, monitoring and monetization of API’s. The current version of the API Manager is a complete solution that consists of a number of components that work seamlessly together.

To give a high-level overview, the API Manager consists of several individual components:

  1. API Publisher
  2. API Store
  3. API Gateway
  4. API Key Manager
  5. Traffic Manager
  6. Analytics

API Manager front end.png

Figure 1 Image

The open source nature of all WSO2 products make them extensible to fit your organization’s needs.

By extensibility we do not mean changing the source code of the product but rather using one of the extension point the products offer. In case of the API Manager 2.1.0 one of the extensions is the use of a custom handler. This of course begs the question what exactly a handler is. In this WSO2 Tutorial you will read how to create a custom handler for the WSO2 API Manager 2.1.0.

What is a handler?

A handler is one of the processes that an API invocation goes through when it travels through the Gateway component (#3 in the above image). These handlers are executed sequentially and by default in the order as shown in fig. 2.

Handler.png

Let’s see what each handler does:

CORSRequestHandler:  Sets the CORS headers to the request and executes the CORS sequence mediation logic. This handler is thereby responsible for returning the CORS headers from the gateway or routing the requests to the backend and letting the backend send the CORS headers.

This is an optional setting that will be triggered when Enable API based CORS Configuration is checked.

APIAuthenticationHandler: Validates the OAuth2 bearer token used to invoke the API. It also determines whether the token is of type Production or Sandbox and sets MessageContext variables as appropriate.

Again, this handler is optional, in the sense that if there is no token required for the API or an URI Template the handler will either not be invoked or it will return almost directly after invocation. (WHAT IS IT?)

APIThrottleHandler: Throttles requests based on the throttling policy specified by the policyKey property. Throttling is applied both at the application level as well as subscription level.

APIMgtUsageHandler: Publishes events to WSO2 Data Analytics Server (WSO2 DAS) for collection and analysis of statistics. This handler only comes to effect if API usage tracking is enabled.

APIMgtGoogleAnalyticsTrackingHandler: Publishes events to Google Analytics. This handler only comes into effect if Google analytics tracking is enabled.

APIManagerExtensionHandler : Triggers extension sequences. By default, the extension handler is listed at last in the handler chain, and therefore is executed last. To configure the API Gateway to execute extension handler first, uncomment the <ExtensionHandlerPosition> section in the <APIM_HOME>/repository/conf/api-manager.xml file and provide the value top. What is executed are sequences on the IN-, OUT- and Faultflow. This is optional and should be checked when publishing the API.

But, there is more.

These are just the default handlers. You can create a custom handler and execute it when the API flows through the API gateway. By the way, by editing the publishing template that the API Publisher uses (velocity template) you have complete control on what happens in the gateway.

Publishing an API

When an API is created, a file with its synapse configuration is added to the API Gateway. You can find it in the [APIM-HOME]/repository/deployment/server/synapse-configs/default/api folder. This XML file has a set of handlers (from the velocity template), each of which is executed on the APIs in the same order they appear in the configuration.

<handlers>
     <handler class="org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler">
        <property name="apiImplementationType" value="ENDPOINT"/>     </handler>
    <handler class="org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler"/>
     <handler class="org.wso2.carbon.apimgt.gateway.handlers.throttling.APIThrottleHandler">
        <property name="id" value="A"/>
        <property name="policyKeyResource" value="gov:/apimgt/applicationdata/res-tiers.xml"/>
        <property name="policyKey" value="gov:/apimgt/applicationdata/tiers.xml"/>
        <property name="policyKeyApplication" value="gov:/apimgt/applicationdata/app-tiers.xml"/>
     </handler>
     <handler class="org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageHandler"/>
     <handler class="org.wso2.carbon.apimgt.usage.publisher.APIMgtGoogleAnalyticsTrackingHandler">
        <property name="configKey" value="gov:/apimgt/statistics/ga-config.xml"/>
     </handler>
     <handler class="org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler"/>
  </handlers>

As said we can extend the flow by adding a custom handler and including it in the Synapse configuration file.

Writing a custom handler

What is happening in a custom handler is completely up to you. It could be that you want to include extra security, log each invocation in a database or something else.

You can extend the API Manager with a custom handler by writing your own authentication handler class. This custom handler must extend org.apache.synapse.rest.AbstractHandler class and implement the handleRequest() and handleResponse() methods. We have created a simple custom handler that does nothing else but put a message on the console.

The reason is that we want to keep these articles simple yet show the mechanism behind it.

So we create a maven project with the following code in it:

Handler code 2.png

The HelloWorldHandler extends the AbstractHandler and implements the MAnagedLigecycle that among other things allows for the release of  used resourceThe handleRequest and handleResponse both return true after putting a message on the console.

This is of course unusual because normally there will be a true and false option depending on the logic incorporated in the program. So when you take this example you can extend it with your own logic.

Since we have created a maven project, we need to create the jar file (in the /target directory) with:

mvn clean install

After that copy the jar file [APIM-HOME]/repository/components/lib and restart the API Manager. The jar files are not hot deployed.

Engaging the custom handler

You can engage a custom handler to all APIs at once or only to selected APIs. To engage a custom handler to APIs, you need to add the custom handler with its logic in the <APIM_HOME>/repository/resources/api_templates/velocity_template.xml file.

There is however a quicker option and that is quickly changing the Synapse configuration of the API found in [APIM-HOME]/repository/deployment/server/synapse-configs/default/api.

It is not recommended to update the API source code via the source view UI or file system when engaging a custom handler to selected APIs, because the customizations get overridden by the publisher updates.

But it this case it is a quick way to test the custom handler. I’ve deployed the sample API (Pizzashack) on the API Manager and will change that file (admin--PizzaShackAPI_v1.0.0.xml).

Find the handler section and add the following line:

<handler class="com.yenlo.api.handler.HelloWorldHandler"/>

Handler - HelloWorldHandler.png

Invoke the API for instance using SOAPUI to see the custom handler in action.

Invoke the API for instance using SOAPUI .png

Note that you need to be subscribed to the API, have an access token and added a REST project to SoapUI with OAUTH2 authorization. As you can see, you get a response and on the console of the API Manager you will see two lines.

response and on the console of the API Manager .png

This shows a custom handler that is executed when you invoke the API.

Thanks to my colleague Rob Brouwers for his contribution to this blog.

If you have any questions about this blogpost contact us via the comments section of this blog. View also our WSO2 Tutorials, webinars or white papers for more technical information. Need support? We do deliver WSO2 Product SupportWSO2 Development SupportWSO2 Operational Support and WSO2 Training Programs.