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