Introduction
Recently RESTful web services have been popular among developers, so I decided to make a basic implementation in perl to show you how easy is to create them in perl.
Prerequisites
The only requisite before starting is to have installed a Perl distribution. I recomment to install Active Perl from http://www.activestate.com/activeperl/downloads
which I consider a good perl distribution if you are a beginner with perl.
Installing Dancer
Once we have installed Perl in our computer we will need to install the Dancer module using the tool
Perl Package Manager which comes with the active perl distribution.
Time to code
Now it's time to have some fun and write some lines to create the service.
Methods
For this example I wrote three methods to explain the basic usage of the Dancer framework. They show how to create Get methods to display information.
First Method:
Description: Greets guest users with a message "First rest Web Service with perl and dancer"
Access: http://server:port
Second Method:
Description: Greet an specific user provided in the URL.
Access: http://server:port/users/user name
Third Method:
Description: Prints a list of fake users in the system.
Access: http://server:port/users.
use Dancer;
set serializer => 'XML';
#set serializer => 'JSON'; #un-comment this for json format responses
get '/' => sub{
return {message => "First rest Web Service with Perl and Dancer"};
};
get '/users/:name' => sub {
my $user = params->{name};
return {message => "Hello $user"};
};
get '/users' => sub{
my %users = (
userA => {
id => "1",
name => "Carlos",
},
userB => {
id => "2",
name => "Andres",
},
userC => {
id => "3",
name => "Bryan",
},
);
return \%users;
};
dance;
Running the code:
Once we have written the previous code it's time to run our code by typing "perl file.pl" in a command line.
Conclusion
Writing things with Perl and Dancer is dead easy, why don't you give it a try?