How can I implement a RESTful API in Perl?

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;

I would use something like CGI::Application::Dispatch, it lets me build a dispatch table with variables and REST methods, and lets you use CGI and CGI::Application modules from CPAN. E.g.:

table => [
'/questions/:id[get]'    => { rm => 'get_question' },
'/users/:id[get]'        => { rm => 'get_user' }, # OR
':app/:id[post]'         => { rm => 'update' }, # where :app is your cgi application module
':app/:id[delete]'       => { rm => 'delete' },
],

(or you can use auto_rest or auto_rest_lc)

you can use a separate CGI::Application class for each type of thing (or just use classes in your cgi-app controller class methods).

CGI::Application also comes with plugins for outputting XML, JSON or text generated from templates.

cgi-app (and c::a::d) are are CGI applications and can be used with (little or) no change under CGI, FastCGI or mod_perl. C::A::D is also a mod_perl PerlHandler by default too.

Tags:

Rest

Perl