Friday 15 November 2013

How to access data from remote server API in Sencha Touch 2

Today, we are going to see how to access data from the remote server API using Sencha Touch 2. For our demonstration purpose, we are going to access weather report information using Local Weather API's from World Weather Online Site.

In order to access the weather reports using Local Weather API, you first need to create an account. After that, you need to create an application. By creating an application you will receive an API key. This API key needs to be passed as the request parameter in various Local Weather API's URL.

Now, we are going to access weather reports of my local town (chennai, india) using Local Weather API in Sencha Touch 2. we are going to use Ext.data.JsonP.request(), this method is used for creating cross-domain JsonP request. JsonP is the communication mechanism which allows to request data from a server in a different domain.

Ext.data.JsonP.request({
    url: 'http://api.worldweatheronline.com/free/v1/weather.ashx',

    params: {
        key: ADD-YOUR-API_KEY,
        q: 'chennai,india',
        format: 'json',
        num_of_days: 1
    },

    success: function (result, request) {
        console.log(result.data);
   },
    failure: function (e) {
        Ext.Msg.alert("Error", "Can not access data from worldweatheronline.com");
    }
});

Important Note: you need to replace 'ADD-YOUR-API_KEY' with your API key. Also you need to add 'Ext.data.JsonP' class as the requires in Ext.Application class.

Here are the important request parameters in Local Weather API

q: Location Specific Information (city, state, country)
extra: Include any additional information
num_of_days: Number of days of forecast
format: output response format  (XML, JSON, CSV)

In order to know, all the available request parameters, please refer the API explorer page and official documentation page.

Hope, you enjoyed this post.

No comments:

Post a Comment