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