Catalyst::Action::Serialize::View uses the calculated $stash_key; amended C::C::REST...
[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
16     use base 'Catalyst::Controller::REST';
17
18     sub thing : Local : ActionClass('REST') { }
19
20     # Answer GET requests to "thing"
21     sub thing_GET {
22        my ( $self, $c ) = @_;
23
24        # Return a 200 OK, with the data in entity
25        # serialized in the body
26        $self->status_ok(
27             $c,
28             entity => {
29                 some => 'data',
30                 foo  => 'is real bar-y',
31             },
32        );
33     }
34
35     # Answer PUT requests to "thing"
36     sub thing_PUT {
37       ... some action ...
38     }
39
40 =head1 DESCRIPTION
41
42 Catalyst::Controller::REST implements a mechanism for building
43 RESTful services in Catalyst.  It does this by extending the
44 normal Catalyst dispatch mechanism to allow for different
45 subroutines to be called based on the HTTP Method requested,
46 while also transparently handling all the serialization/deserialization for
47 you.
48
49 This is probably best served by an example.  In the above
50 controller, we have declared a Local Catalyst action on
51 "sub thing", and have used the ActionClass('REST').
52
53 Below, we have declared "thing_GET" and "thing_PUT".  Any
54 GET requests to thing will be dispatched to "thing_GET",
55 while any PUT requests will be dispatched to "thing_PUT".
56
57 Any unimplemented HTTP methods will be met with a "405 Method Not Allowed"
58 response, automatically containing the proper list of available methods.  You
59 can override this behavior through implementing a custom
60 C<thing_not_implemented> method.
61
62 If you do not provide an OPTIONS handler, we will respond to any OPTIONS
63 requests with a "200 OK", populating the Allowed header automatically.
64
65 Any data included in C<< $c->stash->{'rest'} >> will be serialized for you.
66 The serialization format will be selected based on the content-type
67 of the incoming request.  It is probably easier to use the L<STATUS HELPERS>,
68 which are described below.
69
70 The HTTP POST, PUT, and OPTIONS methods will all automatically deserialize the
71 contents of $c->request->body based on the requests content-type header.
72 A list of understood serialization formats is below.
73
74 If we do not have (or cannot run) a serializer for a given content-type, a 415
75 "Unsupported Media Type" error is generated.
76
77 To make your Controller RESTful, simply have it
78
79   BEGIN {extends 'Catalyst::Controller::REST'; }
80
81 Or if you use pre-Moose Catalyst versions,
82
83   use parent 'Catalyst::Controller::REST';
84
85
86 =head1 SERIALIZATION
87
88 Catalyst::Controller::REST will automatically serialize your
89 responses, and deserialize any POST, PUT or OPTIONS requests. It evaluates
90 which serializer to use by mapping a content-type to a Serialization module.
91 We select the content-type based on:
92
93 =over 2
94
95 =item B<The Content-Type Header>
96
97 If the incoming HTTP Request had a Content-Type header set, we will use it.
98
99 =item B<The content-type Query Parameter>
100
101 If this is a GET request, you can supply a content-type query parameter.
102
103 =item B<Evaluating the Accept Header>
104
105 Finally, if the client provided an Accept header, we will evaluate
106 it and use the best-ranked choice.
107
108 =back
109
110
111 =head1 AVAILABLE SERIALIZERS
112
113 A given serialization mechanism is only available if you have the underlying
114 modules installed.  For example, you can't use XML::Simple if it's not already
115 installed.
116
117 In addition, each serializer has its quirks in terms of what sorts of data
118 structures it will properly handle.  L<Catalyst::Controller::REST> makes
119 no attempt to save you from yourself in this regard. :)
120
121 =over 2
122
123 =item * C<text/x-yaml> => C<YAML::Syck>
124
125 Returns YAML generated by L<YAML::Syck>.
126
127 =item * C<text/html> => C<YAML::HTML>
128
129 This uses L<YAML::Syck> and L<URI::Find> to generate YAML with all URLs turned
130 to hyperlinks.  Only useable for Serialization.
131
132 =item * C<application/json> => C<JSON>
133
134 Uses L<JSON> to generate JSON output.  It is strongly advised to also have
135 L<JSON::XS> installed.  The C<text/x-json> content type is supported but is
136 deprecated and you will receive warnings in your log.
137
138 =item * C<text/x-data-dumper> => C<Data::Serializer>
139
140 Uses the L<Data::Serializer> module to generate L<Data::Dumper> output.
141
142 =item * C<text/x-data-denter> => C<Data::Serializer>
143
144 Uses the L<Data::Serializer> module to generate L<Data::Denter> output.
145
146 =item * C<text/x-data-taxi> => C<Data::Serializer>
147
148 Uses the L<Data::Serializer> module to generate L<Data::Taxi> output.
149
150 =item * C<application/x-storable> => C<Data::Serializer>
151
152 Uses the L<Data::Serializer> module to generate L<Storable> output.
153
154 =item * C<application/x-freezethaw> => C<Data::Serializer>
155
156 Uses the L<Data::Serializer> module to generate L<FreezeThaw> output.
157
158 =item * C<text/x-config-general> => C<Data::Serializer>
159
160 Uses the L<Data::Serializer> module to generate L<Config::General> output.
161
162 =item * C<text/x-php-serialization> => C<Data::Serializer>
163
164 Uses the L<Data::Serializer> module to generate L<PHP::Serialization> output.
165
166 =item * C<text/xml> => C<XML::Simple>
167
168 Uses L<XML::Simple> to generate XML output.  This is probably not suitable
169 for any real heavy XML work. Due to L<XML::Simple>s requirement that the data
170 you serialize be a HASHREF, we transform outgoing data to be in the form of:
171
172   { data => $yourdata }
173
174 =item * L<View>
175
176 Uses a regular Catalyst view.  For example, if you wanted to have your
177 C<text/html> and C<text/xml> views rendered by TT, set:
178
179   __PACKAGE__->config(
180       map => {
181           'text/html' => [ 'View', 'TT' ],
182           'text/xml'  => [ 'View', 'XML' ],
183       }
184   );    
185
186 Your views should have a C<process> method like this:
187
188   sub process {
189       my ( $self, $c, $stash_key ) = @_;
190       
191       my $output;
192       eval {
193           $output = $self->serialize( $c->stash->{$stash_key} );
194       };
195       return $@ if $@;
196       
197       $c->response->body( $output );
198       return 1;  # important
199   }
200   
201   sub serialize {
202       my ( $self, $data ) = @_;
203   
204       my $serialized = ... process $data here ...
205       
206       return $serialized;
207   }
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 4
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 AUTHOR
554
555 Adam Jacob <adam@stalecoffee.org>, with lots of help from mst and jrockway
556
557 Marchex, Inc. paid me while I developed this module.  (http://www.marchex.com)
558
559 =head1 MAINTAINER
560
561 J. Shirley <jshirley@cpan.org>
562
563 =head1 LICENSE
564
565 You may distribute this code under the same terms as Perl itself.
566
567 =cut
568
569 1;