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