This part will give you a quick start into programming with liberator.
Liberator is available from clojars. Add liberator to your project.clj as
For the tutorial we’ll use ring-core, ring-jetty-adapter and compojure. For a fast setup, we’ll use lein:
Add dependencies to project.clj:
src/liberator_tutorial/core.clj where we define our first resource:
lein ring server and jetty will be started on port 3000. However,
the result of pointing your browser is somewhat disappointing:
“No acceptable resource available”. To get a more exciting result we simply must
declare which kind of media type we are able to offer, e.g.
“text/html” and set a handler for the status
So change the definition as follows:
The result is promising but we likely want to return something more dynamic. For this we declare a handler function that will be invoked for the http status code 200 “OK”. As you can see, liberator accepts either values or functions that take the context as the only argument.
Make sure that you actually provide a function and not a value:
This looks well but handle-ok will be set to a value which was computed
when the function
resource was called, not when the request was
processed. The correct solution is:
Until now we used the function
resource to create a ring
handler for the resources. It is natural that liberator also provides
a macro to bind the resource function to a var:
Liberator also supports so-called parametrized resources. These are handler factories that close over some bindings and match perfectly with compojure’s routing parameters:
Processing GET was easy, wasn’t it? Now let’s try a different HTTP method, say “PUT”:
Woohoo! Exactly what I’d expect. But how did liberator determine that it must send a 405 status? It uses a graph of decisions which is described in the next part: Decision graph.