Bump versions
[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.83';
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 =item * C<text/javascript> => C<JSONP>
150
151 If a callback=? parameter is passed, this returns javascript in the form of: $callback($serializedJSON);
152
153 Note - this is disabled by default as it can be a security risk if you are unaware.
154
155 The usual MIME types for this serialization format are: 'text/javascript', 'application/x-javascript',
156 'application/javascript'.
157
158 =item * C<text/x-data-dumper> => C<Data::Serializer>
159
160 Uses the L<Data::Serializer> module to generate L<Data::Dumper> output.
161
162 =item * C<text/x-data-denter> => C<Data::Serializer>
163
164 Uses the L<Data::Serializer> module to generate L<Data::Denter> output.
165
166 =item * C<text/x-data-taxi> => C<Data::Serializer>
167
168 Uses the L<Data::Serializer> module to generate L<Data::Taxi> output.
169
170 =item * C<application/x-storable> => C<Data::Serializer>
171
172 Uses the L<Data::Serializer> module to generate L<Storable> output.
173
174 =item * C<application/x-freezethaw> => C<Data::Serializer>
175
176 Uses the L<Data::Serializer> module to generate L<FreezeThaw> 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 =back
230
231 By default, L<Catalyst::Controller::REST> will return a 
232 C<415 Unsupported Media Type> response if an attempt to use an unsupported
233 content-type is made.  You can ensure that something is always returned by
234 setting the C<default> config option:
235
236   __PACKAGE__->config(default => 'text/x-yaml');
237
238 would make it always fall back to the serializer plugin defined for
239 C<text/x-yaml>.
240
241 =head1 CUSTOM SERIALIZERS
242
243 Implementing new Serialization formats is easy!  Contributions
244 are most welcome!  If you would like to implement a custom serializer, 
245 you should create two new modules in the L<Catalyst::Action::Serialize>
246 and L<Catalyst::Action::Deserialize> namespace.  Then assign your new
247 class to the content-type's you want, and you're done.
248
249 See L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize> 
250 for more information.
251
252 =head1 STATUS HELPERS
253
254 Since so much of REST is in using HTTP, we provide these Status Helpers.
255 Using them will ensure that you are responding with the proper codes,
256 headers, and entities.
257
258 These helpers try and conform to the HTTP 1.1 Specification.  You can
259 refer to it at: L<http://www.w3.org/Protocols/rfc2616/rfc2616.txt>.
260 These routines are all implemented as regular subroutines, and as
261 such require you pass the current context ($c) as the first argument.
262
263 =over
264
265 =cut
266
267 BEGIN { extends 'Catalyst::Controller' }
268 use Params::Validate qw(SCALAR OBJECT);
269
270 __PACKAGE__->mk_accessors(qw(serialize));
271
272 __PACKAGE__->config(
273     'stash_key' => 'rest',
274     'map'       => {
275         'text/html'          => 'YAML::HTML',
276         'text/xml'           => 'XML::Simple',
277         'text/x-yaml'        => 'YAML',
278         'application/json'   => 'JSON',
279         'text/x-json'        => 'JSON',
280         'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
281         'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
282         'text/x-data-taxi'   => [ 'Data::Serializer', 'Data::Taxi'   ],
283         'application/x-storable'   => [ 'Data::Serializer', 'Storable' ],
284         'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
285         'text/x-config-general'    => [ 'Data::Serializer', 'Config::General' ],
286         'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
287     },
288 );
289
290 sub begin : ActionClass('Deserialize') { }
291
292 sub end : ActionClass('Serialize') { }
293
294 =item status_ok
295
296 Returns a "200 OK" response.  Takes an "entity" to serialize.
297
298 Example:
299
300   $self->status_ok(
301     $c,
302     entity => {
303         radiohead => "Is a good band!",
304     }
305   );
306
307 =cut
308
309 sub status_ok {
310     my $self = shift;
311     my $c    = shift;
312     my %p    = Params::Validate::validate( @_, { entity => 1, }, );
313
314     $c->response->status(200);
315     $self->_set_entity( $c, $p{'entity'} );
316     return 1;
317 }
318
319 =item status_created
320
321 Returns a "201 CREATED" response.  Takes an "entity" to serialize,
322 and a "location" where the created object can be found.
323
324 Example:
325
326   $self->status_created(
327     $c,
328     location => $c->req->uri->as_string,
329     entity => {
330         radiohead => "Is a good band!",
331     }
332   );
333
334 In the above example, we use the requested URI as our location.
335 This is probably what you want for most PUT requests.
336
337 =cut
338
339 sub status_created {
340     my $self = shift;
341     my $c    = shift;
342     my %p    = Params::Validate::validate(
343         @_,
344         {
345             location => { type     => SCALAR | OBJECT },
346             entity   => { optional => 1 },
347         },
348     );
349
350     my $location;
351     if ( ref( $p{'location'} ) ) {
352         $location = $p{'location'}->as_string;
353     } else {
354         $location = $p{'location'};
355     }
356     $c->response->status(201);
357     $c->response->header( 'Location' => $location );
358     $self->_set_entity( $c, $p{'entity'} );
359     return 1;
360 }
361
362 =item status_accepted
363
364 Returns a "202 ACCEPTED" response.  Takes an "entity" to serialize.
365
366 Example:
367
368   $self->status_accepted(
369     $c,
370     entity => {
371         status => "queued",
372     }
373   );
374
375 =cut
376
377 sub status_accepted {
378     my $self = shift;
379     my $c    = shift;
380     my %p    = Params::Validate::validate( @_, { entity => 1, }, );
381
382     $c->response->status(202);
383     $self->_set_entity( $c, $p{'entity'} );
384     return 1;
385 }
386
387 =item status_no_content
388
389 Returns a "204 NO CONTENT" response.
390
391 =cut
392
393 sub status_no_content {
394     my $self = shift;
395     my $c    = shift;
396     $c->response->status(204);
397     $self->_set_entity( $c, undef );
398     return 1.;
399 }
400
401 =item status_bad_request
402
403 Returns a "400 BAD REQUEST" response.  Takes a "message" argument
404 as a scalar, which will become the value of "error" in the serialized
405 response.
406
407 Example:
408
409   $self->status_bad_request(
410     $c,
411     message => "Cannot do what you have asked!",
412   );
413
414 =cut
415
416 sub status_bad_request {
417     my $self = shift;
418     my $c    = shift;
419     my %p    = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
420
421     $c->response->status(400);
422     $c->log->debug( "Status Bad Request: " . $p{'message'} ) if $c->debug;
423     $self->_set_entity( $c, { error => $p{'message'} } );
424     return 1;
425 }
426
427 =item status_not_found
428
429 Returns a "404 NOT FOUND" response.  Takes a "message" argument
430 as a scalar, which will become the value of "error" in the serialized
431 response.
432
433 Example:
434
435   $self->status_not_found(
436     $c,
437     message => "Cannot find what you were looking for!",
438   );
439
440 =cut
441
442 sub status_not_found {
443     my $self = shift;
444     my $c    = shift;
445     my %p    = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
446
447     $c->response->status(404);
448     $c->log->debug( "Status Not Found: " . $p{'message'} ) if $c->debug;
449     $self->_set_entity( $c, { error => $p{'message'} } );
450     return 1;
451 }
452
453 =item gone
454
455 Returns a "41O GONE" response.  Takes a "message" argument as a scalar,
456 which will become the value of "error" in the serialized response.
457
458 Example:
459
460   $self->status_gone(
461     $c,
462     message => "The document have been deleted by foo",
463   );
464
465 =cut
466
467 sub status_gone {
468     my $self = shift;
469     my $c    = shift;
470     my %p    = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
471
472     $c->response->status(410);
473     $c->log->debug( "Status Gone " . $p{'message'} ) if $c->debug;
474     $self->_set_entity( $c, { error => $p{'message'} } );
475     return 1;
476 }
477
478 sub _set_entity {
479     my $self   = shift;
480     my $c      = shift;
481     my $entity = shift;
482     if ( defined($entity) ) {
483         $c->stash->{ $self->{'stash_key'} } = $entity;
484     }
485     return 1;
486 }
487
488 =back
489
490 =head1 MANUAL RESPONSES
491
492 If you want to construct your responses yourself, all you need to
493 do is put the object you want serialized in $c->stash->{'rest'}.
494
495 =head1 IMPLEMENTATION DETAILS
496
497 This Controller ties together L<Catalyst::Action::REST>,
498 L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>.  It should be suitable for most applications.  You should be aware that it:
499
500 =over 4
501
502 =item Configures the Serialization Actions
503
504 This class provides a default configuration for Serialization.  It is currently:
505
506   __PACKAGE__->config(
507       'stash_key' => 'rest',
508       'map'       => {
509          'text/html'          => 'YAML::HTML',
510          'text/xml'           => 'XML::Simple',
511          'text/x-yaml'        => 'YAML',
512          'application/json'   => 'JSON',
513          'text/x-json'        => 'JSON',
514          'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
515          'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
516          'text/x-data-taxi'   => [ 'Data::Serializer', 'Data::Taxi'   ],
517          'application/x-storable'   => [ 'Data::Serializer', 'Storable' ],
518          'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
519          'text/x-config-general'    => [ 'Data::Serializer', 'Config::General' ],
520          'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
521       },
522   );
523
524 You can read the full set of options for this configuration block in
525 L<Catalyst::Action::Serialize>.
526
527 =item Sets a C<begin> and C<end> method for you
528
529 The C<begin> method uses L<Catalyst::Action::Deserialize>.  The C<end>
530 method uses L<Catalyst::Action::Serialize>.  If you want to override
531 either behavior, simply implement your own C<begin> and C<end> actions
532 and use MRO::Compat:
533
534   package Foo::Controller::Monkey;
535   use Moose;
536   use namespace::autoclean;
537   
538   BEGIN { extends 'Catalyst::Controller::REST' }
539
540   sub begin :Private {
541     my ($self, $c) = @_;
542     ... do things before Deserializing ...
543     $self->maybe::next::method($c);
544     ... do things after Deserializing ...
545   }
546
547   sub end :Private {
548     my ($self, $c) = @_;
549     ... do things before Serializing ...
550     $self->maybe::next::method($c);
551     ... do things after Serializing ...
552   }
553
554 =back
555
556 =head1 A MILD WARNING
557
558 I have code in production using L<Catalyst::Controller::REST>.  That said,
559 it is still under development, and it's possible that things may change
560 between releases.  I promise to not break things unnecessarily. :)
561
562 =head1 SEE ALSO
563
564 L<Catalyst::Action::REST>, L<Catalyst::Action::Serialize>,
565 L<Catalyst::Action::Deserialize>
566
567 For help with REST in general:
568
569 The HTTP 1.1 Spec is required reading. http://www.w3.org/Protocols/rfc2616/rfc2616.txt
570
571 Wikipedia! http://en.wikipedia.org/wiki/Representational_State_Transfer
572
573 The REST Wiki: http://rest.blueoxen.net/cgi-bin/wiki.pl?FrontPage
574
575 =head1 AUTHORS
576
577 See L<Catalyst::Action::REST> for authors.
578
579 =head1 LICENSE
580
581 You may distribute this code under the same terms as Perl itself.
582
583 =cut
584
585 1;