3c9ec67cd2caa390895b0937b872d6b5f539c238
[catagits/Catalyst-Action-REST.git] / lib / Catalyst / Controller / REST.pm
1 package Catalyst::Controller::REST;
2
3 use Moose;
4 use namespace::autoclean;
5
6 =head1 NAME
7
8 Catalyst::Controller::REST - A RESTful controller
9
10 =head1 SYNOPSIS
11
12     package Foo::Controller::Bar;
13     use Moose;
14     use namespace::autoclean;
15
16     BEGIN { extends '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         my ( $self, $c ) = @_;
38
39         $radiohead = $c->req->data->{radiohead};
40
41         $self->status_created(
42             $c,
43             location => $c->req->uri,
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 usable 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 You can also add a hash in your controller config to pass options to the json object.
150 For instance, to relax permissions when deserializing input, add:
151   __PACKAGE__->config(
152     json_options => { relaxed => 1 }
153   )
154
155 =item * C<text/javascript> => C<JSONP>
156
157 If a callback=? parameter is passed, this returns javascript in the form of: $callback($serializedJSON);
158
159 Note - this is disabled by default as it can be a security risk if you are unaware.
160
161 The usual MIME types for this serialization format are: 'text/javascript', 'application/x-javascript',
162 'application/javascript'.
163
164 =item * C<text/x-data-dumper> => C<Data::Serializer>
165
166 Uses the L<Data::Serializer> module to generate L<Data::Dumper> output.
167
168 =item * C<text/x-data-denter> => C<Data::Serializer>
169
170 Uses the L<Data::Serializer> module to generate L<Data::Denter> output.
171
172 =item * C<text/x-data-taxi> => C<Data::Serializer>
173
174 Uses the L<Data::Serializer> module to generate L<Data::Taxi> output.
175
176 =item * C<text/x-config-general> => C<Data::Serializer>
177
178 Uses the L<Data::Serializer> module to generate L<Config::General> output.
179
180 =item * C<text/x-php-serialization> => C<Data::Serializer>
181
182 Uses the L<Data::Serializer> module to generate L<PHP::Serialization> output.
183
184 =item * C<text/xml> => C<XML::Simple>
185
186 Uses L<XML::Simple> to generate XML output.  This is probably not suitable
187 for any real heavy XML work. Due to L<XML::Simple>s requirement that the data
188 you serialize be a HASHREF, we transform outgoing data to be in the form of:
189
190   { data => $yourdata }
191
192 =item * L<View>
193
194 Uses a regular Catalyst view.  For example, if you wanted to have your
195 C<text/html> and C<text/xml> views rendered by TT, set:
196
197   __PACKAGE__->config(
198       map => {
199           'text/html' => [ 'View', 'TT' ],
200           'text/xml'  => [ 'View', 'XML' ],
201       }
202   );
203
204 Your views should have a C<process> method like this:
205
206   sub process {
207       my ( $self, $c, $stash_key ) = @_;
208
209       my $output;
210       eval {
211           $output = $self->serialize( $c->stash->{$stash_key} );
212       };
213       return $@ if $@;
214
215       $c->response->body( $output );
216       return 1;  # important
217   }
218
219   sub serialize {
220       my ( $self, $data ) = @_;
221
222       my $serialized = ... process $data here ...
223
224       return $serialized;
225   }
226
227 =item * Callback
228
229 For infinite flexibility, you can provide a callback for the
230 deserialization/serialization steps.
231
232   __PACKAGE__->config(
233       map => {
234           'text/xml'  => [ 'Callback', { deserialize => \&parse_xml, serialize => \&render_xml } ],
235       }
236   );
237
238 The C<deserialize> callback is passed a string that is the body of the
239 request and is expected to return a scalar value that results from
240 the deserialization.  The C<serialize> callback is passed the data
241 structure that needs to be serialized and must return a string suitable
242 for returning in the HTTP response.  In addition to receiving the scalar
243 to act on, both callbacks are passed the controller object and the context
244 (i.e. C<$c>) as the second and third arguments.
245
246 =back
247
248 By default, L<Catalyst::Controller::REST> will return a
249 C<415 Unsupported Media Type> response if an attempt to use an unsupported
250 content-type is made.  You can ensure that something is always returned by
251 setting the C<default> config option:
252
253   __PACKAGE__->config(default => 'text/x-yaml');
254
255 would make it always fall back to the serializer plugin defined for
256 C<text/x-yaml>.
257
258 =head1 CUSTOM SERIALIZERS
259
260 Implementing new Serialization formats is easy!  Contributions
261 are most welcome!  If you would like to implement a custom serializer,
262 you should create two new modules in the L<Catalyst::Action::Serialize>
263 and L<Catalyst::Action::Deserialize> namespace.  Then assign your new
264 class to the content-type's you want, and you're done.
265
266 See L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>
267 for more information.
268
269 =head1 STATUS HELPERS
270
271 Since so much of REST is in using HTTP, we provide these Status Helpers.
272 Using them will ensure that you are responding with the proper codes,
273 headers, and entities.
274
275 These helpers try and conform to the HTTP 1.1 Specification.  You can
276 refer to it at: L<http://www.w3.org/Protocols/rfc2616/rfc2616.txt>.
277 These routines are all implemented as regular subroutines, and as
278 such require you pass the current context ($c) as the first argument.
279
280 =over
281
282 =cut
283
284 BEGIN { extends 'Catalyst::Controller' }
285 use Params::Validate qw(SCALAR OBJECT);
286
287 __PACKAGE__->mk_accessors(qw(serialize));
288
289 __PACKAGE__->config(
290     'stash_key' => 'rest',
291     'map'       => {
292         'text/xml'           => 'XML::Simple',
293         'application/json'   => 'JSON',
294         'text/x-json'        => 'JSON',
295     },
296     'compliance_mode' => 0,
297 );
298
299 sub begin : ActionClass('Deserialize') { }
300
301 sub end : ActionClass('Serialize') { }
302
303 =item status_ok
304
305 Returns a "200 OK" response.  Takes an "entity" to serialize.
306
307 Example:
308
309   $self->status_ok(
310     $c,
311     entity => {
312         radiohead => "Is a good band!",
313     }
314   );
315
316 =cut
317
318 sub status_ok {
319     my $self = shift;
320     my $c    = shift;
321     my %p    = Params::Validate::validate( @_, { entity => 1, }, );
322
323     $c->response->status(200);
324     $self->_set_entity( $c, $p{'entity'} );
325     return 1;
326 }
327
328 =item status_created
329
330 Returns a "201 CREATED" response.  Takes an "entity" to serialize,
331 and a "location" where the created object can be found.
332
333 Example:
334
335   $self->status_created(
336     $c,
337     location => $c->req->uri,
338     entity => {
339         radiohead => "Is a good band!",
340     }
341   );
342
343 In the above example, we use the requested URI as our location.
344 This is probably what you want for most PUT requests.
345
346 =cut
347
348 sub status_created {
349     my $self = shift;
350     my $c    = shift;
351     my %p    = Params::Validate::validate(
352         @_,
353         {
354             location => { type     => SCALAR | OBJECT },
355             entity   => { optional => 1 },
356         },
357     );
358
359     $c->response->status(201);
360     $c->response->header( 'Location' => $p{location} );
361     $self->_set_entity( $c, $p{'entity'} );
362     return 1;
363 }
364
365 =item status_accepted
366
367 Returns a "202 ACCEPTED" response.  Takes an "entity" to serialize.
368 Also takes optional "location" for queue type scenarios.
369
370 Example:
371
372   $self->status_accepted(
373     $c,
374     location => $c->req->uri,
375     entity => {
376         status => "queued",
377     }
378   );
379
380 =cut
381
382 sub status_accepted {
383     my $self = shift;
384     my $c    = shift;
385     my %p    = Params::Validate::validate(
386         @_,
387         {
388             location => { type => SCALAR | OBJECT, optional => 1 },
389             entity   => 1,
390         },
391     );
392
393     $c->response->status(202);
394     $c->response->header( 'Location' => $p{location} ) if exists $p{location};
395     $self->_set_entity( $c, $p{'entity'} );
396     return 1;
397 }
398
399 =item status_no_content
400
401 Returns a "204 NO CONTENT" response.
402
403 =cut
404
405 sub status_no_content {
406     my $self = shift;
407     my $c    = shift;
408     $c->response->status(204);
409     $self->_set_entity( $c, undef );
410     return 1;
411 }
412
413 =item status_multiple_choices
414
415 Returns a "300 MULTIPLE CHOICES" response. Takes an "entity" to serialize, which should
416 provide list of possible locations. Also takes optional "location" for preferred choice.
417
418 =cut
419
420 sub status_multiple_choices {
421     my $self = shift;
422     my $c    = shift;
423     my %p    = Params::Validate::validate(
424         @_,
425         {
426             entity => 1,
427             location => { type     => SCALAR | OBJECT, optional => 1 },
428         },
429     );
430
431     $c->response->status(300);
432     $c->response->header( 'Location' => $p{location} ) if exists $p{'location'};
433     $self->_set_entity( $c, $p{'entity'} );
434     return 1;
435 }
436
437 =item status_found
438
439 Returns a "302 FOUND" response. Takes an "entity" to serialize.
440 Also takes optional "location".
441
442 =cut
443
444 sub status_found {
445     my $self = shift;
446     my $c    = shift;
447     my %p    = Params::Validate::validate(
448         @_,
449         {
450             entity => 1,
451             location => { type     => SCALAR | OBJECT, optional => 1 },
452         },
453     );
454
455     $c->response->status(302);
456     $c->response->header( 'Location' => $p{location} ) if exists $p{'location'};
457     $self->_set_entity( $c, $p{'entity'} );
458     return 1;
459 }
460
461 =item status_bad_request
462
463 Returns a "400 BAD REQUEST" response.  Takes a "message" argument
464 as a scalar, which will become the value of "error" in the serialized
465 response.
466
467 Example:
468
469   $self->status_bad_request(
470     $c,
471     message => "Cannot do what you have asked!",
472   );
473
474 =cut
475
476 sub status_bad_request {
477     my $self = shift;
478     my $c    = shift;
479     my %p    = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
480
481     $c->response->status(400);
482     $c->log->debug( "Status Bad Request: " . $p{'message'} ) if $c->debug;
483     $self->_set_entity( $c, { error => $p{'message'} } );
484     return 1;
485 }
486
487 =item status_forbidden
488
489 Returns a "403 FORBIDDEN" response.  Takes a "message" argument
490 as a scalar, which will become the value of "error" in the serialized
491 response.
492
493 Example:
494
495   $self->status_forbidden(
496     $c,
497     message => "access denied",
498   );
499
500 =cut
501
502 sub status_forbidden {
503     my $self = shift;
504     my $c    = shift;
505     my %p    = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
506
507     $c->response->status(403);
508     $c->log->debug( "Status Forbidden: " . $p{'message'} ) if $c->debug;
509     $self->_set_entity( $c, { error => $p{'message'} } );
510     return 1;
511 }
512
513 =item status_not_found
514
515 Returns a "404 NOT FOUND" response.  Takes a "message" argument
516 as a scalar, which will become the value of "error" in the serialized
517 response.
518
519 Example:
520
521   $self->status_not_found(
522     $c,
523     message => "Cannot find what you were looking for!",
524   );
525
526 =cut
527
528 sub status_not_found {
529     my $self = shift;
530     my $c    = shift;
531     my %p    = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
532
533     $c->response->status(404);
534     $c->log->debug( "Status Not Found: " . $p{'message'} ) if $c->debug;
535     $self->_set_entity( $c, { error => $p{'message'} } );
536     return 1;
537 }
538
539 =item gone
540
541 Returns a "41O GONE" response.  Takes a "message" argument as a scalar,
542 which will become the value of "error" in the serialized response.
543
544 Example:
545
546   $self->status_gone(
547     $c,
548     message => "The document have been deleted by foo",
549   );
550
551 =cut
552
553 sub status_gone {
554     my $self = shift;
555     my $c    = shift;
556     my %p    = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
557
558     $c->response->status(410);
559     $c->log->debug( "Status Gone " . $p{'message'} ) if $c->debug;
560     $self->_set_entity( $c, { error => $p{'message'} } );
561     return 1;
562 }
563
564 =item status_see_other
565
566 Returns a "303 See Other" response.  Takes an optional "entity" to serialize,
567 and a "location" where the client should redirect to.
568
569 Example:
570
571   $self->status_see_other(
572     $c,
573     location => $some_other_url,
574     entity => {
575         radiohead => "Is a good band!",
576     }
577   );
578
579 =cut
580
581 sub status_see_other {
582     my $self = shift;
583     my $c    = shift;
584     my %p    = Params::Validate::validate(
585         @_,
586         {
587             location => { type     => SCALAR | OBJECT },
588             entity   => { optional => 1 },
589         },
590     );
591
592     $c->response->status(303);
593     $c->response->header( 'Location' => $p{location} );
594     $self->_set_entity( $c, $p{'entity'} );
595     return 1;
596 }
597
598 =item status_moved
599
600 Returns a "301 MOVED" response.  Takes an "entity" to serialize, and a
601 "location" where the created object can be found.
602
603 Example:
604
605  $self->status_moved(
606    $c,
607    location => '/somewhere/else',
608    entity => {
609      radiohead => "Is a good band!",
610    },
611  );
612
613 =cut
614
615 sub status_moved {
616    my $self = shift;
617    my $c    = shift;
618    my %p    = Params::Validate::validate(
619       @_,
620       {
621          location => { type     => SCALAR | OBJECT },
622          entity   => { optional => 1 },
623       },
624    );
625
626    my $location = ref $p{location}
627       ? $p{location}->as_string
628       : $p{location}
629    ;
630
631    $c->response->status(301);
632    $c->response->header( Location => $location );
633    $self->_set_entity($c, $p{entity});
634    return 1;
635 }
636
637 sub _set_entity {
638     my $self   = shift;
639     my $c      = shift;
640     my $entity = shift;
641     if ( defined($entity) ) {
642         $c->stash->{ $self->{'stash_key'} } = $entity;
643     }
644     return 1;
645 }
646
647 =back
648
649 =head1 MANUAL RESPONSES
650
651 If you want to construct your responses yourself, all you need to
652 do is put the object you want serialized in $c->stash->{'rest'}.
653
654 =head1 IMPLEMENTATION DETAILS
655
656 This Controller ties together L<Catalyst::Action::REST>,
657 L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>.  It should be suitable for most applications.  You should be aware that it:
658
659 =over 4
660
661 =item Configures the Serialization Actions
662
663 This class provides a default configuration for Serialization.  It is currently:
664
665   __PACKAGE__->config(
666       'stash_key' => 'rest',
667       'map'       => {
668          'text/html'          => 'YAML::HTML',
669          'text/xml'           => 'XML::Simple',
670          'text/x-yaml'        => 'YAML',
671          'application/json'   => 'JSON',
672          'text/x-json'        => 'JSON',
673          'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
674          'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
675          'text/x-data-taxi'   => [ 'Data::Serializer', 'Data::Taxi'   ],
676          'application/x-storable'   => [ 'Data::Serializer', 'Storable' ],
677          'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
678          'text/x-config-general'    => [ 'Data::Serializer', 'Config::General' ],
679          'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
680       },
681   );
682
683 You can read the full set of options for this configuration block in
684 L<Catalyst::Action::Serialize>.
685
686 =item Sets a C<begin> and C<end> method for you
687
688 The C<begin> method uses L<Catalyst::Action::Deserialize>.  The C<end>
689 method uses L<Catalyst::Action::Serialize>.  If you want to override
690 either behavior, simply implement your own C<begin> and C<end> actions
691 and forward to another action with the Serialize and/or Deserialize
692 action classes:
693
694   package Foo::Controller::Monkey;
695   use Moose;
696   use namespace::autoclean;
697
698   BEGIN { extends 'Catalyst::Controller::REST' }
699
700   sub begin : Private {
701     my ($self, $c) = @_;
702     ... do things before Deserializing ...
703     $c->forward('deserialize');
704     ... do things after Deserializing ...
705   }
706
707   sub deserialize : ActionClass('Deserialize') {}
708
709   sub end :Private {
710     my ($self, $c) = @_;
711     ... do things before Serializing ...
712     $c->forward('serialize');
713     ... do things after Serializing ...
714   }
715
716   sub serialize : ActionClass('Serialize') {}
717
718 If you need to deserialize multipart requests (i.e. REST data in
719 one part and file uploads in others) you can do so by using the
720 L<Catalyst::Action::DeserializeMultiPart> action class.
721
722 =back
723
724 =head1 A MILD WARNING
725
726 I have code in production using L<Catalyst::Controller::REST>.  That said,
727 it is still under development, and it's possible that things may change
728 between releases.  I promise to not break things unnecessarily. :)
729
730 =head1 SEE ALSO
731
732 L<Catalyst::Action::REST>, L<Catalyst::Action::Serialize>,
733 L<Catalyst::Action::Deserialize>
734
735 For help with REST in general:
736
737 The HTTP 1.1 Spec is required reading. http://www.w3.org/Protocols/rfc2616/rfc2616.txt
738
739 Wikipedia! http://en.wikipedia.org/wiki/Representational_State_Transfer
740
741 The REST Wiki: http://rest.blueoxen.net/cgi-bin/wiki.pl?FrontPage
742
743 =head1 AUTHORS
744
745 See L<Catalyst::Action::REST> for authors.
746
747 =head1 LICENSE
748
749 You may distribute this code under the same terms as Perl itself.
750
751 =cut
752
753 __PACKAGE__->meta->make_immutable;
754
755 1;