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