Search code examples
perlrestcgicgi-application

CGI::Application::Plugin::REST Instance Script


I am attempting to build a Restful service with CGI::Application::Plugin::REST, but I am not sure how to actually structure the script. Is it the same as using CGI::Application so the below will be the Instance Script referencing modules withing the Perl library path?

    use CGI::Application::Plugin::REST qw( :all );

$self->rest_route(
        '/Stage/:id'    => {
            'GET'    => 'Stage',
        },
        '/Status/:id'   => {
            'GET'    => 'Status',
        },
        '/Metadate/:id' => {
            'GET'    => 'Metadata',
        },
$self->run();

I will admit I am probably learning CGI::Application backwards, and am looking for an easy way out as once the framework is done the rest is very achievable. Also I did not want to use MVC frameworks as I wanted to build it from scratch. Thanks for the help in advance.


Solution

  • Since you said you want to use this as a structure to build off of, I'd recommend putting your CGI::App logic in its own module. This will make it easier to test later when you start writing tests. Your App.pm will look like a normal CGI::App controller:

    package App;
    
    use strict;
    use parent 'CGI::Application';
    use CGI::Application::Plugin::REST ':all';
    
    sub setup {
        my $self = shift;
        $self->rest_route(
            '/some/route' => {
                'GET' => 'read_widget',
                'POST' => 'save_widget',
            },
        );
    }
    
    sub read_widget { ... }
    sub save_widget { ... }
    1;
    

    And then in your instance script that the web server will call, you can simply use App; App->new->run;

    You can find a fully functioning example in the C::A::P::REST test lib.