Tuesday, January 3, 2012

Returning JSON fault information to JQuery-based API clients

Since many APIs are called by JavaScript libraries like JQuery, it's convenient to return fault information as JSON so that it can be easily read by the client. The object is then parsed to retrieve the reason for the fault. Some APIs make this easy, such as the Rackspace Cloud Identity API which allow faults to be returned as JSON or XML. But in many cases, you have to laboriously configure this JSON conversiona yourself [For example, in the case of WCF, Iain Mitchell has a good blog post about how it can be made to return JSON formatted faults for consumption by JQuery.]

A Gateway serves an important purpose here, by providing fine-grained information on why clients are blocked. A Gateway can XML to clients which expect XML responses, and JSON to REST API clients which expect JSON. Let's see how you can use the Vordel Gateway to take a policy which returns an XML fault (in this case a SOAP Fault) and converts it automatically to JSON...

To start this, I fired up Vordel Policy Studio and connected to my Dev API Gateway. I then dragged in a Policy Shortcut to a policy called "JSON Fault". Next I right-clicked on it and choose "Set as Fault Handler", as shown below:

This means that if any of the filters in the chain return false, my policy gets called. Next let's look at this policy. You can see below that it takes a regular SOAP Fault and converts it automatically to JSON:

When we look at it in action, in the API Gateway's Real-Time Monitoring, we see the familiar "Path through the policies" on the left, and on the right you can see the JSON which is returned to the JQuery client:


The API Gateway's Real-Time Monitoring shows what is happening now for your APIs and services. But in order to look at what has happened in the past, we open the API Gateway's audit trail. Here you can see the opening page, and I click on the "Audit Trail" button:

On the Audit Trail, I run a report for the API requests blocked in the last hour by my API Gateway. Here I see a bunch, and I click on one to see more detail.

When I click on the API request which was blocked, I see the exact reason why it was blocked in the "Path through the Policy". I can see below that it was the authentication which failed, the same reason which was passed back to the JQuery client.

So in summary, it's quite straightforward to return JSON fault information to clients, and view fault information in the Audit Trail, using the Vordel Gateway. To get more info, or your own copy of the Vordel Gateway, contact us on info@vordel.com