1 package Catalyst::Controller::REST;
6 $VERSION = eval $VERSION;
10 Catalyst::Controller::REST - A RESTful controller
14 package Foo::Controller::Bar;
16 use base 'Catalyst::Controller::REST';
18 sub thing : Local : ActionClass('REST') { }
20 # Answer GET requests to "thing"
22 my ( $self, $c ) = @_;
24 # Return a 200 OK, with the data in entity
25 # serialized in the body
30 foo => 'is real bar-y',
35 # Answer PUT requests to "thing"
42 Catalyst::Controller::REST implements a mechanism for building
43 RESTful services in Catalyst. It does this by extending the
44 normal Catalyst dispatch mechanism to allow for different
45 subroutines to be called based on the HTTP Method requested,
46 while also transparently handling all the serialization/deserialization for
49 This is probably best served by an example. In the above
50 controller, we have declared a Local Catalyst action on
51 "sub thing", and have used the ActionClass('REST').
53 Below, we have declared "thing_GET" and "thing_PUT". Any
54 GET requests to thing will be dispatched to "thing_GET",
55 while any PUT requests will be dispatched to "thing_PUT".
57 Any unimplemented HTTP methods will be met with a "405 Method Not Allowed"
58 response, automatically containing the proper list of available methods. You
59 can override this behavior through implementing a custom
60 C<thing_not_implemented> method.
62 If you do not provide an OPTIONS handler, we will respond to any OPTIONS
63 requests with a "200 OK", populating the Allowed header automatically.
65 Any data included in C<< $c->stash->{'rest'} >> will be serialized for you.
66 The serialization format will be selected based on the content-type
67 of the incoming request. It is probably easier to use the L<STATUS HELPERS>,
68 which are described below.
70 The HTTP POST, PUT, and OPTIONS methods will all automatically deserialize the
71 contents of $c->request->body based on the requests content-type header.
72 A list of understood serialization formats is below.
74 If we do not have (or cannot run) a serializer for a given content-type, a 415
75 "Unsupported Media Type" error is generated.
77 To make your Controller RESTful, simply have it
79 BEGIN {extends 'Catalyst::Controller::REST'; }
81 Or if you use pre-Moose Catalyst versions,
83 use parent 'Catalyst::Controller::REST';
88 See L<Catalyst::Action::Serialize/CONFIGURATION>. Note that the C<serialize>
89 key has been deprecated.
94 Catalyst::Controller::REST will automatically serialize your
95 responses, and deserialize any POST, PUT or OPTIONS requests. It evaluates
96 which serializer to use by mapping a content-type to a Serialization module.
97 We select the content-type based on:
101 =item B<The Content-Type Header>
103 If the incoming HTTP Request had a Content-Type header set, we will use it.
105 =item B<The content-type Query Parameter>
107 If this is a GET request, you can supply a content-type query parameter.
109 =item B<Evaluating the Accept Header>
111 Finally, if the client provided an Accept header, we will evaluate
112 it and use the best-ranked choice.
117 =head1 AVAILABLE SERIALIZERS
119 A given serialization mechanism is only available if you have the underlying
120 modules installed. For example, you can't use XML::Simple if it's not already
123 In addition, each serializer has its quirks in terms of what sorts of data
124 structures it will properly handle. L<Catalyst::Controller::REST> makes
125 no attempt to save you from yourself in this regard. :)
129 =item * C<text/x-yaml> => C<YAML::Syck>
131 Returns YAML generated by L<YAML::Syck>.
133 =item * C<text/html> => C<YAML::HTML>
135 This uses L<YAML::Syck> and L<URI::Find> to generate YAML with all URLs turned
136 to hyperlinks. Only useable for Serialization.
138 =item * C<application/json> => C<JSON>
140 Uses L<JSON> to generate JSON output. It is strongly advised to also have
141 L<JSON::XS> installed. The C<text/x-json> content type is supported but is
142 deprecated and you will receive warnings in your log.
144 =item * C<text/x-data-dumper> => C<Data::Serializer>
146 Uses the L<Data::Serializer> module to generate L<Data::Dumper> output.
148 =item * C<text/x-data-denter> => C<Data::Serializer>
150 Uses the L<Data::Serializer> module to generate L<Data::Denter> output.
152 =item * C<text/x-data-taxi> => C<Data::Serializer>
154 Uses the L<Data::Serializer> module to generate L<Data::Taxi> output.
156 =item * C<application/x-storable> => C<Data::Serializer>
158 Uses the L<Data::Serializer> module to generate L<Storable> output.
160 =item * C<application/x-freezethaw> => C<Data::Serializer>
162 Uses the L<Data::Serializer> module to generate L<FreezeThaw> output.
164 =item * C<text/x-config-general> => C<Data::Serializer>
166 Uses the L<Data::Serializer> module to generate L<Config::General> output.
168 =item * C<text/x-php-serialization> => C<Data::Serializer>
170 Uses the L<Data::Serializer> module to generate L<PHP::Serialization> output.
172 =item * C<text/xml> => C<XML::Simple>
174 Uses L<XML::Simple> to generate XML output. This is probably not suitable
175 for any real heavy XML work. Due to L<XML::Simple>s requirement that the data
176 you serialize be a HASHREF, we transform outgoing data to be in the form of:
178 { data => $yourdata }
182 Uses a regular Catalyst view. For example, if you wanted to have your
183 C<text/html> and C<text/xml> views rendered by TT, set:
187 'text/html' => [ 'View', 'TT' ],
188 'text/xml' => [ 'View', 'XML' ],
192 Your views should have a C<process> method like this:
195 my ( $self, $c, $stash_key ) = @_;
199 $output = $self->serialize( $c->stash->{$stash_key} );
203 $c->response->body( $output );
204 return 1; # important
208 my ( $self, $data ) = @_;
210 my $serialized = ... process $data here ...
218 By default, L<Catalyst::Controller::REST> will return a
219 C<415 Unsupported Media Type> response if an attempt to use an unsupported
220 content-type is made. You can ensure that something is always returned by
221 setting the C<default> config option:
223 __PACKAGE__->config->{'default'} = 'text/x-yaml';
225 would make it always fall back to the serializer plugin defined for
228 =head1 CUSTOM SERIALIZERS
230 Implementing new Serialization formats is easy! Contributions
231 are most welcome! If you would like to implement a custom serializer,
232 you should create two new modules in the L<Catalyst::Action::Serialize>
233 and L<Catalyst::Action::Deserialize> namespace. Then assign your new
234 class to the content-type's you want, and you're done.
236 See L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>
237 for more information.
239 =head1 STATUS HELPERS
241 Since so much of REST is in using HTTP, we provide these Status Helpers.
242 Using them will ensure that you are responding with the proper codes,
243 headers, and entities.
245 These helpers try and conform to the HTTP 1.1 Specification. You can
246 refer to it at: L<http://www.w3.org/Protocols/rfc2616/rfc2616.txt>.
247 These routines are all implemented as regular subroutines, and as
248 such require you pass the current context ($c) as the first argument.
254 use base 'Catalyst::Controller';
255 use Params::Validate qw(SCALAR OBJECT);
257 __PACKAGE__->mk_accessors(qw(serialize));
260 'stash_key' => 'rest',
262 'text/html' => 'YAML::HTML',
263 'text/xml' => 'XML::Simple',
264 'text/x-yaml' => 'YAML',
265 'application/json' => 'JSON',
266 'text/x-json' => 'JSON',
267 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
268 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
269 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
270 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
271 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
272 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
273 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
277 sub begin : ActionClass('Deserialize') { }
279 sub end : ActionClass('Serialize') { }
283 Returns a "200 OK" response. Takes an "entity" to serialize.
290 radiohead => "Is a good band!",
299 my %p = Params::Validate::validate( @_, { entity => 1, }, );
301 $c->response->status(200);
302 $self->_set_entity( $c, $p{'entity'} );
308 Returns a "201 CREATED" response. Takes an "entity" to serialize,
309 and a "location" where the created object can be found.
313 $self->status_created(
315 location => $c->req->uri->as_string,
317 radiohead => "Is a good band!",
321 In the above example, we use the requested URI as our location.
322 This is probably what you want for most PUT requests.
329 my %p = Params::Validate::validate(
332 location => { type => SCALAR | OBJECT },
333 entity => { optional => 1 },
338 if ( ref( $p{'location'} ) ) {
339 $location = $p{'location'}->as_string;
341 $location = $p{'location'};
343 $c->response->status(201);
344 $c->response->header( 'Location' => $location );
345 $self->_set_entity( $c, $p{'entity'} );
349 =item status_accepted
351 Returns a "202 ACCEPTED" response. Takes an "entity" to serialize.
355 $self->status_accepted(
364 sub status_accepted {
367 my %p = Params::Validate::validate( @_, { entity => 1, }, );
369 $c->response->status(202);
370 $self->_set_entity( $c, $p{'entity'} );
374 =item status_no_content
376 Returns a "204 NO CONTENT" response.
380 sub status_no_content {
383 $c->response->status(204);
384 $self->_set_entity( $c, undef );
388 =item status_bad_request
390 Returns a "400 BAD REQUEST" response. Takes a "message" argument
391 as a scalar, which will become the value of "error" in the serialized
396 $self->status_bad_request(
398 message => "Cannot do what you have asked!",
403 sub status_bad_request {
406 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
408 $c->response->status(400);
409 $c->log->debug( "Status Bad Request: " . $p{'message'} ) if $c->debug;
410 $self->_set_entity( $c, { error => $p{'message'} } );
414 =item status_not_found
416 Returns a "404 NOT FOUND" response. Takes a "message" argument
417 as a scalar, which will become the value of "error" in the serialized
422 $self->status_not_found(
424 message => "Cannot find what you were looking for!",
429 sub status_not_found {
432 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
434 $c->response->status(404);
435 $c->log->debug( "Status Not Found: " . $p{'message'} ) if $c->debug;
436 $self->_set_entity( $c, { error => $p{'message'} } );
442 Returns a "41O GONE" response. Takes a "message" argument as a scalar,
443 which will become the value of "error" in the serialized response.
449 message => "The document have been deleted by foo",
457 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
459 $c->response->status(410);
460 $c->log->debug( "Status Gone " . $p{'message'} ) if $c->debug;
461 $self->_set_entity( $c, { error => $p{'message'} } );
469 if ( defined($entity) ) {
470 $c->stash->{ $self->{'stash_key'} } = $entity;
477 =head1 MANUAL RESPONSES
479 If you want to construct your responses yourself, all you need to
480 do is put the object you want serialized in $c->stash->{'rest'}.
482 =head1 IMPLEMENTATION DETAILS
484 This Controller ties together L<Catalyst::Action::REST>,
485 L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>. It should be suitable for most applications. You should be aware that it:
489 =item Configures the Serialization Actions
491 This class provides a default configuration for Serialization. It is currently:
494 'stash_key' => 'rest',
496 'text/html' => 'YAML::HTML',
497 'text/xml' => 'XML::Simple',
498 'text/x-yaml' => 'YAML',
499 'application/json' => 'JSON',
500 'text/x-json' => 'JSON',
501 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
502 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
503 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
504 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
505 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
506 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
507 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
511 You can read the full set of options for this configuration block in
512 L<Catalyst::Action::Serialize>.
514 =item Sets a C<begin> and C<end> method for you
516 The C<begin> method uses L<Catalyst::Action::Deserialize>. The C<end>
517 method uses L<Catalyst::Action::Serialize>. If you want to override
518 either behavior, simply implement your own C<begin> and C<end> actions
521 my Foo::Controller::Monkey;
522 use base qw(Catalyst::Controller::REST);
526 ... do things before Deserializing ...
527 $self->maybe::next::method($c);
528 ... do things after Deserializing ...
533 ... do things before Serializing ...
534 $self->maybe::next::method($c);
535 ... do things after Serializing ...
540 =head1 A MILD WARNING
542 I have code in production using L<Catalyst::Controller::REST>. That said,
543 it is still under development, and it's possible that things may change
544 between releases. I promise to not break things unneccesarily. :)
548 L<Catalyst::Action::REST>, L<Catalyst::Action::Serialize>,
549 L<Catalyst::Action::Deserialize>
551 For help with REST in general:
553 The HTTP 1.1 Spec is required reading. http://www.w3.org/Protocols/rfc2616/rfc2616.txt
555 Wikipedia! http://en.wikipedia.org/wiki/Representational_State_Transfer
557 The REST Wiki: http://rest.blueoxen.net/cgi-bin/wiki.pl?FrontPage
561 Adam Jacob <adam@stalecoffee.org>, with lots of help from mst and jrockway
563 Marchex, Inc. paid me while I developed this module. (http://www.marchex.com)
567 J. Shirley <jshirley@cpan.org>
571 You may distribute this code under the same terms as Perl itself.