Archive for the ‘API’ Category

Web + API + CORS = Like

June 22, 2012

In my previous post around API driven web application architectures I delved into the need for every web application to have a corresponding API. There is shift in trends around scalable web application development.

Enterprises need “micro applications”  not “monolithic  applications”.

Take a look at Mary Meeker’s latest Internet trends which talks about mobile devices way surpassing PC based access as we step into the latter half of the decade.

Mobile apps need APIs, not UIs. Devices need APIs not UIs.

If you are building an enterprise application, build your API first not your UI. Of couse UI and User experience is really important and you will continue to court users over the web access from PC devices/mobile browsers.

Which comes to the real heart of this post. If your web application and API applications are two (or more ) applications, how do they talk to each other. Let’s look cover the basics before we review our options.

The Protocol: REST…REST…REST

 

This also implies that you should be using JSON for your data exchange and HTTP/HTTPS as your underlying transport mechanism. If your are thinking of XM-Hell, then think again.

The Client: HTML5, Javascript, CSS3

 
HTML5, CSS3, Ajax, Javascript are starting to make a huge comeback. Thanks to the Google(s),Facebook(s),Twitter(s), LinkedIn(s) of the world to popularize the power of client side scripting and the trend that is also know as “single page web apps”.
Note: If you have not read LinkedIn’s tech blog about how they build their iPad app, I would strongly recommend you do.

The options:

 
Ideally you should be able to do a Ajax request (GET, POST, DELETE etc.) over to your API app and it should work. Browsers have prevented this with the “Same origin policy” for JavaScript. This policy is a really good thing as it helps web applications be less prone security hacks that allow arbitrary scripts to be executed as the user. Given this policy, there are three options to get your web application to talk to your API:
  1. Server side Proxy
  2. JSONP
  3. Cross Origin Resource Sharing (CORS)
 
Server side Proxy 
 
This is the most obvious choice and probably what most developers will start with. Here’s how the sequence of events play out with this option:
This is certainly a very good option and is the chosen road for most applications especially when the web app needs to interact with a 3rd party API that the app does not control.  However proxying every request, has performance tradeoffs as well the need to keep the server side code up-to-date with the API versions. In the world of JSON/Ajax type web apps, the server side component is not adding too much value.
 
JSONP
 
Short for JSON with Padding, allows you to inject <script> elements at runtime and invoke a server side URL that returns the JSON data wrapped in a Javascript function. Read more about it here. The flow of events for JSONP is below:
For e.g. say your API end point is http://api.app.com/getSomething, the sequence of events would be:
  1. Your Javascript library (JQuery etc.) would create a new <script> DOM element with “src” attribute set to http://api.app.com/getSomething?callback=javascriptFn
  2. The API will receive a HTTP GET request, process the request and generate the JSON response
  3. Once the response is generated, it will wrap the JSON response around the Javascript function name and return the response setting the Content-Type header value to application/javascript
    The response would be something like this:

    javascriptFn({'responseStr':'Response Value'});

  4. The Browser receives the response and because the content type is set to JavaScript, it will attempt to call the function called javascriptFn passing in the JSON response. The function can now update the DOM/do any processing with the data as it deems fit.
The major downside is because this is all happening over HTTP(S) GET you cannot really pass in HTTP headers (e.g. Auth information) which essentially makes this a very un-secure option. This is a major reason why most IT/ Enterprises shun this approach. JSONP is certainly an option for any public web services that does not give away any user specific secret/authentication credentials.
 
Cross Origin Resource Sharing
 
Cross Origin Resource Sharing (CORS) is a more recent technique that overcomes the downsides of JSONP and provide a more “secure” way for your applications to talk to each other. It is currently a “draft” spec by W3C (http://www.w3.org/TR/cors/). However most modern web browsers have added support for CORS already.  For a good list of support browsers, go to http://en.wikipedia.org/wiki/Cross-origin_resource_sharing#Browser_support
 
Implementing CORS on a server is as simple as sending additional HTTP headers, for example:

Access-Control-Allow-Origin: http://example.com:8080

There are additional headers that can be sent as part of the response. Below are some additional headers:


Access-Control-Allow-Origin
Access-Control-Allow-Credentials
Access-Control-Expose-Headers
Access-Control-Max-Age
Access-Control-Allow-Methods
Access-Control-Allow-Headers

On the client side, you call your API using the standard Ajax / XMLHttpRequest method. For e.g., if you were using JQuery (you should if you are not !!!). The code would look something like this:

function callApi(){
$.get( 'http://api-dot-com.herokuapp.com/apiCall',
{requestParam: 'Parametervalue'},
function(responseJson){
doSomething(responseJson); console.log(d);
}
);
}

The browser when making this Ajax request sends the following header as part of the request:

Origin: http://foo.example

In addition, the client(browser) can send an additional Access-Control-Request-Method and Access-Control-Request-Headers header values for fine grained control on the HTTP Method that is being used to make the request.

The server will receive this header and determine if the Access-Control-Allow-Origin should be sent back with the corresponding value.