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 Catalyst::Controller::REST will automatically serialize your
89 responses, and deserialize any POST, PUT or OPTIONS requests. It evaluates
90 which serializer to use by mapping a content-type to a Serialization module.
91 We select the content-type based on:
95 =item B<The Content-Type Header>
97 If the incoming HTTP Request had a Content-Type header set, we will use it.
99 =item B<The content-type Query Parameter>
101 If this is a GET request, you can supply a content-type query parameter.
103 =item B<Evaluating the Accept Header>
105 Finally, if the client provided an Accept header, we will evaluate
106 it and use the best-ranked choice.
111 =head1 AVAILABLE SERIALIZERS
113 A given serialization mechanism is only available if you have the underlying
114 modules installed. For example, you can't use XML::Simple if it's not already
117 In addition, each serializer has its quirks in terms of what sorts of data
118 structures it will properly handle. L<Catalyst::Controller::REST> makes
119 no attempt to save you from yourself in this regard. :)
123 =item * C<text/x-yaml> => C<YAML::Syck>
125 Returns YAML generated by L<YAML::Syck>.
127 =item * C<text/html> => C<YAML::HTML>
129 This uses L<YAML::Syck> and L<URI::Find> to generate YAML with all URLs turned
130 to hyperlinks. Only useable for Serialization.
132 =item * C<application/json> => C<JSON>
134 Uses L<JSON> to generate JSON output. It is strongly advised to also have
135 L<JSON::XS> installed. The C<text/x-json> content type is supported but is
136 deprecated and you will receive warnings in your log.
138 =item * C<text/x-data-dumper> => C<Data::Serializer>
140 Uses the L<Data::Serializer> module to generate L<Data::Dumper> output.
142 =item * C<text/x-data-denter> => C<Data::Serializer>
144 Uses the L<Data::Serializer> module to generate L<Data::Denter> output.
146 =item * C<text/x-data-taxi> => C<Data::Serializer>
148 Uses the L<Data::Serializer> module to generate L<Data::Taxi> output.
150 =item * C<application/x-storable> => C<Data::Serializer>
152 Uses the L<Data::Serializer> module to generate L<Storable> output.
154 =item * C<application/x-freezethaw> => C<Data::Serializer>
156 Uses the L<Data::Serializer> module to generate L<FreezeThaw> output.
158 =item * C<text/x-config-general> => C<Data::Serializer>
160 Uses the L<Data::Serializer> module to generate L<Config::General> output.
162 =item * C<text/x-php-serialization> => C<Data::Serializer>
164 Uses the L<Data::Serializer> module to generate L<PHP::Serialization> output.
166 =item * C<text/xml> => C<XML::Simple>
168 Uses L<XML::Simple> to generate XML output. This is probably not suitable
169 for any real heavy XML work. Due to L<XML::Simple>s requirement that the data
170 you serialize be a HASHREF, we transform outgoing data to be in the form of:
172 { data => $yourdata }
176 Uses a regular Catalyst view. For example, if you wanted to have your
177 C<text/html> and C<text/xml> views rendered by TT:
179 'text/html' => [ 'View', 'TT' ],
180 'text/xml' => [ 'View', 'XML' ],
182 Will do the trick nicely.
186 By default, L<Catalyst::Controller::REST> will return a
187 C<415 Unsupported Media Type> response if an attempt to use an unsupported
188 content-type is made. You can ensure that something is always returned by
189 setting the C<default> config option:
191 __PACKAGE__->config->{'default'} = 'text/x-yaml';
193 would make it always fall back to the serializer plugin defined for
196 =head1 CUSTOM SERIALIZERS
198 Implementing new Serialization formats is easy! Contributions
199 are most welcome! If you would like to implement a custom serializer,
200 you should create two new modules in the L<Catalyst::Action::Serialize>
201 and L<Catalyst::Action::Deserialize> namespace. Then assign your new
202 class to the content-type's you want, and you're done.
204 See L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>
205 for more information.
207 =head1 STATUS HELPERS
209 Since so much of REST is in using HTTP, we provide these Status Helpers.
210 Using them will ensure that you are responding with the proper codes,
211 headers, and entities.
213 These helpers try and conform to the HTTP 1.1 Specification. You can
214 refer to it at: L<http://www.w3.org/Protocols/rfc2616/rfc2616.txt>.
215 These routines are all implemented as regular subroutines, and as
216 such require you pass the current context ($c) as the first argument.
222 use base 'Catalyst::Controller';
223 use Params::Validate qw(SCALAR OBJECT);
225 __PACKAGE__->mk_accessors(qw(serialize));
228 'stash_key' => 'rest',
230 'text/html' => 'YAML::HTML',
231 'text/xml' => 'XML::Simple',
232 'text/x-yaml' => 'YAML',
233 'application/json' => 'JSON',
234 'text/x-json' => 'JSON',
235 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
236 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
237 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
238 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
239 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
240 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
241 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
245 sub begin : ActionClass('Deserialize') { }
247 sub end : ActionClass('Serialize') { }
251 Returns a "200 OK" response. Takes an "entity" to serialize.
258 radiohead => "Is a good band!",
267 my %p = Params::Validate::validate( @_, { entity => 1, }, );
269 $c->response->status(200);
270 $self->_set_entity( $c, $p{'entity'} );
276 Returns a "201 CREATED" response. Takes an "entity" to serialize,
277 and a "location" where the created object can be found.
281 $self->status_created(
283 location => $c->req->uri->as_string,
285 radiohead => "Is a good band!",
289 In the above example, we use the requested URI as our location.
290 This is probably what you want for most PUT requests.
297 my %p = Params::Validate::validate(
300 location => { type => SCALAR | OBJECT },
301 entity => { optional => 1 },
306 if ( ref( $p{'location'} ) ) {
307 $location = $p{'location'}->as_string;
309 $location = $p{'location'};
311 $c->response->status(201);
312 $c->response->header( 'Location' => $location );
313 $self->_set_entity( $c, $p{'entity'} );
317 =item status_accepted
319 Returns a "202 ACCEPTED" response. Takes an "entity" to serialize.
323 $self->status_accepted(
332 sub status_accepted {
335 my %p = Params::Validate::validate( @_, { entity => 1, }, );
337 $c->response->status(202);
338 $self->_set_entity( $c, $p{'entity'} );
342 =item status_no_content
344 Returns a "204 NO CONTENT" response.
348 sub status_no_content {
351 $c->response->status(204);
352 $self->_set_entity( $c, undef );
356 =item status_bad_request
358 Returns a "400 BAD REQUEST" response. Takes a "message" argument
359 as a scalar, which will become the value of "error" in the serialized
364 $self->status_bad_request(
366 message => "Cannot do what you have asked!",
371 sub status_bad_request {
374 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
376 $c->response->status(400);
377 $c->log->debug( "Status Bad Request: " . $p{'message'} ) if $c->debug;
378 $self->_set_entity( $c, { error => $p{'message'} } );
382 =item status_not_found
384 Returns a "404 NOT FOUND" response. Takes a "message" argument
385 as a scalar, which will become the value of "error" in the serialized
390 $self->status_not_found(
392 message => "Cannot find what you were looking for!",
397 sub status_not_found {
400 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
402 $c->response->status(404);
403 $c->log->debug( "Status Not Found: " . $p{'message'} ) if $c->debug;
404 $self->_set_entity( $c, { error => $p{'message'} } );
410 Returns a "41O GONE" response. Takes a "message" argument as a scalar,
411 which will become the value of "error" in the serialized response.
417 message => "The document have been deleted by foo",
425 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
427 $c->response->status(410);
428 $c->log->debug( "Status Gone " . $p{'message'} ) if $c->debug;
429 $self->_set_entity( $c, { error => $p{'message'} } );
437 if ( defined($entity) ) {
438 $c->stash->{ $self->{'stash_key'} } = $entity;
445 =head1 MANUAL RESPONSES
447 If you want to construct your responses yourself, all you need to
448 do is put the object you want serialized in $c->stash->{'rest'}.
450 =head1 IMPLEMENTATION DETAILS
452 This Controller ties together L<Catalyst::Action::REST>,
453 L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>. It should be suitable for most applications. You should be aware that it:
457 =item Configures the Serialization Actions
459 This class provides a default configuration for Serialization. It is currently:
462 'stash_key' => 'rest',
464 'text/html' => 'YAML::HTML',
465 'text/xml' => 'XML::Simple',
466 'text/x-yaml' => 'YAML',
467 'application/json' => 'JSON',
468 'text/x-json' => 'JSON',
469 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
470 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
471 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
472 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
473 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
474 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
475 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
479 You can read the full set of options for this configuration block in
480 L<Catalyst::Action::Serialize>.
482 =item Sets a C<begin> and C<end> method for you
484 The C<begin> method uses L<Catalyst::Action::Deserialize>. The C<end>
485 method uses L<Catalyst::Action::Serialize>. If you want to override
486 either behavior, simply implement your own C<begin> and C<end> actions
489 my Foo::Controller::Monkey;
490 use base qw(Catalyst::Controller::REST);
494 ... do things before Deserializing ...
495 $self->maybe::next::method($c);
496 ... do things after Deserializing ...
501 ... do things before Serializing ...
502 $self->maybe::next::method($c);
503 ... do things after Serializing ...
508 =head1 A MILD WARNING
510 I have code in production using L<Catalyst::Controller::REST>. That said,
511 it is still under development, and it's possible that things may change
512 between releases. I promise to not break things unneccesarily. :)
516 L<Catalyst::Action::REST>, L<Catalyst::Action::Serialize>,
517 L<Catalyst::Action::Deserialize>
519 For help with REST in general:
521 The HTTP 1.1 Spec is required reading. http://www.w3.org/Protocols/rfc2616/rfc2616.txt
523 Wikipedia! http://en.wikipedia.org/wiki/Representational_State_Transfer
525 The REST Wiki: http://rest.blueoxen.net/cgi-bin/wiki.pl?FrontPage
529 Adam Jacob <adam@stalecoffee.org>, with lots of help from mst and jrockway
531 Marchex, Inc. paid me while I developed this module. (http://www.marchex.com)
535 J. Shirley <jshirley@cpan.org>
539 You may distribute this code under the same terms as Perl itself.