Saturday, December 27, 2014

Customizing API Manager – Adding custom handlers

API Manager comes with a built in ESB. It acts as the gateway and handles all the api calls. API creator can manipulate the requests before they are sent back to the actual back end by configuring the api gateway. Handlers can be used to achieve this task.
There are some default handlers added to an api once it is created. To check this first create and publish an api by login in to API manager publisher and then go to the <AM_HOME>/repository/deployment/server/synapse-configs/default/api location. If the api is created successfully, there will be an xml file with the name of the api in this location (creator_name_version.xmlwould be the exact name ). Under the <hanlders> element, all the default handlers are defined. These handlers execute (in the order) first once a request hits the api before sending it to the back end.
These handlers handle different tasks related to the api call. First handler handles the authentication part of the request. For example, to call an published api, we need to use an access token ( adding it to the Authorization header of the request). APIAuthenticationHandler handler is used to validate the token and reject invalid requests.
Adding a custom handler to an existing api
api creator may need to add his own processing. (for example validate some other headers) . He can develop a custom handler and plug it in to the api. Tutorial on creating a custom handler can be found in the Api manager documentation. After creating the handler, put it in to the<AM_HOME>/repository/components/lib folder and insert an entry inside the <handlers> element
<handler class="org.wso2.customhandlers.testhandler"/>
Note: To build the custom handler you need the have the synapse libraries in the class path. You can point to<AM_HOME>/repository/components/plugins folder for this.
Adding a custom handler to all the apis.
If this handler needs to be added to every new api, then it is not practical to add it manually once the api is created. API manager provides templates to define the structure of the api and we can modify this to have the custom handler as a default handler. This way every api will have the custom handler inside the<handlers> element
For this we need to modify the velocity_template.xml file in the<AM_HOME>/repository/resources/api_templates/ location. Open it and find the location '<handlers>'
Add the custom handler inside the <handlers> element after the #end tag. This will add the custom handler after the default handlers.

No comments:

Post a Comment