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