Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement a RESTful API in Perl?

Tags:

rest

perl

I'm trying to implement a RESTful API in Perl. My current idea is to simply parse the path_info with a regex then dispatch the request to the appropriate subroutine which will then spit out the JSON, XML or even XHTML for the requested resource.

For example to retrieve info about user 1234 the RESTful client should find it at:

http://example.com/model.pl/users/1234

Below is the skeleton code of my first attempt at implementing a RESTful API:

model.pl :

#!/usr/bin/perl -w
use strict;
use CGI;

my $q = CGI->new();

print $q->header('text/html');

my $restfuluri  = $q->path_info;

if      ($restfuluri =~ /^\/(questions)\/([1-9]+$)/) { questions($1, $2); }
elsif   ($restfuluri =~ /^\/(users)\/([1-9]+$)/)     { users($1, $2); }


sub questions
{
      my $object = shift;
      my $value  = shift;

      #This is a stub, spits out JSON or XML when implemented.
      print $q->p("GET question : $object -> $value");
}

sub users
{
      my $object = shift;
      my $value  = shift;

      #This is a stub, spits out JSON or XML when implemented.
      print $q->p("GET user: $object -> $value");
}

Before I proceed any further, I would like to hear from experienced Perl hackers whether I got the basic idea right and if there are any serious shortcomings with this approach in terms of performance.

I can imagine, after a while, the if/else block would grow really large.

Looking forward to hear your views to make this code better.

like image 547
GeneQ Avatar asked Aug 11 '09 08:08

GeneQ


People also ask

What language is used to make RESTful API?

XML: JSON and XML are the two de facto standards for sending and receiving data in REST APIs. Web programming languages such as Python, JavaScript, Ruby on Rails, and Java all have tools for parsing and working with XML and JSON.


2 Answers

For lightweight REST APIs I would look at Mojolicious. The request routing is really straightforward and the inbuilt JSON renderer and user agent make development of simple REST APIs very straightforward in my experience.

If your app is going to be relatively small then Mojo::Lite may suit your requirements. For example you may be able to do something like this:

use Mojolicious::Lite;

get '/questions/(:question_id)' => sub {
    my $self = shift;
    my $result = {};
    # do stuff with $result based on $self->stash('question_id')
    return $self->render_json($result)
}

app->start;
like image 164
robert_b_clarke Avatar answered Oct 01 '22 03:10

robert_b_clarke


The simple solution:

 use CGI;

 my $page  = new CGI;

 if( $ENV{ 'REQUEST_METHOD' } eq 'GET' ){

    my $data = <<json;
    {
    "isbn" : "123456",
    "title" : "Programming Perl",
    "author" : "L. Wall"
     }
 json

     print $page->header('application/json');

     print $data;
 }
like image 40
Gerd Avatar answered Oct 01 '22 01:10

Gerd