1 package Catalyst::Controller::REST;
7 Catalyst::Controller::REST - A RESTful controller
11 package Foo::Controller::Bar;
13 use base 'Catalyst::Controller::REST';
15 sub thing : Local : ActionClass('REST') { }
17 # Answer GET requests to "thing"
19 my ( $self, $c ) = @_;
21 # Return a 200 OK, with the data in entity
22 # serialized in the body
27 foo => 'is real bar-y',
32 # Answer PUT requests to "thing"
39 Catalyst::Controller::REST implements a mechanism for building
40 RESTful services in Catalyst. It does this by extending the
41 normal Catalyst dispatch mechanism to allow for different
42 subroutines to be called based on the HTTP Method requested,
43 while also transparently handling all the serialization/deserialization for
46 This is probably best served by an example. In the above
47 controller, we have declared a Local Catalyst action on
48 "sub thing", and have used the ActionClass('REST').
50 Below, we have declared "thing_GET" and "thing_PUT". Any
51 GET requests to thing will be dispatched to "thing_GET",
52 while any PUT requests will be dispatched to "thing_PUT".
54 Any unimplemented HTTP methods will be met with a "405 Method Not Allowed"
55 response, automatically containing the proper list of available methods. You
56 can override this behavior through implementing a custom
57 C<thing_not_implemented> method.
59 If you do not provide an OPTIONS handler, we will respond to any OPTIONS
60 requests with a "200 OK", populating the Allowed header automatically.
62 Any data included in C<< $c->stash->{'rest'} >> will be serialized for you.
63 The serialization format will be selected based on the content-type
64 of the incoming request. It is probably easier to use the L<STATUS HELPERS>,
65 which are described below.
67 The HTTP POST, PUT, and OPTIONS methods will all automatically deserialize the
68 contents of $c->request->body based on the requests content-type header.
69 A list of understood serialization formats is below.
71 If we do not have (or cannot run) a serializer for a given content-type, a 415
72 "Unsupported Media Type" error is generated.
74 To make your Controller RESTful, simply have it
76 use base 'Catalyst::Controller::REST';
80 Catalyst::Controller::REST will automatically serialize your
81 responses, and deserialize any POST, PUT or OPTIONS requests. It evaluates
82 which serializer to use by mapping a content-type to a Serialization module.
83 We select the content-type based on:
87 =item B<The Content-Type Header>
89 If the incoming HTTP Request had a Content-Type header set, we will use it.
91 =item B<The content-type Query Parameter>
93 If this is a GET request, you can supply a content-type query parameter.
95 =item B<Evaluating the Accept Header>
97 Finally, if the client provided an Accept header, we will evaluate
98 it and use the best-ranked choice.
102 =head1 AVAILABLE SERIALIZERS
104 A given serialization mechanism is only available if you have the underlying
105 modules installed. For example, you can't use XML::Simple if it's not already
108 In addition, each serializer has it's quirks in terms of what sorts of data
109 structures it will properly handle. L<Catalyst::Controller::REST> makes
110 no attempt to svae you from yourself in this regard. :)
114 =item C<text/x-yaml> => C<YAML::Syck>
116 Returns YAML generated by L<YAML::Syck>.
118 =item C<text/html> => C<YAML::HTML>
120 This uses L<YAML::Syck> and L<URI::Find> to generate YAML with all URLs turned
121 to hyperlinks. Only useable for Serialization.
123 =item C<text/x-json> => C<JSON::Syck>
125 Uses L<JSON::Syck> to generate JSON output
127 =item C<text/x-data-dumper> => C<Data::Serializer>
129 Uses the L<Data::Serializer> module to generate L<Data::Dumper> output.
131 =item C<text/x-data-denter> => C<Data::Serializer>
133 Uses the L<Data::Serializer> module to generate L<Data::Denter> output.
135 =item C<text/x-data-taxi> => C<Data::Serializer>
137 Uses the L<Data::Serializer> module to generate L<Data::Taxi> output.
139 =item C<application/x-storable> => C<Data::Serializer>
141 Uses the L<Data::Serializer> module to generate L<Storable> output.
143 =item C<application/x-freezethaw> => C<Data::Serializer>
145 Uses the L<Data::Serializer> module to generate L<FreezeThaw> output.
147 =item C<text/x-config-general> => C<Data::Serializer>
149 Uses the L<Data::Serializer> module to generate L<Config::General> output.
151 =item C<text/x-php-serialization> => C<Data::Serializer>
153 Uses the L<Data::Serializer> module to generate L<PHP::Serialization> output.
155 =item C<text/xml> => C<XML::Simple>
157 Uses L<XML::Simple> to generate XML output. This is probably not suitable
158 for any real heavy XML work. Due to L<XML::Simple>s requirement that the data
159 you serialize be a HASHREF, we transform outgoing data to be in the form of:
161 { data => $yourdata }
165 Uses a regular Catalyst view. For example, if you wanted to have your
166 C<text/html> and C<text/xml> views rendered by TT:
168 'text/html' => [ 'View', 'TT' ],
169 'text/xml' => [ 'View', 'XML' ],
171 Will do the trick nicely.
175 By default, L<Catalyst::Controller::REST> will return a C<415 Unsupported Media Type>
176 response if an attempt to use an unsupported content-type is made. You
177 can ensure that something is always returned by setting the C<default>
180 __PACKAGE__->config->{'default'} = 'text/x-yaml';
182 Would make it always fall back to the serializer plugin defined for text/x-yaml.
184 Implementing new Serialization formats is easy! Contributions
185 are most welcome! See L<Catalyst::Action::Serialize> and
186 L<Catalyst::Action::Deserialize> for more information.
188 =head1 CUSTOM SERIALIZERS
190 If you would like to implement a custom serializer, you should create two new
191 modules in the L<Catalyst::Action::Serialize> and
192 L<Catalyst::Action::Deserialize> namespace. Then assign your new class
193 to the content-type's you want, and you're done.
195 =head1 STATUS HELPERS
197 Since so much of REST is in using HTTP, we provide these Status Helpers.
198 Using them will ensure that you are responding with the proper codes,
199 headers, and entities.
201 These helpers try and conform to the HTTP 1.1 Specification. You can
202 refer to it at: L<http://www.w3.org/Protocols/rfc2616/rfc2616.txt>.
203 These routines are all implemented as regular subroutines, and as
204 such require you pass the current context ($c) as the first argument.
212 use base 'Catalyst::Controller';
213 use Params::Validate qw(SCALAR OBJECT);
215 __PACKAGE__->mk_accessors(qw(serialize));
218 'stash_key' => 'rest',
220 'text/html' => 'YAML::HTML',
221 'text/xml' => 'XML::Simple',
222 'text/x-yaml' => 'YAML',
223 'application/json' => 'JSON',
224 'text/x-json' => 'JSON',
225 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
226 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
227 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
228 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
229 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
230 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
231 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
235 sub begin : ActionClass('Deserialize') {
238 sub end : ActionClass('Serialize') {
243 Returns a "200 OK" response. Takes an "entity" to serialize.
250 radiohead => "Is a good band!",
259 my %p = Params::Validate::validate( @_, { entity => 1, }, );
261 $c->response->status(200);
262 $self->_set_entity( $c, $p{'entity'} );
268 Returns a "201 CREATED" response. Takes an "entity" to serialize,
269 and a "location" where the created object can be found.
273 $self->status_created(
275 location => $c->req->uri->as_string,
277 radiohead => "Is a good band!",
281 In the above example, we use the requested URI as our location.
282 This is probably what you want for most PUT requests.
289 my %p = Params::Validate::validate(
292 location => { type => SCALAR | OBJECT },
293 entity => { optional => 1 },
298 if ( ref( $p{'location'} ) ) {
299 $location = $p{'location'}->as_string;
301 $location = $p{'location'};
303 $c->response->status(201);
304 $c->response->header( 'Location' => $location );
305 $self->_set_entity( $c, $p{'entity'} );
309 =item status_accepted
311 Returns a "202 ACCEPTED" response. Takes an "entity" to serialize.
315 $self->status_accepted(
324 sub status_accepted {
327 my %p = Params::Validate::validate( @_, { entity => 1, }, );
329 $c->response->status(202);
330 $self->_set_entity( $c, $p{'entity'} );
334 =item status_bad_request
336 Returns a "400 BAD REQUEST" response. Takes a "message" argument
337 as a scalar, which will become the value of "error" in the serialized
342 $self->status_bad_request(
344 message => "Cannot do what you have asked!",
349 sub status_bad_request {
352 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
354 $c->response->status(400);
355 $c->log->debug( "Status Bad Request: " . $p{'message'} ) if $c->debug;
356 $self->_set_entity( $c, { error => $p{'message'} } );
360 =item status_not_found
362 Returns a "404 NOT FOUND" response. Takes a "message" argument
363 as a scalar, which will become the value of "error" in the serialized
368 $self->status_not_found(
370 message => "Cannot find what you were looking for!",
375 sub status_not_found {
378 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
380 $c->response->status(404);
381 $c->log->debug( "Status Not Found: " . $p{'message'} ) if $c->debug;
382 $self->_set_entity( $c, { error => $p{'message'} } );
390 if ( defined($entity) ) {
391 $c->stash->{ $self->{'stash_key'} } = $entity;
398 =head1 MANUAL RESPONSES
400 If you want to construct your responses yourself, all you need to
401 do is put the object you want serialized in $c->stash->{'rest'}.
403 =head1 IMPLEMENTATION DETAILS
405 This Controller ties together L<Catalyst::Action::REST>,
406 L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>. It should be suitable for most applications. You should be aware that it:
410 =item Configures the Serialization Actions
412 This class provides a default configuration for Serialization. It is currently:
416 'stash_key' => 'rest',
418 'text/html' => 'YAML::HTML',
419 'text/xml' => 'XML::Simple',
420 'text/x-yaml' => 'YAML',
421 'application/json' => 'JSON',
422 'text/x-json' => 'JSON',
423 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
424 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
425 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
426 'application/x-storable' => [ 'Data::Serializer', 'Storable'
428 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw'
430 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ]
432 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
437 You can read the full set of options for this configuration block in
438 L<Catalyst::Action::Serialize>.
440 =item Sets a C<begin> and C<end> method for you
442 The C<begin> method uses L<Catalyst::Action::Deserialize>. The C<end>
443 method uses L<Catalyst::Action::Serialize>. If you want to override
444 either behavior, simply implement your own C<begin> and C<end> actions
447 my Foo::Controller::Monkey;
448 use base qw(Catalyst::Controller::REST);
452 ... do things before Deserializing ...
453 $self->NEXT::begin($c);
454 ... do things after Deserializing ...
459 ... do things before Serializing ...
460 $self->NEXT::end($c);
461 ... do things after Serializing ...
464 =head1 A MILD WARNING
466 I have code in production using L<Catalyst::Controller::REST>. That said,
467 it is still under development, and it's possible that things may change
468 between releases. I promise to not break things unneccesarily. :)
472 L<Catalyst::Action::REST>, L<Catalyst::Action::Serialize>,
473 L<Catalyst::Action::Deserialize>
475 For help with REST in general:
477 The HTTP 1.1 Spec is required reading. http://www.w3.org/Protocols/rfc2616/rfc2616.txt
479 Wikipedia! http://en.wikipedia.org/wiki/Representational_State_Transfer
481 The REST Wiki: http://rest.blueoxen.net/cgi-bin/wiki.pl?FrontPage
485 Adam Jacob <adam@stalecoffee.org>, with lots of help from mst and jrockway
487 Marchex, Inc. paid me while I developed this module. (http://www.marchex.com)
491 You may distribute this code under the same terms as Perl itself.