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