A RESTful Web Service in Smalltalk
I got a question via Twitter earlier today about creating a RESTful web service in Smalltalk - I'll do a screencast on this tomorrow, but I thought a quick walkthrough might be useful as well. This example uses the VisualWorks Web Toolkit (which would also work in ObjectStudio) - I'll create a Seaside based example later this week.
Want the code? You can grab that here.
So: step one, load the Web Toolkit - right click and select "Load" after getting the Parcel Manager open:
Once that's in, connect to the public store repository, and load JSONReader - that's just what I'm using in this example. You could just as easily answer an XML document using the SAX driver, or some other format entirely. Anyway, load this via a right click on the latest version:
Next, you need to create a "site definition". You don't need to do this for each service; just for each named site (path) you want to support. You'll have two files: webtools.ini (copy that over from the $(VISUALWORKS)/web directory and edit it), and services-site.ini. The name of the latter file is whatever you want to call it, so long as you reference it in webtools.ini:
Now you can create your new service. Define a subclass of SingleThreadModelServlet:
I added the data instance variable just to have something to respond with. The superclass I'm using ensures that each request will spawn a new instance (thus sharing no data) instead of assuming a stateless model. Next, add these two methods:
initialize "Initialize a newly created instance. This method must answer the receiver." super initialize. data := Dictionary new. data at: 'name' put: 'James Robertson'. data at: 'title' put: 'Smalltalk Product Evangelist'.
doGet "entry point for this service" | content | response contentType: 'application/json'. response status: 200. content := self data asJson. response contentLength: content size. response write: content
Finally, define a listener so that you can make requests. In the launcher, over on the far right is a button for doing that. Press that, then create the listener (on any available port), and click Create and Start:
I put that on port 8011, so using this url: http://localhost:8011/services/servlet/MyService, I should get this (I'm using Firefox):
If you use some application that expects JSON, you'll get the actual object. And that's it - having the service read from a database (etc) is just a detail - the actual RESTful part is pretty easy. Questions? Send them here.
Want the code? You can grab that here.
Technorati Tags: REST, web services, http, json, smalltalk