Change all classes to Moose
[catagits/Catalyst-Action-REST.git] / lib / Catalyst / Controller / REST.pm
1 package Catalyst::Controller::REST;
2 use Moose;
3 use namespace::autoclean;
4
5 our $VERSION = '0.79';
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         $radiohead = $req->data->{radiohead};
40         
41         $self->status_created(
42             $c,
43             location => $c->req->uri->as_string,
44             entity => {
45                 radiohead => $radiohead,
46             }
47         );
48     }     
49
50 =head1 DESCRIPTION
51
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
57 you.
58
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').
62
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".
66
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.
71
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.
74
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.
79
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>.
85
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.
88
89 To make your Controller RESTful, simply have it
90
91   BEGIN { extends 'Catalyst::Controller::REST' }
92
93 =head1 CONFIGURATION
94
95 See L<Catalyst::Action::Serialize/CONFIGURATION>. Note that the C<serialize>
96 key has been deprecated.
97
98 =head1 SERIALIZATION
99
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:
104
105 =over
106
107 =item B<The Content-Type Header>
108
109 If the incoming HTTP Request had a Content-Type header set, we will use it.
110
111 =item B<The content-type Query Parameter>
112
113 If this is a GET request, you can supply a content-type query parameter.
114
115 =item B<Evaluating the Accept Header>
116
117 Finally, if the client provided an Accept header, we will evaluate
118 it and use the best-ranked choice.
119
120 =back
121
122 =head1 AVAILABLE SERIALIZERS
123
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
126 installed.
127
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. :)
131
132 =over 2
133
134 =item * C<text/x-yaml> => C<YAML::Syck>
135
136 Returns YAML generated by L<YAML::Syck>.
137
138 =item * C<text/html> => C<YAML::HTML>
139
140 This uses L<YAML::Syck> and L<URI::Find> to generate YAML with all URLs turned
141 to hyperlinks.  Only useable for Serialization.
142
143 =item * C<application/json> => C<JSON>
144
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.
148
149 =item * C<text/x-data-dumper> => C<Data::Serializer>
150
151 Uses the L<Data::Serializer> module to generate L<Data::Dumper> output.
152
153 =item * C<text/x-data-denter> => C<Data::Serializer>
154
155 Uses the L<Data::Serializer> module to generate L<Data::Denter> output.
156
157 =item * C<text/x-data-taxi> => C<Data::Serializer>
158
159 Uses the L<Data::Serializer> module to generate L<Data::Taxi> output.
160
161 =item * C<application/x-storable> => C<Data::Serializer>
162
163 Uses the L<Data::Serializer> module to generate L<Storable> output.
164
165 =item * C<application/x-freezethaw> => C<Data::Serializer>
166
167 Uses the L<Data::Serializer> module to generate L<FreezeThaw> output.
168
169 =item * C<text/x-config-general> => C<Data::Serializer>
170
171 Uses the L<Data::Serializer> module to generate L<Config::General> output.
172
173 =item * C<text/x-php-serialization> => C<Data::Serializer>
174
175 Uses the L<Data::Serializer> module to generate L<PHP::Serialization> output.
176
177 =item * C<text/xml> => C<XML::Simple>
178
179 Uses L<XML::Simple> to generate XML output.  This is probably not suitable
180 for any real heavy XML work. Due to L<XML::Simple>s requirement that the data
181 you serialize be a HASHREF, we transform outgoing data to be in the form of:
182
183   { data => $yourdata }
184
185 =item * L<View>
186
187 Uses a regular Catalyst view.  For example, if you wanted to have your
188 C<text/html> and C<text/xml> views rendered by TT, set:
189
190   __PACKAGE__->config(
191       map => {
192           'text/html' => [ 'View', 'TT' ],
193           'text/xml'  => [ 'View', 'XML' ],
194       }
195   );
196
197 Your views should have a C<process> method like this:
198
199   sub process {
200       my ( $self, $c, $stash_key ) = @_;
201
202       my $output;
203       eval {
204           $output = $self->serialize( $c->stash->{$stash_key} );
205       };
206       return $@ if $@;
207
208       $c->response->body( $output );
209       return 1;  # important
210   }
211   
212   sub serialize {
213       my ( $self, $data ) = @_;
214
215       my $serialized = ... process $data here ...
216
217       return $serialized;
218   }
219
220 =back
221
222 By default, L<Catalyst::Controller::REST> will return a 
223 C<415 Unsupported Media Type> response if an attempt to use an unsupported
224 content-type is made.  You can ensure that something is always returned by
225 setting the C<default> config option:
226
227   __PACKAGE__->config(default => 'text/x-yaml');
228
229 would make it always fall back to the serializer plugin defined for
230 C<text/x-yaml>.
231
232 =head1 CUSTOM SERIALIZERS
233
234 Implementing new Serialization formats is easy!  Contributions
235 are most welcome!  If you would like to implement a custom serializer, 
236 you should create two new modules in the L<Catalyst::Action::Serialize>
237 and L<Catalyst::Action::Deserialize> namespace.  Then assign your new
238 class to the content-type's you want, and you're done.
239
240 See L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize> 
241 for more information.
242
243 =head1 STATUS HELPERS
244
245 Since so much of REST is in using HTTP, we provide these Status Helpers.
246 Using them will ensure that you are responding with the proper codes,
247 headers, and entities.
248
249 These helpers try and conform to the HTTP 1.1 Specification.  You can
250 refer to it at: L<http://www.w3.org/Protocols/rfc2616/rfc2616.txt>.
251 These routines are all implemented as regular subroutines, and as
252 such require you pass the current context ($c) as the first argument.
253
254 =over
255
256 =cut
257
258 BEGIN { extends 'Catalyst::Controller' }
259 use Params::Validate qw(SCALAR OBJECT);
260
261 __PACKAGE__->mk_accessors(qw(serialize));
262
263 __PACKAGE__->config(
264     'stash_key' => 'rest',
265     'map'       => {
266         'text/html'          => 'YAML::HTML',
267         'text/xml'           => 'XML::Simple',
268         'text/x-yaml'        => 'YAML',
269         'application/json'   => 'JSON',
270         'text/x-json'        => 'JSON',
271         'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
272         'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
273         'text/x-data-taxi'   => [ 'Data::Serializer', 'Data::Taxi'   ],
274         'application/x-storable'   => [ 'Data::Serializer', 'Storable' ],
275         'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
276         'text/x-config-general'    => [ 'Data::Serializer', 'Config::General' ],
277         'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
278     },
279 );
280
281 sub begin : ActionClass('Deserialize') { }
282
283 sub end : ActionClass('Serialize') { }
284
285 =item status_ok
286
287 Returns a "200 OK" response.  Takes an "entity" to serialize.
288
289 Example:
290
291   $self->status_ok(
292     $c,
293     entity => {
294         radiohead => "Is a good band!",
295     }
296   );
297
298 =cut
299
300 sub status_ok {
301     my $self = shift;
302     my $c    = shift;
303     my %p    = Params::Validate::validate( @_, { entity => 1, }, );
304
305     $c->response->status(200);
306     $self->_set_entity( $c, $p{'entity'} );
307     return 1;
308 }
309
310 =item status_created
311
312 Returns a "201 CREATED" response.  Takes an "entity" to serialize,
313 and a "location" where the created object can be found.
314
315 Example:
316
317   $self->status_created(
318     $c,
319     location => $c->req->uri->as_string,
320     entity => {
321         radiohead => "Is a good band!",
322     }
323   );
324
325 In the above example, we use the requested URI as our location.
326 This is probably what you want for most PUT requests.
327
328 =cut
329
330 sub status_created {
331     my $self = shift;
332     my $c    = shift;
333     my %p    = Params::Validate::validate(
334         @_,
335         {
336             location => { type     => SCALAR | OBJECT },
337             entity   => { optional => 1 },
338         },
339     );
340
341     my $location;
342     if ( ref( $p{'location'} ) ) {
343         $location = $p{'location'}->as_string;
344     } else {
345         $location = $p{'location'};
346     }
347     $c->response->status(201);
348     $c->response->header( 'Location' => $location );
349     $self->_set_entity( $c, $p{'entity'} );
350     return 1;
351 }
352
353 =item status_accepted
354
355 Returns a "202 ACCEPTED" response.  Takes an "entity" to serialize.
356
357 Example:
358
359   $self->status_accepted(
360     $c,
361     entity => {
362         status => "queued",
363     }
364   );
365
366 =cut
367
368 sub status_accepted {
369     my $self = shift;
370     my $c    = shift;
371     my %p    = Params::Validate::validate( @_, { entity => 1, }, );
372
373     $c->response->status(202);
374     $self->_set_entity( $c, $p{'entity'} );
375     return 1;
376 }
377
378 =item status_no_content
379
380 Returns a "204 NO CONTENT" response.
381
382 =cut
383
384 sub status_no_content {
385     my $self = shift;
386     my $c    = shift;
387     $c->response->status(204);
388     $self->_set_entity( $c, undef );
389     return 1.;
390 }
391
392 =item status_bad_request
393
394 Returns a "400 BAD REQUEST" response.  Takes a "message" argument
395 as a scalar, which will become the value of "error" in the serialized
396 response.
397
398 Example:
399
400   $self->status_bad_request(
401     $c,
402     message => "Cannot do what you have asked!",
403   );
404
405 =cut
406
407 sub status_bad_request {
408     my $self = shift;
409     my $c    = shift;
410     my %p    = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
411
412     $c->response->status(400);
413     $c->log->debug( "Status Bad Request: " . $p{'message'} ) if $c->debug;
414     $self->_set_entity( $c, { error => $p{'message'} } );
415     return 1;
416 }
417
418 =item status_not_found
419
420 Returns a "404 NOT FOUND" response.  Takes a "message" argument
421 as a scalar, which will become the value of "error" in the serialized
422 response.
423
424 Example:
425
426   $self->status_not_found(
427     $c,
428     message => "Cannot find what you were looking for!",
429   );
430
431 =cut
432
433 sub status_not_found {
434     my $self = shift;
435     my $c    = shift;
436     my %p    = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
437
438     $c->response->status(404);
439     $c->log->debug( "Status Not Found: " . $p{'message'} ) if $c->debug;
440     $self->_set_entity( $c, { error => $p{'message'} } );
441     return 1;
442 }
443
444 =item gone
445
446 Returns a "41O GONE" response.  Takes a "message" argument as a scalar,
447 which will become the value of "error" in the serialized response.
448
449 Example:
450
451   $self->status_gone(
452     $c,
453     message => "The document have been deleted by foo",
454   );
455
456 =cut
457
458 sub status_gone {
459     my $self = shift;
460     my $c    = shift;
461     my %p    = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
462
463     $c->response->status(410);
464     $c->log->debug( "Status Gone " . $p{'message'} ) if $c->debug;
465     $self->_set_entity( $c, { error => $p{'message'} } );
466     return 1;
467 }
468
469 sub _set_entity {
470     my $self   = shift;
471     my $c      = shift;
472     my $entity = shift;
473     if ( defined($entity) ) {
474         $c->stash->{ $self->{'stash_key'} } = $entity;
475     }
476     return 1;
477 }
478
479 =back
480
481 =head1 MANUAL RESPONSES
482
483 If you want to construct your responses yourself, all you need to
484 do is put the object you want serialized in $c->stash->{'rest'}.
485
486 =head1 IMPLEMENTATION DETAILS
487
488 This Controller ties together L<Catalyst::Action::REST>,
489 L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>.  It should be suitable for most applications.  You should be aware that it:
490
491 =over 4
492
493 =item Configures the Serialization Actions
494
495 This class provides a default configuration for Serialization.  It is currently:
496
497   __PACKAGE__->config(
498       'stash_key' => 'rest',
499       'map'       => {
500          'text/html'          => 'YAML::HTML',
501          'text/xml'           => 'XML::Simple',
502          'text/x-yaml'        => 'YAML',
503          'application/json'   => 'JSON',
504          'text/x-json'        => 'JSON',
505          'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
506          'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
507          'text/x-data-taxi'   => [ 'Data::Serializer', 'Data::Taxi'   ],
508          'application/x-storable'   => [ 'Data::Serializer', 'Storable' ],
509          'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
510          'text/x-config-general'    => [ 'Data::Serializer', 'Config::General' ],
511          'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
512       },
513   );
514
515 You can read the full set of options for this configuration block in
516 L<Catalyst::Action::Serialize>.
517
518 =item Sets a C<begin> and C<end> method for you
519
520 The C<begin> method uses L<Catalyst::Action::Deserialize>.  The C<end>
521 method uses L<Catalyst::Action::Serialize>.  If you want to override
522 either behavior, simply implement your own C<begin> and C<end> actions
523 and use MRO::Compat:
524
525   package Foo::Controller::Monkey;
526   use Moose;
527   use namespace::autoclean;
528   
529   BEGIN { extends 'Catalyst::Controller::REST' }
530
531   sub begin :Private {
532     my ($self, $c) = @_;
533     ... do things before Deserializing ...
534     $self->maybe::next::method($c);
535     ... do things after Deserializing ...
536   }
537
538   sub end :Private {
539     my ($self, $c) = @_;
540     ... do things before Serializing ...
541     $self->maybe::next::method($c);
542     ... do things after Serializing ...
543   }
544
545 =back
546
547 =head1 A MILD WARNING
548
549 I have code in production using L<Catalyst::Controller::REST>.  That said,
550 it is still under development, and it's possible that things may change
551 between releases.  I promise to not break things unneccesarily. :)
552
553 =head1 SEE ALSO
554
555 L<Catalyst::Action::REST>, L<Catalyst::Action::Serialize>,
556 L<Catalyst::Action::Deserialize>
557
558 For help with REST in general:
559
560 The HTTP 1.1 Spec is required reading. http://www.w3.org/Protocols/rfc2616/rfc2616.txt
561
562 Wikipedia! http://en.wikipedia.org/wiki/Representational_State_Transfer
563
564 The REST Wiki: http://rest.blueoxen.net/cgi-bin/wiki.pl?FrontPage
565
566 =head1 AUTHORS
567
568 See L<Catalyst::Action::REST> for authors.
569
570 =head1 LICENSE
571
572 You may distribute this code under the same terms as Perl itself.
573
574 =cut
575
576 1;