Google APIs

Posted on

I have been thinking what I should write about for a while. Believe it or not, even though I have two weeks off from work during this holiday season, I still want to do what I do at work – building applications. This blog post is about Google APIs, specifically the Books API with which I built a simple book search application. While there are a lot of APIs available out there, Google APIs is pretty cool to try out.

Currently, there are 55 available APIs on Google APIs Console including Analytics API, Drive API, and YouTube Analytics API. Most APIs have request limits for free usage but some of them are available only with pricing plan such as Google Cloud SQL and Google Maps Geolocation API. The usage of API access is tracked by the API key generated on the website and you can view the quotas and report as well.

Google Books API allows you to perform CRUD operations on Google Books database with the proper authorization. The search scope can be the whole database or specific users’ both custom and pre-defined bookshelves like books they marked as favorites or read. Operations to retrieve user private data require OAuth token which can be easily generated on the Google API access page. The book concepts are easy to understand except that a book is given a term “volume” in the API.

For the coding part, you will need to request a script from Google API website.

//load script to access Google API
<script src="https://apis.google.com/js/client.js?onload=onLoadCallback"> </script>

Once the script is loaded, you can configure the client object for the query request that you are making.

function onLoadCallback(){
   var _this = this;
   //in this example, the param for API is "books" and the param for API version is 'v1' 
   this.client.load('books', 'v1', function (data) {
      //specify your API key       
      _this.client.setApiKey("{Your API key}");
   });
}

Now you can send any search requests with different parameters. The parameter “fields” defines the data fields to be returned. It’s important because without it, a large object with the complete information of books will be returned. You will never need so much information for your application and it would decrease the performance significantly.

var params = {
          //fields to return. return full information by default.
          fields:"items(volumeInfo/title, volumeInfo/authors,volumeInfo/publishedDate, 
                  volumeInfo/description, volumeInfo/imageLinks/thumbnail)",
          //maximum number of results to return. 10 by default
          maxResults:15,
          //sorting method. "relevance" by default
          orderBy:"newest"
    },
    restRequest = this.client.request({
          //specify the query request. 
          //the path below will return maximum number of 15 books 
          //with information matching "javascript" ordered by the most recent published date
          path:"/books/v1/volumes?q=javascript" + "&fields=" + params.fields 
               + "&maxResults=" + params.maxResults + "&orderBy=" + params.orderBy
    });

//sent the request
restRequest.execute(function (resp) {
   //use the return data 
});

With the proper data, you can build so many amazing applications. Google Books API is one of the easy-to-use APIs that I have used but there are a lot more features that I want to add to my Book Search with Google Books API application. If I ever run out of ideas for blogging, that’s what I am going to do :)


Make Your Weather Forecast with Wunderground

Posted on

I haven’t written any post for a while since I was in transition from a college new grad to working full time. I have learnt a lot from the time since I’ve been in school as well as working as an intern. I was thinking about writing a blog post about it but I guess I have postponed it for too long:) Anyway, it’s good to get back on track of blogging.

I check weather reports quite often so I think it would be cool to check on the one that I built from scratch, so I made a 10 day weather forecast widget recently with Dojo web Toolkit and Wunderground weather forecast API.

You can sign up for a free developer account on Wunderground.com to use their API with limited queries. There are different kinds of queries you can make, such as 3 days detailed forecast, 7 days forecast, or just the geographic information. The query is easier than Yahoo weather API since you can put in the lookup zip code or city name directly in the query. You can also get the user current location with their IP address and show the customized weather forecast.

Below is the code to draw the table with data returned by Wunderground API. Please refer to the documentation on the Website for the format of the query. I set the default city as San Jose and I request the geographic information and 7 days forcast.

//zipCode is the value in the input box on the screenshot
if (zipCode === undefined || zipCode.trim().length == 0)
   var query = "http://api.wunderground.com/api/a5ce5afd/geolookup/forecast/q/CA/San_Jose.json";
else
   var query = "http://api.wunderground.com/api/a5ce5afd/geolookup/forecast/q/" + zipCode + ".json";

You will need dojo.io.script for cross site Ajax call.

dojo.io.script.get({
   url: query,
   handleAs: "json",
   callbackParamName: "callback",  //required
   load:dojo.hitch(this, function (data) {
	  this.city.innerHTML = data.location.city;
  	  var tr = dojo.create("tr", {id:"titleRow"});
	  var tr1 = dojo.create("tr", {id:"iconRow"});
	  var tr2 = dojo.create("tr", {id:"textRow"});
	  var tr3 = dojo.create("tr", {id:"temperatureRow"});

          dojo.forEach(data.forecast.simpleforecast.forecastday, dojo.hitch(this, function (entry, index) {
	     dojo.place(dojo.create("td", {innerHTML:entry.date.weekday}), tr);
	     //the weather images are provided by the API
             var img = dojo.create('img', {src:entry.icon_url});
	     var td = dojo.place(dojo.create('td'), tr1);
	     dojo.place(img, td);
	     dojo.place(dojo.create("td", {innerHTML:entry.conditions}), tr2);
	     var temperature = entry.low.fahrenheit + "℉ 
" + entry.high.fahrenheit + "℉";
	     dojo.place(dojo.create("td", {innerHTML:temperature}), tr3);
	  }));

	  this.reportTable.appendChild(tr);
	  this.reportTable.appendChild(tr1);
	  this.reportTable.appendChild(tr2);
	  this.reportTable.appendChild(tr3);
   }),
   // error handle for invalid input
   error: dojo.hitch(this, function(response){
  	  this.errorMesg.style.display = "inline-block";
   })
});

Whenever the user enters a zip code, this method will be called to update the data. If you want the icons on the screenshot above, you will need to connect a few event listeners but remember to have them disconnected when the widget is destroyed to prevent memory leak.


GUI Testing Tool – Selenium

Posted on

Selenium is one of the most commonly used testing tool for Web-based applications. Selenium first started with the automation testing library in JavaScript written by Jason Huggins in 2004 and the library became Selenium Core, which underlies all the functionality of Selenium IDE and Selenium Remote Control. The latest release for Selenium server is 2.11. Selenium supports test scripts written in Java, C#, Ruby, Python, Perl, PHP and .Net. Selenium tests run directly in an supported browser, including IE, Firefox, chrome, and Safari.

What to test?

  1. Static Page Content: verify anything in static source code like title, footer, images.
  2. Links: check if the link is a broken link and if expected page returned with the link.
  3. Functionality: test user response with defined inputs. Typical tests can be for user login/registration to, user account operations, backend data retrieval operations, etc. User input can be via any browser-supported input fields, like text input boxes, check boxes, drop-down menus, etc.
  4. Dynamic Elements: test if the dynamic result is generated based on the specific user action.
  5. Ajax Tests: check if the content is returned after a certain time period. The best way to locate and verify an Ajax element is to use the Selenium 2.0 WebDriver API.

Ways to test?

Selenium provides a test suite to fit different kinds of testing requirements.

  • Selenium IDE
    Selenium IDE is a browser plugin which allows you make your test cases or test suites manually or using the record and play feature. Current highest stable release for Firefox 7.0.1, and Selenium IDE 1.4 supports Firefox 8. It is better to generate and test your test cases/suites in Selenium IDE before running them in the Selenium server.You can import and export test cases/suites in different programming languages.

  • Selenium 1 (Selenium RC)
    Selenium Remote Control server serves as the intermediate server between the client browsers and the client language libraries. Most test cases extend the SeleneseTestCase in the com.thoughtworks.selenium package, which is marked as deprecated. It is recommended that you use the Selenium 2 and WebDrive instead.Use “java -jar [absolute_path_to_seleniumServer]” to start Selenium server and Ctrl+C to stop it. If you double click to start the server, try this URL to stop it: http://localhost:4444/selenium-server/driver/?cmd=shutDownSeleniumServer

  • Selenium 2.0 and WebDriver
    Selenium 2 is a way to test all of these different web browsers without having to install Selenium Core on the web server since it has been bundled with Selenium RC so it can act as a proxy server between the testing application and the test script.

    You can run the testcase with notations as JUnit Test or run the WebDrive as Java application in your IDE. If you have JUnit jar file in your classpath, you can run JUnit tests in command prompt with this syntax:
    java junit.textui.TestRunner [-wait] TestCaseClass

    Test suite directly in command line prompt with syntax similar to below:java -jar selenium-server-standalone-.jar -htmlSuite "*firefox"
    "http://www.google.com" "[absolute_path_to_testSuite]"
    "[absolute_path_to_testResultFile]"

Reference:
1. Platforms Supported by Selenium
2. Selenium Documentation