yusukebe blog

Tuesday, July 21, 2009

Simple sample code of Google Ajax Search using jQuery

A same javascript code is written often. So, I paste simple a sample code at below. This JS code loads a JSONP of Google Ajax Search by jQuery and dumps titles to Firebug console.


var apiUrl = 'http://ajax.googleapis.com/ajax/services/search/web?';

function googleSearch ( q ) {
var jsonUrl = apiUrl + 'v=1.0&q=' + q + '&start=1&callback=?';
loadJson( jsonUrl );
function loadJson( url ){
$.getJSON( url, function( data ) {
if( data.responseData.cursor.estimatedResultCount > 0 ){
$.each(data.responseData.results, function(i, entry){
console.log(entry.title);
});
}
});
}
}

Easy to access any WebService API using Perl

I'll introduce easy way to access and parse the any WebService API such as "Google API", "Flickr", "YouTube" etc. using my CPAN module "WebService::Simple".

First, install WebService::Simple from CPAN. The latest version is '0.16'.

Simple sample code is here:

use strict;
use warnings;
use WebService::Simple;
use Data::Dumper;

my $flickr = WebService::Simple->new(
base_url => "http://api.flickr.com/services/rest/",
param => { api_key => "your_api_key", }
);

my $response =
$flickr->get( { method => "flickr.photos.search", text => "cat" } );
print Dumper $response->parse_response;



This program access to Flickr API, call the search photos method, parse the response as hash reference, and dump the object by Data::Dumper.

WebService::Simple helps us three things below.

1. Make the request url to API
2. Fetch the response from API includes contents ( XML, JSON etc. )
3. Parse the content to use ( by XML::Simple etc. )

So, any WebServices could be manipulated.

Let's see another sample code for searching YouTube videos.


use WebService::Simple;
use WebService::Simple::Parser::XML::Simple;
use XML::Simple;

my $keyword = shift || 'Michael Jackson';
my $xs = XML::Simple->new( KeyAttr => [], ForceArray => ['entry'] );
my $service = WebService::Simple->new(
base_url => "http://gdata.youtube.com/feeds/api/videos",
param => { v => 2 },
response_parser =>
WebService::Simple::Parser::XML::Simple->new( xs => $xs ),
);

my $res = $service->get( { 'q' => $keyword, } );
my $ref = $res->parse_response();

for my $entry ( @{ $ref->{entry} } ) {
print $entry->{link}->[0]->{href} . "\n";
}



WebService::Simple make it easy to access WebService API. Use it if you interested in :-)

First Post

"yusukebe blog" has been started now. I write some articles on my personal blog named "yusukebe nikki" in Japanese, but his blog is wrote by my poor English :-)

My interest things are making web services or mashup sites, writing Perl code, and technology related of a linux server.

So, in this blog I'll post entries about tips of these technologies.

If you are interested, please subscribe the feed of "yusukebe blog"!