Dynamic Web Development with Seaside

24.2.2Defining a Service

The idea behind Seaside-REST is that each HTTP request triggers a method of the appropriate service implementation. All service methods are annotated with specific method annotations or pragmas.

It is possible to define a method that should be executed when the handler receives a GET request by adding the annotation <get> to the method. As we will see in Section 24.3, a wide range of other annotations are supported to match other request types, content types, and the elements of the path and query arguments.

To implement our todo service, we merely need to add the following method to ToDoHandler that returns the current todo items as a string:

ToDoHandler>>list
<get>

^ String streamContents: [ :stream |
ToDoList default items do: [ :each |
stream nextPutAll: each title; crlf ] ]

The important thing here is the method annotation <get>, the name of the method itself does not matter. The annotation declares that the method is associated with any GET request the service receives. Later on we will see how to define handlers for other types of requests.

In a web browser enter the URL http://localhost:8080/todo-api. You should get a file containing the list of existing todo items of your applications. If the file is empty verify that you have some todos on your application by trying it at http://localhost:8080/todo. In case of problems, verify that the server is working using the Seaside Control Panel. If everything works well you should obtain a page with the list of todo items. To verify that our service works as expected we can also use cURL or any other HTTP client to inspect the response:

$ curl -i curl -i http://localhost:8080/todo-api
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 71
Date: Sun, 20 Nov 2011 17:04:52 GMT
Server: Zinc HTTP Components 1.0

Finish todo app chapter
Annotate first chapter
Discuss cover design

By default Seaside tries to convert whatever the method returns into a response. In our initial example this was enough, but in many cases we want more control over how the response is built. We gain full control by asking the request context to respond with a custom response. The following re-implementation of the list method has the same behavior as the previous one, but creates the response manually.

ToDoHandler>>list
<get>

self requestContext respond: [ :response |
ToDoList default items do: [ :each |
response contentType: 'text/plain'.
response
nextPutAll: each title;
nextPutAll: String crlf ] ]

Copyright © 19 March 2024 Stéphane Ducasse, Lukas Renggli, C. David Shaffer, Rick Zaccone
This book is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 license.

This book is published using Seaside, Magritte and the Pier book publishing engine.