A Simple HTTP Application

As a pretext to revisit Pharo Syntax

Damien Cassou, Stéphane Ducasse and Luc Fabresse http://stephane.ducasse.free.fr

A Tiny Book Server

Getting a Book

ZnClient new
  url: 'http://localhost:8181/books/1';
  get

Adding a Book

ZnClient new
  url: 'http://localhost:8181/books/1';
  formAt: 'author' put: 'van Caekenberghe et al';
  formAt: 'title'  put: 'Entreprise Pharo';
  post

formAt: 'author' put: 'van Caekenberghe et al'

is equivalent to

formAtput('author' , 'van Caekenberghe et al')

The Full Server

books := Dictionary new.
teapot := Teapot configure: { 
    #defaultOutput -> #json. #port -> 8181 }.
teapot
 GET: '/' -> '<h1>A simple book server</h1>'; output: #html;
 GET: '/books' -> books;
 GET: '/books/<id:IsInteger>' 
   -> [ :request | books at: (request at: #id) asString];
 POST: '/books/<id>' 
   -> [ :request | | book |
          book := { 'author' -> (request at: #author). 
          'title'  -> (request at: #title) } asDictionary.
          books at: (request at: #id) put: book ];   
 start.

Configuring a Server

  | books teapot |
  books := Dictionary new.
  teapot := Teapot configure: {  #defaultOutput -> #json.   #port -> 8181 . #debugMode -> true }.

Defining The Server Routes

teapot
 GET: '/' 
   -> '<h1>A simple book server</h1>'; output: #html;
 GET: '/books' 
   -> books;
 GET: '/books/<id:IsInteger>' 
   -> [ :request | books at: (request at: #id) asString];
 POST: '/books/<id>' 
   -> [ :request | | book |
      book := { 'author' -> (request at: #author) . 
        'title' -> (request at: #title) } asDictionary.
      books at: (request at: #id) put: book ];   
 start.

More About Syntax

Processing URIs such as: http://localhost:8181/books/1

teapot 
 GET: '/books/<id:IsInteger>'
   -> [ :request | books at: (request at: #id) asString];

Conclusion

/