Making RESTful Dancing easy with Dancer::Plugin::REST
An useful plugin for writing RESTful Dancer web applications is Dancer::Plugin::Rest by Alexis Sukrieh, available at https://metacpan.org/module/Dancer::Plugin::REST.
To use it when defining routes, easily:
package MyApp;
use Dancer;
use Dancer::Plugin::REST;
This exports the resource keyword, which can be used as such:
resource camel => (
create => sub {},
get => sub {},
update => sub {},
delete => sub {},
);
This automatically creates the following route handlers:
- post /camel (create)
- post /camel.:format (create)
- get /camel/:id (read)
- get /camel/:id.:format (read)
- put /camel/:id (update)
- put /camel/:id.:format (update)
- del /camel/:id (delete)
- del /camel/:id.:format (delete)
The format param can be used in requests such as
GET /camel/larry.xml
Next to that, this module exports a whole bunch of error handler methods, such as
- status_unauthorized
- status_ok
- status_length_required
- status_not_found
- status_forbidden
which can be used to make life easier:
return status_unauthorized("Not Larry") unless $user->is_larry;
If the code of the status you are using is equal or higher than 100, your error message will be the value of key 'error' ( { error => "Not Larry" } ) - otherwise it's just a verbatim. Of course it's expected that since you're working with REST, you're serialising your return values.
Some nitpicks:
- "get" should be called "read" for CRUD (create read update delete)
- The POD is incorrect.
I earlier issued a pull request of a fork where I update the POD problem and renamed "get" to "read" as well as swapping the meaning of POST and PUT. I believed PUT should be CREATE, and POST update, even though this later proved to be incorrect. I hope the changes to POD will however be added. It's trivial, but correct.
Closing words
This is one of those nifty little modules that makes writing a RESTful webapp just that little bit easier and makes your code more organised. I can recommend it!
Leave a comment