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:
- API Publisher
- API Store
- API Gateway
- API Key Manager
- Traffic Manager
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.
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.
<property name="apiImplementationType" value="ENDPOINT"/> </handler>
<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"/>
<property name="configKey" value="gov:/apimgt/statistics/ga-config.xml"/>
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:
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
There is however a quicker option and that is quickly changing the Synapse configuration of the API found in [APIM-
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
Find the handler section and add the following line:
Invoke the API for instance using SOAPUI to see the custom handler in action.
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.
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 Support, WSO2 Development Support, WSO2 Operational Support and WSO2 Training Programs.