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