1 package Catalyst::Controller::REST;
6 $VERSION = eval $VERSION;
10 Catalyst::Controller::REST - A RESTful controller
14 package Foo::Controller::Bar;
16 use namespace::autoclean;
18 BEGIN { extends 'Catalyst::Controller::REST' }
20 sub thing : Local : ActionClass('REST') { }
22 # Answer GET requests to "thing"
24 my ( $self, $c ) = @_;
26 # Return a 200 OK, with the data in entity
27 # serialized in the body
32 foo => 'is real bar-y',
37 # Answer PUT requests to "thing"
44 Catalyst::Controller::REST implements a mechanism for building
45 RESTful services in Catalyst. It does this by extending the
46 normal Catalyst dispatch mechanism to allow for different
47 subroutines to be called based on the HTTP Method requested,
48 while also transparently handling all the serialization/deserialization for
51 This is probably best served by an example. In the above
52 controller, we have declared a Local Catalyst action on
53 "sub thing", and have used the ActionClass('REST').
55 Below, we have declared "thing_GET" and "thing_PUT". Any
56 GET requests to thing will be dispatched to "thing_GET",
57 while any PUT requests will be dispatched to "thing_PUT".
59 Any unimplemented HTTP methods will be met with a "405 Method Not Allowed"
60 response, automatically containing the proper list of available methods. You
61 can override this behavior through implementing a custom
62 C<thing_not_implemented> method.
64 If you do not provide an OPTIONS handler, we will respond to any OPTIONS
65 requests with a "200 OK", populating the Allowed header automatically.
67 Any data included in C<< $c->stash->{'rest'} >> will be serialized for you.
68 The serialization format will be selected based on the content-type
69 of the incoming request. It is probably easier to use the L<STATUS HELPERS>,
70 which are described below.
72 The HTTP POST, PUT, and OPTIONS methods will all automatically deserialize the
73 contents of $c->request->body based on the requests content-type header.
74 A list of understood serialization formats is below.
76 If we do not have (or cannot run) a serializer for a given content-type, a 415
77 "Unsupported Media Type" error is generated.
79 To make your Controller RESTful, simply have it
81 BEGIN { extends 'Catalyst::Controller::REST' }
85 See L<Catalyst::Action::Serialize/CONFIGURATION>. Note that the C<serialize>
86 key has been deprecated.
90 Catalyst::Controller::REST will automatically serialize your
91 responses, and deserialize any POST, PUT or OPTIONS requests. It evaluates
92 which serializer to use by mapping a content-type to a Serialization module.
93 We select the content-type based on:
97 =item B<The Content-Type Header>
99 If the incoming HTTP Request had a Content-Type header set, we will use it.
101 =item B<The content-type Query Parameter>
103 If this is a GET request, you can supply a content-type query parameter.
105 =item B<Evaluating the Accept Header>
107 Finally, if the client provided an Accept header, we will evaluate
108 it and use the best-ranked choice.
112 =head1 AVAILABLE SERIALIZERS
114 A given serialization mechanism is only available if you have the underlying
115 modules installed. For example, you can't use XML::Simple if it's not already
118 In addition, each serializer has its quirks in terms of what sorts of data
119 structures it will properly handle. L<Catalyst::Controller::REST> makes
120 no attempt to save you from yourself in this regard. :)
124 =item * C<text/x-yaml> => C<YAML::Syck>
126 Returns YAML generated by L<YAML::Syck>.
128 =item * C<text/html> => C<YAML::HTML>
130 This uses L<YAML::Syck> and L<URI::Find> to generate YAML with all URLs turned
131 to hyperlinks. Only useable for Serialization.
133 =item * C<application/json> => C<JSON>
135 Uses L<JSON> to generate JSON output. It is strongly advised to also have
136 L<JSON::XS> installed. The C<text/x-json> content type is supported but is
137 deprecated and you will receive warnings in your log.
139 =item * C<text/x-data-dumper> => C<Data::Serializer>
141 Uses the L<Data::Serializer> module to generate L<Data::Dumper> output.
143 =item * C<text/x-data-denter> => C<Data::Serializer>
145 Uses the L<Data::Serializer> module to generate L<Data::Denter> output.
147 =item * C<text/x-data-taxi> => C<Data::Serializer>
149 Uses the L<Data::Serializer> module to generate L<Data::Taxi> output.
151 =item * C<application/x-storable> => C<Data::Serializer>
153 Uses the L<Data::Serializer> module to generate L<Storable> output.
155 =item * C<application/x-freezethaw> => C<Data::Serializer>
157 Uses the L<Data::Serializer> module to generate L<FreezeThaw> output.
159 =item * C<text/x-config-general> => C<Data::Serializer>
161 Uses the L<Data::Serializer> module to generate L<Config::General> output.
163 =item * C<text/x-php-serialization> => C<Data::Serializer>
165 Uses the L<Data::Serializer> module to generate L<PHP::Serialization> output.
167 =item * C<text/xml> => C<XML::Simple>
169 Uses L<XML::Simple> to generate XML output. This is probably not suitable
170 for any real heavy XML work. Due to L<XML::Simple>s requirement that the data
171 you serialize be a HASHREF, we transform outgoing data to be in the form of:
173 { data => $yourdata }
177 Uses a regular Catalyst view. For example, if you wanted to have your
178 C<text/html> and C<text/xml> views rendered by TT, set:
182 'text/html' => [ 'View', 'TT' ],
183 'text/xml' => [ 'View', 'XML' ],
187 Your views should have a C<process> method like this:
190 my ( $self, $c, $stash_key ) = @_;
194 $output = $self->serialize( $c->stash->{$stash_key} );
198 $c->response->body( $output );
199 return 1; # important
203 my ( $self, $data ) = @_;
205 my $serialized = ... process $data here ...
212 By default, L<Catalyst::Controller::REST> will return a
213 C<415 Unsupported Media Type> response if an attempt to use an unsupported
214 content-type is made. You can ensure that something is always returned by
215 setting the C<default> config option:
217 __PACKAGE__->config(default => 'text/x-yaml');
219 would make it always fall back to the serializer plugin defined for
222 =head1 CUSTOM SERIALIZERS
224 Implementing new Serialization formats is easy! Contributions
225 are most welcome! If you would like to implement a custom serializer,
226 you should create two new modules in the L<Catalyst::Action::Serialize>
227 and L<Catalyst::Action::Deserialize> namespace. Then assign your new
228 class to the content-type's you want, and you're done.
230 See L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>
231 for more information.
233 =head1 STATUS HELPERS
235 Since so much of REST is in using HTTP, we provide these Status Helpers.
236 Using them will ensure that you are responding with the proper codes,
237 headers, and entities.
239 These helpers try and conform to the HTTP 1.1 Specification. You can
240 refer to it at: L<http://www.w3.org/Protocols/rfc2616/rfc2616.txt>.
241 These routines are all implemented as regular subroutines, and as
242 such require you pass the current context ($c) as the first argument.
248 use base 'Catalyst::Controller';
249 use Params::Validate qw(SCALAR OBJECT);
251 __PACKAGE__->mk_accessors(qw(serialize));
254 'stash_key' => 'rest',
256 'text/html' => 'YAML::HTML',
257 'text/xml' => 'XML::Simple',
258 'text/x-yaml' => 'YAML',
259 'application/json' => 'JSON',
260 'text/x-json' => 'JSON',
261 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
262 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
263 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
264 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
265 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
266 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
267 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
271 sub begin : ActionClass('Deserialize') { }
273 sub end : ActionClass('Serialize') { }
277 Returns a "200 OK" response. Takes an "entity" to serialize.
284 radiohead => "Is a good band!",
293 my %p = Params::Validate::validate( @_, { entity => 1, }, );
295 $c->response->status(200);
296 $self->_set_entity( $c, $p{'entity'} );
302 Returns a "201 CREATED" response. Takes an "entity" to serialize,
303 and a "location" where the created object can be found.
307 $self->status_created(
309 location => $c->req->uri->as_string,
311 radiohead => "Is a good band!",
315 In the above example, we use the requested URI as our location.
316 This is probably what you want for most PUT requests.
323 my %p = Params::Validate::validate(
326 location => { type => SCALAR | OBJECT },
327 entity => { optional => 1 },
332 if ( ref( $p{'location'} ) ) {
333 $location = $p{'location'}->as_string;
335 $location = $p{'location'};
337 $c->response->status(201);
338 $c->response->header( 'Location' => $location );
339 $self->_set_entity( $c, $p{'entity'} );
343 =item status_accepted
345 Returns a "202 ACCEPTED" response. Takes an "entity" to serialize.
349 $self->status_accepted(
358 sub status_accepted {
361 my %p = Params::Validate::validate( @_, { entity => 1, }, );
363 $c->response->status(202);
364 $self->_set_entity( $c, $p{'entity'} );
368 =item status_no_content
370 Returns a "204 NO CONTENT" response.
374 sub status_no_content {
377 $c->response->status(204);
378 $self->_set_entity( $c, undef );
382 =item status_bad_request
384 Returns a "400 BAD REQUEST" response. Takes a "message" argument
385 as a scalar, which will become the value of "error" in the serialized
390 $self->status_bad_request(
392 message => "Cannot do what you have asked!",
397 sub status_bad_request {
400 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
402 $c->response->status(400);
403 $c->log->debug( "Status Bad Request: " . $p{'message'} ) if $c->debug;
404 $self->_set_entity( $c, { error => $p{'message'} } );
408 =item status_not_found
410 Returns a "404 NOT FOUND" response. Takes a "message" argument
411 as a scalar, which will become the value of "error" in the serialized
416 $self->status_not_found(
418 message => "Cannot find what you were looking for!",
423 sub status_not_found {
426 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
428 $c->response->status(404);
429 $c->log->debug( "Status Not Found: " . $p{'message'} ) if $c->debug;
430 $self->_set_entity( $c, { error => $p{'message'} } );
436 Returns a "41O GONE" response. Takes a "message" argument as a scalar,
437 which will become the value of "error" in the serialized response.
443 message => "The document have been deleted by foo",
451 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
453 $c->response->status(410);
454 $c->log->debug( "Status Gone " . $p{'message'} ) if $c->debug;
455 $self->_set_entity( $c, { error => $p{'message'} } );
463 if ( defined($entity) ) {
464 $c->stash->{ $self->{'stash_key'} } = $entity;
471 =head1 MANUAL RESPONSES
473 If you want to construct your responses yourself, all you need to
474 do is put the object you want serialized in $c->stash->{'rest'}.
476 =head1 IMPLEMENTATION DETAILS
478 This Controller ties together L<Catalyst::Action::REST>,
479 L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>. It should be suitable for most applications. You should be aware that it:
483 =item Configures the Serialization Actions
485 This class provides a default configuration for Serialization. It is currently:
488 'stash_key' => 'rest',
490 'text/html' => 'YAML::HTML',
491 'text/xml' => 'XML::Simple',
492 'text/x-yaml' => 'YAML',
493 'application/json' => 'JSON',
494 'text/x-json' => 'JSON',
495 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
496 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
497 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
498 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
499 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
500 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
501 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
505 You can read the full set of options for this configuration block in
506 L<Catalyst::Action::Serialize>.
508 =item Sets a C<begin> and C<end> method for you
510 The C<begin> method uses L<Catalyst::Action::Deserialize>. The C<end>
511 method uses L<Catalyst::Action::Serialize>. If you want to override
512 either behavior, simply implement your own C<begin> and C<end> actions
515 my Foo::Controller::Monkey;
516 use base qw(Catalyst::Controller::REST);
520 ... do things before Deserializing ...
521 $self->maybe::next::method($c);
522 ... do things after Deserializing ...
527 ... do things before Serializing ...
528 $self->maybe::next::method($c);
529 ... do things after Serializing ...
534 =head1 A MILD WARNING
536 I have code in production using L<Catalyst::Controller::REST>. That said,
537 it is still under development, and it's possible that things may change
538 between releases. I promise to not break things unneccesarily. :)
542 L<Catalyst::Action::REST>, L<Catalyst::Action::Serialize>,
543 L<Catalyst::Action::Deserialize>
545 For help with REST in general:
547 The HTTP 1.1 Spec is required reading. http://www.w3.org/Protocols/rfc2616/rfc2616.txt
549 Wikipedia! http://en.wikipedia.org/wiki/Representational_State_Transfer
551 The REST Wiki: http://rest.blueoxen.net/cgi-bin/wiki.pl?FrontPage
555 See L<Catalyst::Action::REST> for authors.
559 You may distribute this code under the same terms as Perl itself.