Additional pod cleanups
[catagits/Catalyst-Action-REST.git] / lib / Catalyst / Controller / REST.pm
1 package Catalyst::Controller::REST;
2 use strict;
3 use warnings;
4
5 our $VERSION = '0.78';
6 $VERSION = eval $VERSION;
7
8 =head1 NAME
9
10 Catalyst::Controller::REST - A RESTful controller
11
12 =head1 SYNOPSIS
13
14     package Foo::Controller::Bar;
15     use Moose;
16     use namespace::autoclean;
17     
18     BEGIN { extends 'Catalyst::Controller::REST' }
19
20     sub thing : Local : ActionClass('REST') { }
21
22     # Answer GET requests to "thing"
23     sub thing_GET {
24        my ( $self, $c ) = @_;
25
26        # Return a 200 OK, with the data in entity
27        # serialized in the body
28        $self->status_ok(
29             $c,
30             entity => {
31                 some => 'data',
32                 foo  => 'is real bar-y',
33             },
34        );
35     }
36
37     # Answer PUT requests to "thing"
38     sub thing_PUT {
39       ... some action ...
40     }
41
42 =head1 DESCRIPTION
43
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
49 you.
50
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').
54
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".
58
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.
63
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.
66
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.
71
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.
75
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.
78
79 To make your Controller RESTful, simply have it
80
81   BEGIN { extends 'Catalyst::Controller::REST' }
82
83 =head1 CONFIGURATION
84
85 See L<Catalyst::Action::Serialize/CONFIGURATION>. Note that the C<serialize>
86 key has been deprecated.
87
88 =head1 SERIALIZATION
89
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:
94
95 =over
96
97 =item B<The Content-Type Header>
98
99 If the incoming HTTP Request had a Content-Type header set, we will use it.
100
101 =item B<The content-type Query Parameter>
102
103 If this is a GET request, you can supply a content-type query parameter.
104
105 =item B<Evaluating the Accept Header>
106
107 Finally, if the client provided an Accept header, we will evaluate
108 it and use the best-ranked choice.
109
110 =back
111
112 =head1 AVAILABLE SERIALIZERS
113
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
116 installed.
117
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. :)
121
122 =over 2
123
124 =item * C<text/x-yaml> => C<YAML::Syck>
125
126 Returns YAML generated by L<YAML::Syck>.
127
128 =item * C<text/html> => C<YAML::HTML>
129
130 This uses L<YAML::Syck> and L<URI::Find> to generate YAML with all URLs turned
131 to hyperlinks.  Only useable for Serialization.
132
133 =item * C<application/json> => C<JSON>
134
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.
138
139 =item * C<text/x-data-dumper> => C<Data::Serializer>
140
141 Uses the L<Data::Serializer> module to generate L<Data::Dumper> output.
142
143 =item * C<text/x-data-denter> => C<Data::Serializer>
144
145 Uses the L<Data::Serializer> module to generate L<Data::Denter> output.
146
147 =item * C<text/x-data-taxi> => C<Data::Serializer>
148
149 Uses the L<Data::Serializer> module to generate L<Data::Taxi> output.
150
151 =item * C<application/x-storable> => C<Data::Serializer>
152
153 Uses the L<Data::Serializer> module to generate L<Storable> output.
154
155 =item * C<application/x-freezethaw> => C<Data::Serializer>
156
157 Uses the L<Data::Serializer> module to generate L<FreezeThaw> output.
158
159 =item * C<text/x-config-general> => C<Data::Serializer>
160
161 Uses the L<Data::Serializer> module to generate L<Config::General> output.
162
163 =item * C<text/x-php-serialization> => C<Data::Serializer>
164
165 Uses the L<Data::Serializer> module to generate L<PHP::Serialization> output.
166
167 =item * C<text/xml> => C<XML::Simple>
168
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:
172
173   { data => $yourdata }
174
175 =item * L<View>
176
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:
179
180   __PACKAGE__->config(
181       map => {
182           'text/html' => [ 'View', 'TT' ],
183           'text/xml'  => [ 'View', 'XML' ],
184       }
185   );
186
187 Your views should have a C<process> method like this:
188
189   sub process {
190       my ( $self, $c, $stash_key ) = @_;
191
192       my $output;
193       eval {
194           $output = $self->serialize( $c->stash->{$stash_key} );
195       };
196       return $@ if $@;
197
198       $c->response->body( $output );
199       return 1;  # important
200   }
201   
202   sub serialize {
203       my ( $self, $data ) = @_;
204
205       my $serialized = ... process $data here ...
206
207       return $serialized;
208   }
209
210 =back
211
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:
216
217   __PACKAGE__->config(default => 'text/x-yaml');
218
219 would make it always fall back to the serializer plugin defined for
220 C<text/x-yaml>.
221
222 =head1 CUSTOM SERIALIZERS
223
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.
229
230 See L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize> 
231 for more information.
232
233 =head1 STATUS HELPERS
234
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.
238
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.
243
244 =over
245
246 =cut
247
248 use base 'Catalyst::Controller';
249 use Params::Validate qw(SCALAR OBJECT);
250
251 __PACKAGE__->mk_accessors(qw(serialize));
252
253 __PACKAGE__->config(
254     'stash_key' => 'rest',
255     'map'       => {
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' ],
268     },
269 );
270
271 sub begin : ActionClass('Deserialize') { }
272
273 sub end : ActionClass('Serialize') { }
274
275 =item status_ok
276
277 Returns a "200 OK" response.  Takes an "entity" to serialize.
278
279 Example:
280
281   $self->status_ok(
282     $c,
283     entity => {
284         radiohead => "Is a good band!",
285     }
286   );
287
288 =cut
289
290 sub status_ok {
291     my $self = shift;
292     my $c    = shift;
293     my %p    = Params::Validate::validate( @_, { entity => 1, }, );
294
295     $c->response->status(200);
296     $self->_set_entity( $c, $p{'entity'} );
297     return 1;
298 }
299
300 =item status_created
301
302 Returns a "201 CREATED" response.  Takes an "entity" to serialize,
303 and a "location" where the created object can be found.
304
305 Example:
306
307   $self->status_created(
308     $c,
309     location => $c->req->uri->as_string,
310     entity => {
311         radiohead => "Is a good band!",
312     }
313   );
314
315 In the above example, we use the requested URI as our location.
316 This is probably what you want for most PUT requests.
317
318 =cut
319
320 sub status_created {
321     my $self = shift;
322     my $c    = shift;
323     my %p    = Params::Validate::validate(
324         @_,
325         {
326             location => { type     => SCALAR | OBJECT },
327             entity   => { optional => 1 },
328         },
329     );
330
331     my $location;
332     if ( ref( $p{'location'} ) ) {
333         $location = $p{'location'}->as_string;
334     } else {
335         $location = $p{'location'};
336     }
337     $c->response->status(201);
338     $c->response->header( 'Location' => $location );
339     $self->_set_entity( $c, $p{'entity'} );
340     return 1;
341 }
342
343 =item status_accepted
344
345 Returns a "202 ACCEPTED" response.  Takes an "entity" to serialize.
346
347 Example:
348
349   $self->status_accepted(
350     $c,
351     entity => {
352         status => "queued",
353     }
354   );
355
356 =cut
357
358 sub status_accepted {
359     my $self = shift;
360     my $c    = shift;
361     my %p    = Params::Validate::validate( @_, { entity => 1, }, );
362
363     $c->response->status(202);
364     $self->_set_entity( $c, $p{'entity'} );
365     return 1;
366 }
367
368 =item status_no_content
369
370 Returns a "204 NO CONTENT" response.
371
372 =cut
373
374 sub status_no_content {
375     my $self = shift;
376     my $c    = shift;
377     $c->response->status(204);
378     $self->_set_entity( $c, undef );
379     return 1.;
380 }
381
382 =item status_bad_request
383
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
386 response.
387
388 Example:
389
390   $self->status_bad_request(
391     $c,
392     message => "Cannot do what you have asked!",
393   );
394
395 =cut
396
397 sub status_bad_request {
398     my $self = shift;
399     my $c    = shift;
400     my %p    = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
401
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'} } );
405     return 1;
406 }
407
408 =item status_not_found
409
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
412 response.
413
414 Example:
415
416   $self->status_not_found(
417     $c,
418     message => "Cannot find what you were looking for!",
419   );
420
421 =cut
422
423 sub status_not_found {
424     my $self = shift;
425     my $c    = shift;
426     my %p    = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
427
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'} } );
431     return 1;
432 }
433
434 =item gone
435
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.
438
439 Example:
440
441   $self->status_gone(
442     $c,
443     message => "The document have been deleted by foo",
444   );
445
446 =cut
447
448 sub status_gone {
449     my $self = shift;
450     my $c    = shift;
451     my %p    = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
452
453     $c->response->status(410);
454     $c->log->debug( "Status Gone " . $p{'message'} ) if $c->debug;
455     $self->_set_entity( $c, { error => $p{'message'} } );
456     return 1;
457 }
458
459 sub _set_entity {
460     my $self   = shift;
461     my $c      = shift;
462     my $entity = shift;
463     if ( defined($entity) ) {
464         $c->stash->{ $self->{'stash_key'} } = $entity;
465     }
466     return 1;
467 }
468
469 =back
470
471 =head1 MANUAL RESPONSES
472
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'}.
475
476 =head1 IMPLEMENTATION DETAILS
477
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:
480
481 =over 4
482
483 =item Configures the Serialization Actions
484
485 This class provides a default configuration for Serialization.  It is currently:
486
487   __PACKAGE__->config(
488       'stash_key' => 'rest',
489       'map'       => {
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' ],
502       },
503   );
504
505 You can read the full set of options for this configuration block in
506 L<Catalyst::Action::Serialize>.
507
508 =item Sets a C<begin> and C<end> method for you
509
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
513 and use MRO::Compat:
514
515   my Foo::Controller::Monkey;
516   use base qw(Catalyst::Controller::REST);
517
518   sub begin :Private {
519     my ($self, $c) = @_;
520     ... do things before Deserializing ...
521     $self->maybe::next::method($c);
522     ... do things after Deserializing ...
523   }
524
525   sub end :Private {
526     my ($self, $c) = @_;
527     ... do things before Serializing ...
528     $self->maybe::next::method($c);
529     ... do things after Serializing ...
530   }
531
532 =back
533
534 =head1 A MILD WARNING
535
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. :)
539
540 =head1 SEE ALSO
541
542 L<Catalyst::Action::REST>, L<Catalyst::Action::Serialize>,
543 L<Catalyst::Action::Deserialize>
544
545 For help with REST in general:
546
547 The HTTP 1.1 Spec is required reading. http://www.w3.org/Protocols/rfc2616/rfc2616.txt
548
549 Wikipedia! http://en.wikipedia.org/wiki/Representational_State_Transfer
550
551 The REST Wiki: http://rest.blueoxen.net/cgi-bin/wiki.pl?FrontPage
552
553 =head1 AUTHORS
554
555 See L<Catalyst::Action::REST> for authors.
556
557 =head1 LICENSE
558
559 You may distribute this code under the same terms as Perl itself.
560
561 =cut
562
563 1;