1 package Catalyst::Controller::REST;
3 use namespace::autoclean;
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"
39 $radiohead = $req->data->{radiohead};
41 $self->status_created(
43 location => $c->req->uri->as_string,
45 radiohead => $radiohead,
52 Catalyst::Controller::REST implements a mechanism for building
53 RESTful services in Catalyst. It does this by extending the
54 normal Catalyst dispatch mechanism to allow for different
55 subroutines to be called based on the HTTP Method requested,
56 while also transparently handling all the serialization/deserialization for
59 This is probably best served by an example. In the above
60 controller, we have declared a Local Catalyst action on
61 "sub thing", and have used the ActionClass('REST').
63 Below, we have declared "thing_GET" and "thing_PUT". Any
64 GET requests to thing will be dispatched to "thing_GET",
65 while any PUT requests will be dispatched to "thing_PUT".
67 Any unimplemented HTTP methods will be met with a "405 Method Not Allowed"
68 response, automatically containing the proper list of available methods. You
69 can override this behavior through implementing a custom
70 C<thing_not_implemented> method.
72 If you do not provide an OPTIONS handler, we will respond to any OPTIONS
73 requests with a "200 OK", populating the Allowed header automatically.
75 Any data included in C<< $c->stash->{'rest'} >> will be serialized for you.
76 The serialization format will be selected based on the content-type
77 of the incoming request. It is probably easier to use the L<STATUS HELPERS>,
78 which are described below.
80 "The HTTP POST, PUT, and OPTIONS methods will all automatically
81 L<deserialize|Catalyst::Action::Deserialize> the contents of
82 C<< $c->request->body >> into the C<< $c->request->data >> hashref", based on
83 the request's C<Content-type> header. A list of understood serialization
84 formats is L<below|/AVAILABLE SERIALIZERS>.
86 If we do not have (or cannot run) a serializer for a given content-type, a 415
87 "Unsupported Media Type" error is generated.
89 To make your Controller RESTful, simply have it
91 BEGIN { extends 'Catalyst::Controller::REST' }
95 See L<Catalyst::Action::Serialize/CONFIGURATION>. Note that the C<serialize>
96 key has been deprecated.
100 Catalyst::Controller::REST will automatically serialize your
101 responses, and deserialize any POST, PUT or OPTIONS requests. It evaluates
102 which serializer to use by mapping a content-type to a Serialization module.
103 We select the content-type based on:
107 =item B<The Content-Type Header>
109 If the incoming HTTP Request had a Content-Type header set, we will use it.
111 =item B<The content-type Query Parameter>
113 If this is a GET request, you can supply a content-type query parameter.
115 =item B<Evaluating the Accept Header>
117 Finally, if the client provided an Accept header, we will evaluate
118 it and use the best-ranked choice.
122 =head1 AVAILABLE SERIALIZERS
124 A given serialization mechanism is only available if you have the underlying
125 modules installed. For example, you can't use XML::Simple if it's not already
128 In addition, each serializer has its quirks in terms of what sorts of data
129 structures it will properly handle. L<Catalyst::Controller::REST> makes
130 no attempt to save you from yourself in this regard. :)
134 =item * C<text/x-yaml> => C<YAML::Syck>
136 Returns YAML generated by L<YAML::Syck>.
138 =item * C<text/html> => C<YAML::HTML>
140 This uses L<YAML::Syck> and L<URI::Find> to generate YAML with all URLs turned
141 to hyperlinks. Only usable for Serialization.
143 =item * C<application/json> => C<JSON>
145 Uses L<JSON> to generate JSON output. It is strongly advised to also have
146 L<JSON::XS> installed. The C<text/x-json> content type is supported but is
147 deprecated and you will receive warnings in your log.
149 =item * C<text/javascript> => C<JSONP>
151 If a callback=? parameter is passed, this returns javascript in the form of: $callback($serializedJSON);
153 Note - this is disabled by default as it can be a security risk if you are unaware.
155 The usual MIME types for this serialization format are: 'text/javascript', 'application/x-javascript',
156 'application/javascript'.
158 =item * C<text/x-data-dumper> => C<Data::Serializer>
160 Uses the L<Data::Serializer> module to generate L<Data::Dumper> output.
162 =item * C<text/x-data-denter> => C<Data::Serializer>
164 Uses the L<Data::Serializer> module to generate L<Data::Denter> output.
166 =item * C<text/x-data-taxi> => C<Data::Serializer>
168 Uses the L<Data::Serializer> module to generate L<Data::Taxi> output.
170 =item * C<application/x-storable> => C<Data::Serializer>
172 Uses the L<Data::Serializer> module to generate L<Storable> output.
174 =item * C<application/x-freezethaw> => C<Data::Serializer>
176 Uses the L<Data::Serializer> module to generate L<FreezeThaw> output.
178 =item * C<text/x-config-general> => C<Data::Serializer>
180 Uses the L<Data::Serializer> module to generate L<Config::General> output.
182 =item * C<text/x-php-serialization> => C<Data::Serializer>
184 Uses the L<Data::Serializer> module to generate L<PHP::Serialization> output.
186 =item * C<text/xml> => C<XML::Simple>
188 Uses L<XML::Simple> to generate XML output. This is probably not suitable
189 for any real heavy XML work. Due to L<XML::Simple>s requirement that the data
190 you serialize be a HASHREF, we transform outgoing data to be in the form of:
192 { data => $yourdata }
196 Uses a regular Catalyst view. For example, if you wanted to have your
197 C<text/html> and C<text/xml> views rendered by TT, set:
201 'text/html' => [ 'View', 'TT' ],
202 'text/xml' => [ 'View', 'XML' ],
206 Your views should have a C<process> method like this:
209 my ( $self, $c, $stash_key ) = @_;
213 $output = $self->serialize( $c->stash->{$stash_key} );
217 $c->response->body( $output );
218 return 1; # important
222 my ( $self, $data ) = @_;
224 my $serialized = ... process $data here ...
231 By default, L<Catalyst::Controller::REST> will return a
232 C<415 Unsupported Media Type> response if an attempt to use an unsupported
233 content-type is made. You can ensure that something is always returned by
234 setting the C<default> config option:
236 __PACKAGE__->config(default => 'text/x-yaml');
238 would make it always fall back to the serializer plugin defined for
241 =head1 CUSTOM SERIALIZERS
243 Implementing new Serialization formats is easy! Contributions
244 are most welcome! If you would like to implement a custom serializer,
245 you should create two new modules in the L<Catalyst::Action::Serialize>
246 and L<Catalyst::Action::Deserialize> namespace. Then assign your new
247 class to the content-type's you want, and you're done.
249 See L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>
250 for more information.
252 =head1 STATUS HELPERS
254 Since so much of REST is in using HTTP, we provide these Status Helpers.
255 Using them will ensure that you are responding with the proper codes,
256 headers, and entities.
258 These helpers try and conform to the HTTP 1.1 Specification. You can
259 refer to it at: L<http://www.w3.org/Protocols/rfc2616/rfc2616.txt>.
260 These routines are all implemented as regular subroutines, and as
261 such require you pass the current context ($c) as the first argument.
267 BEGIN { extends 'Catalyst::Controller' }
268 use Params::Validate qw(SCALAR OBJECT);
270 __PACKAGE__->mk_accessors(qw(serialize));
273 'stash_key' => 'rest',
275 'text/html' => 'YAML::HTML',
276 'text/xml' => 'XML::Simple',
277 'text/x-yaml' => 'YAML',
278 'application/json' => 'JSON',
279 'text/x-json' => 'JSON',
280 'application/x-javascript' => 'JSONP',
281 'application/javascript' => 'JSONP',
282 'text/javascript' => 'JSONP',
283 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
284 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
285 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
286 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
287 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
288 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
289 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
293 sub begin : ActionClass('Deserialize') { }
295 sub end : ActionClass('Serialize') { }
299 Returns a "200 OK" response. Takes an "entity" to serialize.
306 radiohead => "Is a good band!",
315 my %p = Params::Validate::validate( @_, { entity => 1, }, );
317 $c->response->status(200);
318 $self->_set_entity( $c, $p{'entity'} );
324 Returns a "201 CREATED" response. Takes an "entity" to serialize,
325 and a "location" where the created object can be found.
329 $self->status_created(
331 location => $c->req->uri->as_string,
333 radiohead => "Is a good band!",
337 In the above example, we use the requested URI as our location.
338 This is probably what you want for most PUT requests.
345 my %p = Params::Validate::validate(
348 location => { type => SCALAR | OBJECT },
349 entity => { optional => 1 },
354 if ( ref( $p{'location'} ) ) {
355 $location = $p{'location'}->as_string;
357 $location = $p{'location'};
359 $c->response->status(201);
360 $c->response->header( 'Location' => $location );
361 $self->_set_entity( $c, $p{'entity'} );
365 =item status_accepted
367 Returns a "202 ACCEPTED" response. Takes an "entity" to serialize.
371 $self->status_accepted(
380 sub status_accepted {
383 my %p = Params::Validate::validate( @_, { entity => 1, }, );
385 $c->response->status(202);
386 $self->_set_entity( $c, $p{'entity'} );
390 =item status_no_content
392 Returns a "204 NO CONTENT" response.
396 sub status_no_content {
399 $c->response->status(204);
400 $self->_set_entity( $c, undef );
404 =item status_bad_request
406 Returns a "400 BAD REQUEST" response. Takes a "message" argument
407 as a scalar, which will become the value of "error" in the serialized
412 $self->status_bad_request(
414 message => "Cannot do what you have asked!",
419 sub status_bad_request {
422 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
424 $c->response->status(400);
425 $c->log->debug( "Status Bad Request: " . $p{'message'} ) if $c->debug;
426 $self->_set_entity( $c, { error => $p{'message'} } );
430 =item status_not_found
432 Returns a "404 NOT FOUND" response. Takes a "message" argument
433 as a scalar, which will become the value of "error" in the serialized
438 $self->status_not_found(
440 message => "Cannot find what you were looking for!",
445 sub status_not_found {
448 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
450 $c->response->status(404);
451 $c->log->debug( "Status Not Found: " . $p{'message'} ) if $c->debug;
452 $self->_set_entity( $c, { error => $p{'message'} } );
458 Returns a "41O GONE" response. Takes a "message" argument as a scalar,
459 which will become the value of "error" in the serialized response.
465 message => "The document have been deleted by foo",
473 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
475 $c->response->status(410);
476 $c->log->debug( "Status Gone " . $p{'message'} ) if $c->debug;
477 $self->_set_entity( $c, { error => $p{'message'} } );
485 if ( defined($entity) ) {
486 $c->stash->{ $self->{'stash_key'} } = $entity;
493 =head1 MANUAL RESPONSES
495 If you want to construct your responses yourself, all you need to
496 do is put the object you want serialized in $c->stash->{'rest'}.
498 =head1 IMPLEMENTATION DETAILS
500 This Controller ties together L<Catalyst::Action::REST>,
501 L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>. It should be suitable for most applications. You should be aware that it:
505 =item Configures the Serialization Actions
507 This class provides a default configuration for Serialization. It is currently:
510 'stash_key' => 'rest',
512 'text/html' => 'YAML::HTML',
513 'text/xml' => 'XML::Simple',
514 'text/x-yaml' => 'YAML',
515 'application/json' => 'JSON',
516 'text/x-json' => 'JSON',
517 'application/x-javascript' => 'JSONP',
518 'application/javascript' => 'JSONP',
519 'text/javascript' => 'JSONP',
520 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
521 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
522 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
523 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
524 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
525 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
526 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
530 You can read the full set of options for this configuration block in
531 L<Catalyst::Action::Serialize>.
533 =item Sets a C<begin> and C<end> method for you
535 The C<begin> method uses L<Catalyst::Action::Deserialize>. The C<end>
536 method uses L<Catalyst::Action::Serialize>. If you want to override
537 either behavior, simply implement your own C<begin> and C<end> actions
540 package Foo::Controller::Monkey;
542 use namespace::autoclean;
544 BEGIN { extends 'Catalyst::Controller::REST' }
548 ... do things before Deserializing ...
549 $self->maybe::next::method($c);
550 ... do things after Deserializing ...
555 ... do things before Serializing ...
556 $self->maybe::next::method($c);
557 ... do things after Serializing ...
562 =head1 A MILD WARNING
564 I have code in production using L<Catalyst::Controller::REST>. That said,
565 it is still under development, and it's possible that things may change
566 between releases. I promise to not break things unnecessarily. :)
570 L<Catalyst::Action::REST>, L<Catalyst::Action::Serialize>,
571 L<Catalyst::Action::Deserialize>
573 For help with REST in general:
575 The HTTP 1.1 Spec is required reading. http://www.w3.org/Protocols/rfc2616/rfc2616.txt
577 Wikipedia! http://en.wikipedia.org/wiki/Representational_State_Transfer
579 The REST Wiki: http://rest.blueoxen.net/cgi-bin/wiki.pl?FrontPage
583 See L<Catalyst::Action::REST> for authors.
587 You may distribute this code under the same terms as Perl itself.