Creating a Web Service Using Perl

I need to create a server application (a tiny web service) for testing. What are the CPAN modules and Perl libraries for this task?

+5
source share
4 answers

There are many possibilities

  • CGI - if you like to do everything as in the old days
  • CGI::Application - a bit more advanced

or you can use frameworks like

  • Catalyst
  • Dancer
  • Mojolicious

It depends on your skills and goals, which decision you should choose.

+4
source

The web service simply returns an HTTP status code and some data, possibly serialized in JSON or XML. You can use a module for this CGI, for example:

#!/usr/bin/perl -w

use strict;
use warnings;
use CGI;
use CGI::Pretty qw/:standard/;
use URI::Escape;

my $query = CGI->new;
my $jsonQueryValue = uri_unescape $query->param('helloWorld'); 

#  let say that 'helloWorld' is a uri_escape()-ed POST variable 
#  that contains the JSON object { 'hello' : 'world' }

print header(-type => "application/json", -status => "200 OK");
print "$jsonQueryValue";

, , HTTP- . , - 404, , , . .

+5

Testing a tiny web service with Plack :: Test :

use Plack::Test;
use Test::More;
test_psgi(
    app => sub {
        my ($env) = @_;
        return [200, ['Content-Type' => 'text/plain'], ["Hello World"]],
    },
    client => sub {
        my ($cb) = @_;
        my $req  = HTTP::Request->new(GET => "http://localhost/hello");
        my $res  = $cb->($req);
        like $res->content, qr/Hello World/;
    },
);
done_testing;
+4
source

I like to use mojolicious . At first it is light and can also be heavy lifting. Mojolicious :: Lite is especially good for fast and dirty.

  use Mojolicious::Lite;

  # Route with placeholder
  get '/:foo' => sub {
    my $self = shift;
    my $foo  = $self->param('foo');
    $self->render(text => "Hello from $foo.");
  };

  # Start the Mojolicious command system
  app->start;
+2
source

All Articles