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 use base 'Catalyst::Controller::REST';
83 Catalyst::Controller::REST will automatically serialize your
84 responses, and deserialize any POST, PUT or OPTIONS requests. It evaluates
85 which serializer to use by mapping a content-type to a Serialization module.
86 We select the content-type based on:
90 =item B<The Content-Type Header>
92 If the incoming HTTP Request had a Content-Type header set, we will use it.
94 =item B<The content-type Query Parameter>
96 If this is a GET request, you can supply a content-type query parameter.
98 =item B<Evaluating the Accept Header>
100 Finally, if the client provided an Accept header, we will evaluate
101 it and use the best-ranked choice.
105 =head1 AVAILABLE SERIALIZERS
107 A given serialization mechanism is only available if you have the underlying
108 modules installed. For example, you can't use XML::Simple if it's not already
111 In addition, each serializer has it's quirks in terms of what sorts of data
112 structures it will properly handle. L<Catalyst::Controller::REST> makes
113 no attempt to save you from yourself in this regard. :)
117 =item C<text/x-yaml> => C<YAML::Syck>
119 Returns YAML generated by L<YAML::Syck>.
121 =item C<text/html> => C<YAML::HTML>
123 This uses L<YAML::Syck> and L<URI::Find> to generate YAML with all URLs turned
124 to hyperlinks. Only useable for Serialization.
126 =item C<application/json> => C<JSON>
128 Uses L<JSON> to generate JSON output. It is strongly advised to also have
129 L<JSON::XS> installed. The C<text/x-json> content type is supported but is
130 deprecated and you will receive warnings in your log.
132 =item C<text/x-data-dumper> => C<Data::Serializer>
134 Uses the L<Data::Serializer> module to generate L<Data::Dumper> output.
136 =item C<text/x-data-denter> => C<Data::Serializer>
138 Uses the L<Data::Serializer> module to generate L<Data::Denter> output.
140 =item C<text/x-data-taxi> => C<Data::Serializer>
142 Uses the L<Data::Serializer> module to generate L<Data::Taxi> output.
144 =item C<application/x-storable> => C<Data::Serializer>
146 Uses the L<Data::Serializer> module to generate L<Storable> output.
148 =item C<application/x-freezethaw> => C<Data::Serializer>
150 Uses the L<Data::Serializer> module to generate L<FreezeThaw> output.
152 =item C<text/x-config-general> => C<Data::Serializer>
154 Uses the L<Data::Serializer> module to generate L<Config::General> output.
156 =item C<text/x-php-serialization> => C<Data::Serializer>
158 Uses the L<Data::Serializer> module to generate L<PHP::Serialization> output.
160 =item C<text/xml> => C<XML::Simple>
162 Uses L<XML::Simple> to generate XML output. This is probably not suitable
163 for any real heavy XML work. Due to L<XML::Simple>s requirement that the data
164 you serialize be a HASHREF, we transform outgoing data to be in the form of:
166 { data => $yourdata }
170 Uses a regular Catalyst view. For example, if you wanted to have your
171 C<text/html> and C<text/xml> views rendered by TT:
173 'text/html' => [ 'View', 'TT' ],
174 'text/xml' => [ 'View', 'XML' ],
176 Will do the trick nicely.
180 By default, L<Catalyst::Controller::REST> will return a C<415 Unsupported Media Type>
181 response if an attempt to use an unsupported content-type is made. You
182 can ensure that something is always returned by setting the C<default>
185 __PACKAGE__->config->{'default'} = 'text/x-yaml';
187 Would make it always fall back to the serializer plugin defined for text/x-yaml.
189 Implementing new Serialization formats is easy! Contributions
190 are most welcome! See L<Catalyst::Action::Serialize> and
191 L<Catalyst::Action::Deserialize> for more information.
193 =head1 CUSTOM SERIALIZERS
195 If you would like to implement a custom serializer, you should create two new
196 modules in the L<Catalyst::Action::Serialize> and
197 L<Catalyst::Action::Deserialize> namespace. Then assign your new class
198 to the content-type's you want, and you're done.
200 =head1 STATUS HELPERS
202 Since so much of REST is in using HTTP, we provide these Status Helpers.
203 Using them will ensure that you are responding with the proper codes,
204 headers, and entities.
206 These helpers try and conform to the HTTP 1.1 Specification. You can
207 refer to it at: L<http://www.w3.org/Protocols/rfc2616/rfc2616.txt>.
208 These routines are all implemented as regular subroutines, and as
209 such require you pass the current context ($c) as the first argument.
215 use base 'Catalyst::Controller';
216 use Params::Validate qw(SCALAR OBJECT);
218 __PACKAGE__->mk_accessors(qw(serialize));
221 'stash_key' => 'rest',
223 'text/html' => 'YAML::HTML',
224 'text/xml' => 'XML::Simple',
225 'text/x-yaml' => 'YAML',
226 'application/json' => 'JSON',
227 'text/x-json' => 'JSON',
228 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
229 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
230 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
231 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
232 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
233 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
234 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
238 sub begin : ActionClass('Deserialize') { }
240 sub end : ActionClass('Serialize') { }
244 Returns a "200 OK" response. Takes an "entity" to serialize.
251 radiohead => "Is a good band!",
260 my %p = Params::Validate::validate( @_, { entity => 1, }, );
262 $c->response->status(200);
263 $self->_set_entity( $c, $p{'entity'} );
269 Returns a "201 CREATED" response. Takes an "entity" to serialize,
270 and a "location" where the created object can be found.
274 $self->status_created(
276 location => $c->req->uri->as_string,
278 radiohead => "Is a good band!",
282 In the above example, we use the requested URI as our location.
283 This is probably what you want for most PUT requests.
290 my %p = Params::Validate::validate(
293 location => { type => SCALAR | OBJECT },
294 entity => { optional => 1 },
299 if ( ref( $p{'location'} ) ) {
300 $location = $p{'location'}->as_string;
302 $location = $p{'location'};
304 $c->response->status(201);
305 $c->response->header( 'Location' => $location );
306 $self->_set_entity( $c, $p{'entity'} );
310 =item status_accepted
312 Returns a "202 ACCEPTED" response. Takes an "entity" to serialize.
316 $self->status_accepted(
325 sub status_accepted {
328 my %p = Params::Validate::validate( @_, { entity => 1, }, );
330 $c->response->status(202);
331 $self->_set_entity( $c, $p{'entity'} );
335 =item status_no_content
337 Returns a "204 NO CONTENT" response.
341 sub status_no_content {
344 $c->response->status(204);
345 $self->_set_entity( $c, undef );
349 =item status_bad_request
351 Returns a "400 BAD REQUEST" response. Takes a "message" argument
352 as a scalar, which will become the value of "error" in the serialized
357 $self->status_bad_request(
359 message => "Cannot do what you have asked!",
364 sub status_bad_request {
367 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
369 $c->response->status(400);
370 $c->log->debug( "Status Bad Request: " . $p{'message'} ) if $c->debug;
371 $self->_set_entity( $c, { error => $p{'message'} } );
375 =item status_not_found
377 Returns a "404 NOT FOUND" response. Takes a "message" argument
378 as a scalar, which will become the value of "error" in the serialized
383 $self->status_not_found(
385 message => "Cannot find what you were looking for!",
390 sub status_not_found {
393 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
395 $c->response->status(404);
396 $c->log->debug( "Status Not Found: " . $p{'message'} ) if $c->debug;
397 $self->_set_entity( $c, { error => $p{'message'} } );
403 Returns a "41O GONE" response. Takes a "message" argument as a scalar,
404 which will become the value of "error" in the serialized response.
410 message => "The document have been deleted by foo",
418 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
420 $c->response->status(410);
421 $c->log->debug( "Status Gone " . $p{'message'} ) if $c->debug;
422 $self->_set_entity( $c, { error => $p{'message'} } );
430 if ( defined($entity) ) {
431 $c->stash->{ $self->{'stash_key'} } = $entity;
438 =head1 MANUAL RESPONSES
440 If you want to construct your responses yourself, all you need to
441 do is put the object you want serialized in $c->stash->{'rest'}.
443 =head1 IMPLEMENTATION DETAILS
445 This Controller ties together L<Catalyst::Action::REST>,
446 L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>. It should be suitable for most applications. You should be aware that it:
450 =item Configures the Serialization Actions
452 This class provides a default configuration for Serialization. It is currently:
456 'stash_key' => 'rest',
458 'text/html' => 'YAML::HTML',
459 'text/xml' => 'XML::Simple',
460 'text/x-yaml' => 'YAML',
461 'application/json' => 'JSON',
462 'text/x-json' => 'JSON',
463 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
464 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
465 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
466 'application/x-storable' => [ 'Data::Serializer', 'Storable'
468 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw'
470 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ]
472 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
477 You can read the full set of options for this configuration block in
478 L<Catalyst::Action::Serialize>.
480 =item Sets a C<begin> and C<end> method for you
482 The C<begin> method uses L<Catalyst::Action::Deserialize>. The C<end>
483 method uses L<Catalyst::Action::Serialize>. If you want to override
484 either behavior, simply implement your own C<begin> and C<end> actions
487 my Foo::Controller::Monkey;
488 use base qw(Catalyst::Controller::REST);
492 ... do things before Deserializing ...
493 $self->maybe::next::method($c);
494 ... do things after Deserializing ...
499 ... do things before Serializing ...
500 $self->maybe::next::method($c);
501 ... do things after Serializing ...
506 =head1 A MILD WARNING
508 I have code in production using L<Catalyst::Controller::REST>. That said,
509 it is still under development, and it's possible that things may change
510 between releases. I promise to not break things unneccesarily. :)
514 L<Catalyst::Action::REST>, L<Catalyst::Action::Serialize>,
515 L<Catalyst::Action::Deserialize>
517 For help with REST in general:
519 The HTTP 1.1 Spec is required reading. http://www.w3.org/Protocols/rfc2616/rfc2616.txt
521 Wikipedia! http://en.wikipedia.org/wiki/Representational_State_Transfer
523 The REST Wiki: http://rest.blueoxen.net/cgi-bin/wiki.pl?FrontPage
527 Adam Jacob <adam@stalecoffee.org>, with lots of help from mst and jrockway
529 Marchex, Inc. paid me while I developed this module. (http://www.marchex.com)
533 J. Shirley <jshirley@cpan.org>
537 You may distribute this code under the same terms as Perl itself.