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