[Catalyst] RESTful example apps?

Gabriel Andrade gabiruh at gmail.com
Thu Sep 15 18:22:11 GMT 2011


On Sep 15, 2011, at 9:53 AM, <Ian.Docherty at nomura.com> <Ian.Docherty at nomura.com> wrote:

> 
> package MyApp::Web::Controller::Rest;
> use Moose;
> use Readonly;
> 
> BEGIN {
>    extends 'Catalyst::Controller::REST';
> }
> my $base_url = '/rest';
> 
> Readonly::Scalar our $HTTP__OK                              => 200;
> Readonly::Scalar our $HTTP__BAD_REQUEST                     => 400;
> Readonly::Scalar our $HTTP__FORBIDDEN                       => 403;
> Readonly::Scalar our $HTTP__NOT_FOUND                       => 404;
> 
> sub foo : Local : ActionClass('REST::ForBrowsers') {}
> 
> *status_GET_foo = \&foo_GET;
> sub foo_GET : Private {
>    my ($self, $c) = @_;
> 
>    # Response
>    my $response = {
>        message     => 'hello world',
>        bar         => 123,
>    };
> 
>    $c->stash->{rest} = $response;
>    $c->response->status($HTTP__OK);
> }

Catalyst::Controller::REST already provides a set of helpers so you don't have to arbitrarily mess up with the status codes and end up breaking the REST architecture specs.

This would suffice:

  package My::Controller::Foo;
  use Moose;
  use namespace::autoclean;

  BEGIN { extends 'Catalyst::Controller::REST' }

  sub bar : Local : Args(1) : ActionClass('REST') {
  }

  sub bar_GET {
    my ( $self, $c, $some ) = @_;
    $self->status_ok( $c,
      entity => { bar => $c->model('LotsOfBars')->get($some)->as_hashref } );
  }

  sub bar_POST {
    my ( $self, $c ) = @_;
    $self->status_bad_request( $c, message => "Sorry?" );
  }


Catalyst::Controller::REST properly serializes the response based on request's Content-Type.

So, with jQuery, for example, you can do something like:

  $.getJSON('http://awesome.com/foo/bar/9', function(data){ messUpWith(data.bar) })

And get a "bar" object decoded from the JSON response.








More information about the Catalyst mailing list