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