Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Perl

REST Service with Perl and Dancer

4.82/5 (4 votes)
12 Jul 2012CPOL1 min read 35.9K  
A simple REST service with Perl and the Dancer framework.

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.

Image 1

Image 2

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.

PHP
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.

Image 3

Image 4

Image 5

Image 6
 

Conclusion 

Writing things with Perl and Dancer is dead easy, why don't you give it a try? 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)