1 package Catalyst::Controller::REST;
5 Catalyst::Controller::REST - A RESTful controller
9 package Foo::Controller::Bar;
11 use base 'Catalyst::Controller::REST';
13 sub thing : Local : ActionClass('REST') { }
15 # Answer GET requests to "thing"
17 my ( $self, $c ) = @_;
19 # Return a 200 OK, with the data in entity
20 # serialized in the body
25 foo => 'is real bar-y',
30 # Answer PUT requests to "thing"
37 Catalyst::Controller::REST implements a mechanism for building
38 RESTful services in Catalyst. It does this by extending the
39 normal Catalyst dispatch mechanism to allow for different
40 subroutines to be called based on the HTTP Method requested,
41 while also transparently handling all the serialization/deserialization for
44 This is probably best served by an example. In the above
45 controller, we have declared a Local Catalyst action on
46 "sub thing", and have used the ActionClass('REST').
48 Below, we have declared "thing_GET" and "thing_PUT". Any
49 GET requests to thing will be dispatched to "thing_GET",
50 while any PUT requests will be dispatched to "thing_PUT".
52 Any unimplemented HTTP methods will be met with a "405 Method Not Allowed"
53 response, automatically containing the proper list of available methods. You
54 can override this behavior through implementing a custom
55 C<thing_not_implemented> method.
57 If you do not provide an OPTIONS handler, we will respond to any OPTIONS
58 requests with a "200 OK", populating the Allowed header automatically.
60 Any data included in C<< $c->stash->{'rest'} >> will be serialized for you.
61 The serialization format will be selected based on the content-type
62 of the incoming request. It is probably easier to use the L<STATUS HELPERS>,
63 which are described below.
65 The HTTP POST, PUT, and OPTIONS methods will all automatically deserialize the
66 contents of $c->request->body based on the requests content-type header.
67 A list of understood serialization formats is below.
69 If we do not have (or cannot run) a serializer for a given content-type, a 415
70 "Unsupported Media Type" error is generated.
72 To make your Controller RESTful, simply have it
74 use base 'Catalyst::Controller::REST';
78 Catalyst::Controller::REST will automatically serialize your
79 responses, and deserialize any POST, PUT or OPTIONS requests. It evaluates
80 which serializer to use by mapping a content-type to a Serialization module.
81 We select the content-type based on:
85 =item B<The Content-Type Header>
87 If the incoming HTTP Request had a Content-Type header set, we will use it.
89 =item B<The content-type Query Parameter>
91 If this is a GET request, you can supply a content-type query parameter.
93 =item B<Evaluating the Accept Header>
95 Finally, if the client provided an Accept header, we will evaluate
96 it and use the best-ranked choice.
100 =head1 AVAILABLE SERIALIZERS
102 A given serialization mechanism is only available if you have the underlying
103 modules installed. For example, you can't use XML::Simple if it's not already
106 In addition, each serializer has it's quirks in terms of what sorts of data
107 structures it will properly handle. L<Catalyst::Controller::REST> makes
108 no attempt to svae you from yourself in this regard. :)
112 =item C<text/x-yaml> => C<YAML::Syck>
114 Returns YAML generated by L<YAML::Syck>.
116 =item C<text/html> => C<YAML::HTML>
118 This uses L<YAML::Syck> and L<URI::Find> to generate YAML with all URLs turned
119 to hyperlinks. Only useable for Serialization.
121 =item C<text/x-json> => C<JSON::Syck>
123 Uses L<JSON::Syck> to generate JSON output
125 =item C<text/x-data-dumper> => C<Data::Serializer>
127 Uses the L<Data::Serializer> module to generate L<Data::Dumper> output.
129 =item C<text/x-data-denter> => C<Data::Serializer>
131 Uses the L<Data::Serializer> module to generate L<Data::Denter> output.
133 =item C<text/x-data-taxi> => C<Data::Serializer>
135 Uses the L<Data::Serializer> module to generate L<Data::Taxi> output.
137 =item C<application/x-storable> => C<Data::Serializer>
139 Uses the L<Data::Serializer> module to generate L<Storable> output.
141 =item C<application/x-freezethaw> => C<Data::Serializer>
143 Uses the L<Data::Serializer> module to generate L<FreezeThaw> output.
145 =item C<text/x-config-general> => C<Data::Serializer>
147 Uses the L<Data::Serializer> module to generate L<Config::General> output.
149 =item C<text/x-php-serialization> => C<Data::Serializer>
151 Uses the L<Data::Serializer> module to generate L<PHP::Serialization> output.
153 =item C<text/xml> => C<XML::Simple>
155 Uses L<XML::Simple> to generate XML output. This is probably not suitable
156 for any real heavy XML work. Due to L<XML::Simple>s requirement that the data
157 you serialize be a HASHREF, we transform outgoing data to be in the form of:
159 { data => $yourdata }
163 By default, L<Catalyst::Controller::REST> will return a C<415 Unsupported Media Type> response if an attempt to use an unsupported content-type is made. You
164 can ensure that something is always returned by setting the C<default> config
167 __PACKAGE__->config->{'serialize'}->{'default'} = 'YAML';
169 Would make it always fall back to YAML.
171 Implementing new Serialization formats is easy! Contributions
172 are most welcome! See L<Catalyst::Action::Serialize> and
173 L<Catalyst::Action::Deserialize> for more information.
175 =head1 CUSTOM SERIALIZERS
177 If you would like to implement a custom serializer, you should create two new
178 modules in the L<Catalyst::Action::Serialize> and
179 L<Catalyst::Action::Deserialize> namespace. Then assign your new class
180 to the content-type's you want, and you're done.
182 =head1 STATUS HELPERS
184 Since so much of REST is in using HTTP, we provide these Status Helpers.
185 Using them will ensure that you are responding with the proper codes,
186 headers, and entities.
188 These helpers try and conform to the HTTP 1.1 Specification. You can
189 refer to it at: L<http://www.w3.org/Protocols/rfc2616/rfc2616.txt>.
190 These routines are all implemented as regular subroutines, and as
191 such require you pass the current context ($c) as the first argument.
199 use base 'Catalyst::Controller';
200 use Params::Validate qw(:all);
202 __PACKAGE__->mk_accessors(qw(serialize));
206 'stash_key' => 'rest',
208 'text/html' => 'YAML::HTML',
209 'text/xml' => 'XML::Simple',
210 'text/x-yaml' => 'YAML',
211 'text/x-json' => 'JSON',
212 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
213 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
214 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
215 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
216 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
217 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
218 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
223 sub begin : ActionClass('Deserialize') {
226 sub end : ActionClass('Serialize') {
231 Returns a "200 OK" response. Takes an "entity" to serialize.
238 radiohead => "Is a good band!",
247 my %p = validate( @_, { entity => 1, }, );
249 $c->response->status(200);
250 $self->_set_entity( $c, $p{'entity'} );
256 Returns a "201 CREATED" response. Takes an "entity" to serialize,
257 and a "location" where the created object can be found.
261 $self->status_created(
263 location => $c->req->uri->as_string,
265 radiohead => "Is a good band!",
269 In the above example, we use the requested URI as our location.
270 This is probably what you want for most PUT requests.
280 location => { type => SCALAR | OBJECT },
281 entity => { optional => 1 },
286 if ( ref( $p{'location'} ) ) {
287 $location = $p{'location'}->as_string;
289 $location = $p{'location'};
291 $c->response->status(201);
292 $c->response->header( 'Location' => $location );
293 $self->_set_entity( $c, $p{'entity'} );
297 =item status_accepted
299 Returns a "202 ACCEPTED" response. Takes an "entity" to serialize.
303 $self->status_accepted(
312 sub status_accepted {
315 my %p = validate( @_, { entity => 1, }, );
317 $c->response->status(202);
318 $self->_set_entity( $c, $p{'entity'} );
322 =item status_bad_request
324 Returns a "400 BAD REQUEST" response. Takes a "message" argument
325 as a scalar, which will become the value of "error" in the serialized
330 $self->status_bad_request(
332 message => "Cannot do what you have asked!",
337 sub status_bad_request {
340 my %p = validate( @_, { message => { type => SCALAR }, }, );
342 $c->response->status(400);
343 $c->log->debug( "Status Bad Request: " . $p{'message'} );
344 $self->_set_entity( $c, { error => $p{'message'} } );
348 =item status_not_found
350 Returns a "404 NOT FOUND" response. Takes a "message" argument
351 as a scalar, which will become the value of "error" in the serialized
356 $self->status_not_found(
358 message => "Cannot find what you were looking for!",
363 sub status_not_found {
366 my %p = validate( @_, { message => { type => SCALAR }, }, );
368 $c->response->status(404);
369 $c->log->debug( "Status Not Found: " . $p{'message'} );
370 $self->_set_entity( $c, { error => $p{'message'} } );
378 if ( defined($entity) ) {
379 $c->stash->{ $self->config->{'serialize'}->{'stash_key'} } = $entity;
386 =head1 MANUAL RESPONSES
388 If you want to construct your responses yourself, all you need to
389 do is put the object you want serialized in $c->stash->{'rest'}.
391 =head1 IMPLEMENTATION DETAILS
393 This Controller ties together L<Catalyst::Action::REST>,
394 L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>. It should be suitable for most applications. You should be aware that it:
398 =item Configures the Serialization Actions
400 This class provides a default configuration for Serialization. It is currently:
404 'stash_key' => 'rest',
406 'text/html' => 'YAML::HTML',
407 'text/xml' => 'XML::Simple',
408 'text/x-yaml' => 'YAML',
409 'text/x-json' => 'JSON',
410 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
411 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
412 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
413 'application/x-storable' => [ 'Data::Serializer', 'Storable'
415 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw'
417 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ]
419 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serializat
425 You can read the full set of options for this configuration block in
426 L<Catalyst::Action::Serialize>.
428 =item Sets a C<begin> and C<end> method for you
430 The C<begin> method uses L<Catalyst::Action::Deserialize>. The C<end>
431 method uses L<Catalyst::Action::Serialize>. If you want to override
432 either behavior, simply implement your own C<begin> and C<end> actions
435 my Foo::Controller::Monkey;
436 use base qw(Catalyst::Controller::REST);
440 ... do things before Deserializing ...
441 $self->NEXT::begin($c);
442 ... do things after Deserializing ...
447 ... do things before Serializing ...
448 $self->NEXT::end($c);
449 ... do things after Serializing ...
452 =head1 A MILD WARNING
454 I have code in production using L<Catalyst::Controller::REST>. That said,
455 it is still under development, and it's possible that things may change
456 between releases. I promise to not break things unneccesarily. :)
460 L<Catalyst::Action::REST>, L<Catalyst::Action::Serialize>,
461 L<Catalyst::Action::Deserialize>
463 For help with REST in general:
465 The HTTP 1.1 Spec is required reading. http://www.w3.org/Protocols/rfc2616/rfc2616.txt
467 Wikipedia! http://en.wikipedia.org/wiki/Representational_State_Transfer
469 The REST Wiki: http://rest.blueoxen.net/cgi-bin/wiki.pl?FrontPage
473 Adam Jacob <adam@stalecoffee.org>, with lots of help from mst and jrockway
475 Marchex, Inc. paid me while I developed this module. (http://www.marchex.com)
479 You may distribute this code under the same terms as Perl itself.