martedì 3 luglio 2007

RESTful Web Services Example 2.15 - Yahoo! News Search w/ JSON

The final example from Chapter 2 of the RESTful Web Services book that I'll be converting to Squeak is another version of the Yahoo! Web Search, this time using JSON and, to spice things up a little, the news search service instead of the web search one.

In order to get this example to work, you'll have to install Squeak's JSON package, available from SqueakSource.

Here's the code for the example:
yahooNewsSearch: aString
| baseURI document term json |
"Code taken from RESTful Web Services. Copyright © 2007 O'Reilly Media, Inc.
All rights reserved. Used with permission."
baseURI := 'http://api.search.yahoo.com/NewsSearchService/V1/newsSearch'.
term := aString encodeForHTTP.
json := Curl new getContentsUrl: baseURI , '?appid=restbook&output=json&query=' , term.
document := Json readFrom: json readStream.
((document at: #ResultSet) at: #Result) do:
[:element |
Transcript
show: (element at: #Title) printString;
cr]

There isn't much to say about this example that hasn't been said for Example 2.1: the document returned from the #getContentsUrl: send is a JSON script that is fed to Squeak's JSON parser. The parser returns a nested structure of Dictionaries and Arrays that can be accessed with the standard at: message. The results are then printed to the Transcript, as usual.

The code for this method may be found in package RWS-gc.8 in the RWS repository.

This post concludes the series of examples from Chapter 3 of the RWS book. In the next posts (coming next week or so) I'll show examples from Chapter 3, including a complete implementation of a Squeak client for the Amazon S3 service.

Nessun commento: