Techumber
Home Blog Work

Create Restful Services Using Perl Dancer

Published on August 24, 2014

The Web is changing. Applications are becoming service centric. Once we created these services we can use them from any ware and any devices. Since We have so many devices available in market Services oriented approach is the best thing to do right now so we can use them later on when we develop an application for the specific device.

Download

When it comes to Services, REST(Representational State Transfer) become the best architecture for developing web services and APIs. In REST there are no sessions. That means no client-server relationship. That’s way in REST each request will contain all necessary information to send and receive data from server and client. Basically, in REST we take the advantage of HTTP Request methods. Though there are several request methods, we mostly use the following only.

POST- Create request to the server PUT -Update request to the server GET - Read requests to the server DELETE - Delete request to the server

Hello API !!!

I just want to give a small introduction to the API(Application Program Interface). In API we will be having publicly exposed methods were logic is abstracted. Seems like an oops concept right? For example, if you want to get users data from database then you will create an API with function getUserData where you will writing all your logic and your database information. But, You won’t expose any of them you will just give the getUserData function wrapping into a package. For programming language like java, Perl, etc. We will create packages and distribute them. But when it come to Web API, We will create service end points. Where these end points will be showed in a specific domain ex**(api.mydomain.com**).

Setup Stage:-

Now, We need a stage to Dance. In order to create Perl Dancer application first, we need to install few thing and make our development environment ready. I’m using window7 as my operating system. So, I will explain things based on it. If you using any other operating system the installation process may vary a little. 1)Perl: By default, windows don’t come with Perl so we have installed it. In windows, we have so many ways to install it but will use ActivePerl for now. Download and install ActivePerl from //www.activestate.com/activeperl 2)Perl Dancer: Once you install ActivePerl , open you command prompt and type following command in it.

ppm install Dancer

or you can use ActivePerl GUI also to do that just type ppm in your command prompt and press enter. 3) Plack: Thought, Perl Dancer have its own build in the server we won’t use it since it’s not suitable for deployment. Instead of that, we will use Perl web servers like Starman, Twiggy or Corona. In order to use them, we need Plack. To install Plack open your command prompt and type following .

ppm install Plack.

4)DBI: Finally, to interact with any Database we need this. To install

ppm install DBI

The stage is ready now. Let’s start the party.

Began Dance:

Let’s start creating a simple application using Perl Dancer. First of all, we need to create a directory structure. TU-API TU API.pm app.psgi

app.psgi

use Plack::Builder;
use Dancer;#
Dancer config
my $app = sub {
    setting appdir => '/TU';
    setting apphandler => 'PSGI';
    load_app "TU::API";
    Dancer::App - > set_running_app("TU::API");
    my $env = shift;
    Dancer::Handler - > init_request_headers($env);
    my $req = Dancer::Request - > new(env => $env);
    Dancer - > dance($req);
};#
Starman config
builder {
    mount "/" => builder {
        $app
    };

};

This code is for Starman server configurations and . In $app subroutine we have all settings for Dancer app. If you need anything else you can add them here. For full list of configurations please check //search.cpan.org/~xsawyerx/Dancer-1.3110/lib/Dancer/Config.pm

APP.pm

package MAP::API;
use Dancer;
use DBI;
get '/' => sub {
    return "hi";
};
1;

In Perl, we use package keyword to create packages. pm represents Perl module. Every Perl module has to return a true value at the end so we put 1; at the end of the file.

Running the Dancer

Now, our dancer has to run. To do that just got the folder path where you app.psgi located and type

plackup

(make sure you have installed plack) If you open your browser and got to //localhost:5000/ then you should get “hi” on the screen.

Dance with Database

Now, let’s make our app a little complex. For of all, I’m using SQL Server as my database. If you don’t have any download and install SQL server express from //msdn.microsoft.com/en-in/evalcenter/dn434042.aspx or you can use MySQL also if you want but you need to do some changes to database connection string, as well as you, need to do migration changes for the data dump. Once you have fire up your SQL server management studio and open SQL file inside DB folder from above download and execute it. Don’t forget to change your database by default it will be selected to the master database. If everything works fine you have your DB ready. Let’s go back to your API.pm and add the code

APP.pm

package MAP::API;
use Dancer;
use DBI;
get '/country' => sub {
    my $database = "TU";
    my $user = "sa";
    my $passwd = "abc123";
    my $server = ".\\DIMPU";
    my $dbh = DBI - > connect("DBI:ODBC:Driver={SQL Server};Server=$server;Database=$database;UID=$user;PWD=$passwd");
    my@ rows;
    my $sql_str = "select *from Country";
    my $sth = $dbh - > prepare($sql_str);
    $sth - > execute();
    while (my $record = $sth - > fetchrow_hashref()) {
        push@ rows, $record;
    }
    set serializer => 'JSON';
    return {
        data => [@rows],
            status => 'success',
            response => 'Succcess'
    };
};
1;

In this, we use DBI::ODBC to connect to the SQL Server database. By default, we making the output as JSON format. Now , restart the server by pressing ctrl+c and type pluckup. Go //localhost:5000/country you will get all countries DB as JSON format.

Dance formats:

Perl Dancer supports different output formats like JSON,XML,YAML. In order to change output format we have to use set serializer => ‘JSON’; this is a dancer setting. Now, let’s add a function set_format which sets an output format based on extinction. By default, it will be JSON.

sub set_format {
    my $format = shift;
    if (defined($format)) {
        if ($format eq "json") {
            set serializer => 'JSON';
        }
        elsif($format eq "xml") {
            set serializer => 'XML';
        }
        elsif($format eq "yaml") {
            set serializer => 'YAML';
        } else {
            set serializer => 'JSON';
        }
    } else {
        set serializer => 'JSON';
    }
}

Final Code:

package MAP::API;
use Dancer;
use DBI;#
localhost: 5000 / country.json
get '/country.:format' => sub {
    my $format = param('format');
    my $database = "TU";
    my $user = "sa";
    my $passwd = "abc123";
    my $server = ".\\DIMPU";#
    connect to database
    my $dbh = DBI - > connect("DBI:ODBC:Driver={SQL Server};Server=$server;Database=$database;UID=$user;PWD=$passwd");

    my@ rows;
    my $sql_str = "select *from Country";
    my $sth = $dbh - > prepare($sql_str);
    $sth - > execute();
    while (my $record = $sth - > fetchrow_hashref()) {
        push@ rows, $record;
    }
    set_format($format);
    return {
        data => [@rows],
            status => 'success',
            response => 'Succcess'
    };
};#
setting output format based on extenction
sub set_format {
    my $format = shift;
    if (defined($format)) {
        if ($format eq "json") {
            set serializer => 'JSON';
        }
        elsif($format eq "xml") {
            set serializer => 'XML';
        }
        elsif($format eq "yaml") {
            set serializer => 'YAML';
        } else {
            set serializer => 'JSON';
        }
    } else {
        set serializer => 'JSON';
    }
}
1;

Final Test

To check how our app works just got to //localhost:5000/country.json and now change JSON with XML,YAML to see how it will render the output.