Add explicit 1;
[catagits/Catalyst-Action-REST.git] / lib / Catalyst / Controller / REST.pm
CommitLineData
256c894f 1package Catalyst::Controller::REST;
930013e6 2use Moose;
3use namespace::autoclean;
256c894f 4
a9e5f3d2 5our $VERSION = '0.88';
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
26b59bcb 141to hyperlinks. Only usable for Serialization.
e601adda 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
838f49dc 149You can also add a hash in your controller config to pass options to the json object.
150For instance, to relax permissions when deserializing input, add:
151 __PACKAGE__->config(
152 json_options => { relaxed => 1 }
153 )
154
d0d292d4 155=item * C<text/javascript> => C<JSONP>
156
157If a callback=? parameter is passed, this returns javascript in the form of: $callback($serializedJSON);
158
92d78e8f 159Note - this is disabled by default as it can be a security risk if you are unaware.
160
161The usual MIME types for this serialization format are: 'text/javascript', 'application/x-javascript',
162'application/javascript'.
163
95318468 164=item * C<text/x-data-dumper> => C<Data::Serializer>
e601adda 165
166Uses the L<Data::Serializer> module to generate L<Data::Dumper> output.
167
95318468 168=item * C<text/x-data-denter> => C<Data::Serializer>
e601adda 169
170Uses the L<Data::Serializer> module to generate L<Data::Denter> output.
171
95318468 172=item * C<text/x-data-taxi> => C<Data::Serializer>
e601adda 173
174Uses the L<Data::Serializer> module to generate L<Data::Taxi> output.
175
95318468 176=item * C<application/x-storable> => C<Data::Serializer>
e601adda 177
178Uses the L<Data::Serializer> module to generate L<Storable> output.
179
95318468 180=item * C<application/x-freezethaw> => C<Data::Serializer>
e601adda 181
182Uses the L<Data::Serializer> module to generate L<FreezeThaw> output.
183
95318468 184=item * C<text/x-config-general> => C<Data::Serializer>
e601adda 185
186Uses the L<Data::Serializer> module to generate L<Config::General> output.
187
95318468 188=item * C<text/x-php-serialization> => C<Data::Serializer>
e601adda 189
190Uses the L<Data::Serializer> module to generate L<PHP::Serialization> output.
191
95318468 192=item * C<text/xml> => C<XML::Simple>
e601adda 193
194Uses L<XML::Simple> to generate XML output. This is probably not suitable
195for any real heavy XML work. Due to L<XML::Simple>s requirement that the data
196you serialize be a HASHREF, we transform outgoing data to be in the form of:
197
198 { data => $yourdata }
199
95318468 200=item * L<View>
9a76221e 201
db8bb647 202Uses a regular Catalyst view. For example, if you wanted to have your
3d8a0645 203C<text/html> and C<text/xml> views rendered by TT, set:
204
205 __PACKAGE__->config(
206 map => {
207 'text/html' => [ 'View', 'TT' ],
208 'text/xml' => [ 'View', 'XML' ],
209 }
5cb5f6bb 210 );
3d8a0645 211
212Your views should have a C<process> method like this:
213
214 sub process {
215 my ( $self, $c, $stash_key ) = @_;
5cb5f6bb 216
3d8a0645 217 my $output;
218 eval {
219 $output = $self->serialize( $c->stash->{$stash_key} );
220 };
221 return $@ if $@;
5cb5f6bb 222
3d8a0645 223 $c->response->body( $output );
224 return 1; # important
225 }
226
227 sub serialize {
228 my ( $self, $data ) = @_;
5cb5f6bb 229
3d8a0645 230 my $serialized = ... process $data here ...
5cb5f6bb 231
3d8a0645 232 return $serialized;
233 }
9a76221e 234
e601adda 235=back
236
95318468 237By default, L<Catalyst::Controller::REST> will return a
238C<415 Unsupported Media Type> response if an attempt to use an unsupported
239content-type is made. You can ensure that something is always returned by
240setting the C<default> config option:
398c5a1b 241
5cb5f6bb 242 __PACKAGE__->config(default => 'text/x-yaml');
398c5a1b 243
95318468 244would make it always fall back to the serializer plugin defined for
245C<text/x-yaml>.
398c5a1b 246
e601adda 247=head1 CUSTOM SERIALIZERS
248
95318468 249Implementing new Serialization formats is easy! Contributions
250are most welcome! If you would like to implement a custom serializer,
251you should create two new modules in the L<Catalyst::Action::Serialize>
252and L<Catalyst::Action::Deserialize> namespace. Then assign your new
253class to the content-type's you want, and you're done.
254
255See L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>
256for more information.
e601adda 257
398c5a1b 258=head1 STATUS HELPERS
259
e601adda 260Since so much of REST is in using HTTP, we provide these Status Helpers.
261Using them will ensure that you are responding with the proper codes,
262headers, and entities.
263
398c5a1b 264These helpers try and conform to the HTTP 1.1 Specification. You can
db8bb647 265refer to it at: L<http://www.w3.org/Protocols/rfc2616/rfc2616.txt>.
398c5a1b 266These routines are all implemented as regular subroutines, and as
267such require you pass the current context ($c) as the first argument.
268
5cb5f6bb 269=over
398c5a1b 270
271=cut
272
930013e6 273BEGIN { extends 'Catalyst::Controller' }
d4611771 274use Params::Validate qw(SCALAR OBJECT);
256c894f 275
276__PACKAGE__->mk_accessors(qw(serialize));
277
278__PACKAGE__->config(
e540a1fa 279 'stash_key' => 'rest',
280 'map' => {
281 'text/html' => 'YAML::HTML',
282 'text/xml' => 'XML::Simple',
283 'text/x-yaml' => 'YAML',
284 'application/json' => 'JSON',
285 'text/x-json' => 'JSON',
286 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
287 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
288 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
95318468 289 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
290 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
291 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
e540a1fa 292 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
293 },
256c894f 294);
295
e540a1fa 296sub begin : ActionClass('Deserialize') { }
5511d1ff 297
0ba73721 298sub end : ActionClass('Serialize') { }
299
398c5a1b 300=item status_ok
301
302Returns a "200 OK" response. Takes an "entity" to serialize.
303
304Example:
305
306 $self->status_ok(
db8bb647 307 $c,
398c5a1b 308 entity => {
309 radiohead => "Is a good band!",
310 }
311 );
312
313=cut
314
315sub status_ok {
316 my $self = shift;
e601adda 317 my $c = shift;
d4611771 318 my %p = Params::Validate::validate( @_, { entity => 1, }, );
398c5a1b 319
320 $c->response->status(200);
e601adda 321 $self->_set_entity( $c, $p{'entity'} );
398c5a1b 322 return 1;
323}
324
325=item status_created
326
327Returns a "201 CREATED" response. Takes an "entity" to serialize,
328and a "location" where the created object can be found.
329
330Example:
331
332 $self->status_created(
db8bb647 333 $c,
398c5a1b 334 location => $c->req->uri->as_string,
335 entity => {
336 radiohead => "Is a good band!",
337 }
338 );
339
340In the above example, we use the requested URI as our location.
341This is probably what you want for most PUT requests.
342
343=cut
bb4130f6 344
5511d1ff 345sub status_created {
346 my $self = shift;
e601adda 347 my $c = shift;
d4611771 348 my %p = Params::Validate::validate(
e601adda 349 @_,
5511d1ff 350 {
e601adda 351 location => { type => SCALAR | OBJECT },
352 entity => { optional => 1 },
5511d1ff 353 },
354 );
256c894f 355
5511d1ff 356 my $location;
e601adda 357 if ( ref( $p{'location'} ) ) {
5511d1ff 358 $location = $p{'location'}->as_string;
33e5de96 359 } else {
360 $location = $p{'location'};
5511d1ff 361 }
362 $c->response->status(201);
e601adda 363 $c->response->header( 'Location' => $location );
364 $self->_set_entity( $c, $p{'entity'} );
bb4130f6 365 return 1;
366}
367
398c5a1b 368=item status_accepted
369
370Returns a "202 ACCEPTED" response. Takes an "entity" to serialize.
371
372Example:
373
374 $self->status_accepted(
db8bb647 375 $c,
398c5a1b 376 entity => {
377 status => "queued",
378 }
379 );
380
381=cut
e601adda 382
398c5a1b 383sub status_accepted {
bb4130f6 384 my $self = shift;
e601adda 385 my $c = shift;
d4611771 386 my %p = Params::Validate::validate( @_, { entity => 1, }, );
bb4130f6 387
398c5a1b 388 $c->response->status(202);
e601adda 389 $self->_set_entity( $c, $p{'entity'} );
bb4130f6 390 return 1;
391}
392
bbf0feae 393=item status_no_content
394
395Returns a "204 NO CONTENT" response.
396
397=cut
398
399sub status_no_content {
400 my $self = shift;
401 my $c = shift;
402 $c->response->status(204);
403 $self->_set_entity( $c, undef );
404 return 1.;
405}
406
bdff70a9 407=item status_multiple_choices
408
409Returns a "300 MULTIPLE CHOICES" response. Takes an "entity" to serialize, which should
410provide list of possible locations. Also takes optional "location" for preferred choice.
411
412=cut
413
414sub status_multiple_choices {
415 my $self = shift;
416 my $c = shift;
417 my %p = Params::Validate::validate(
418 @_,
419 {
420 entity => 1,
421 location => { type => SCALAR | OBJECT, optional => 1 },
422 },
423 );
424
425 my $location;
426 if ( ref( $p{'location'} ) ) {
427 $location = $p{'location'}->as_string;
428 } else {
429 $location = $p{'location'};
430 }
431 $c->response->status(300);
432 $c->response->header( 'Location' => $location ) if exists $p{'location'};
433 $self->_set_entity( $c, $p{'entity'} );
434 return 1;
435}
436
398c5a1b 437=item status_bad_request
438
439Returns a "400 BAD REQUEST" response. Takes a "message" argument
440as a scalar, which will become the value of "error" in the serialized
441response.
442
443Example:
444
445 $self->status_bad_request(
db8bb647 446 $c,
33e5de96 447 message => "Cannot do what you have asked!",
398c5a1b 448 );
449
450=cut
e601adda 451
cc186a5b 452sub status_bad_request {
453 my $self = shift;
e601adda 454 my $c = shift;
d4611771 455 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
cc186a5b 456
457 $c->response->status(400);
faf5c20b 458 $c->log->debug( "Status Bad Request: " . $p{'message'} ) if $c->debug;
e601adda 459 $self->_set_entity( $c, { error => $p{'message'} } );
cc186a5b 460 return 1;
461}
462
398c5a1b 463=item status_not_found
464
465Returns a "404 NOT FOUND" response. Takes a "message" argument
466as a scalar, which will become the value of "error" in the serialized
467response.
468
469Example:
470
471 $self->status_not_found(
db8bb647 472 $c,
33e5de96 473 message => "Cannot find what you were looking for!",
398c5a1b 474 );
475
476=cut
e601adda 477
bb4130f6 478sub status_not_found {
479 my $self = shift;
e601adda 480 my $c = shift;
d4611771 481 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
bb4130f6 482
483 $c->response->status(404);
faf5c20b 484 $c->log->debug( "Status Not Found: " . $p{'message'} ) if $c->debug;
e601adda 485 $self->_set_entity( $c, { error => $p{'message'} } );
bb4130f6 486 return 1;
487}
488
bbf0feae 489=item gone
490
491Returns a "41O GONE" response. Takes a "message" argument as a scalar,
492which will become the value of "error" in the serialized response.
493
494Example:
495
496 $self->status_gone(
497 $c,
498 message => "The document have been deleted by foo",
499 );
500
501=cut
502
503sub status_gone {
504 my $self = shift;
505 my $c = shift;
506 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
507
508 $c->response->status(410);
509 $c->log->debug( "Status Gone " . $p{'message'} ) if $c->debug;
510 $self->_set_entity( $c, { error => $p{'message'} } );
511 return 1;
512}
513
bb4130f6 514sub _set_entity {
e601adda 515 my $self = shift;
516 my $c = shift;
bb4130f6 517 my $entity = shift;
e601adda 518 if ( defined($entity) ) {
faf5c20b 519 $c->stash->{ $self->{'stash_key'} } = $entity;
5511d1ff 520 }
521 return 1;
eccb2137 522}
256c894f 523
398c5a1b 524=back
525
526=head1 MANUAL RESPONSES
527
528If you want to construct your responses yourself, all you need to
529do is put the object you want serialized in $c->stash->{'rest'}.
530
e601adda 531=head1 IMPLEMENTATION DETAILS
532
533This Controller ties together L<Catalyst::Action::REST>,
534L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>. It should be suitable for most applications. You should be aware that it:
535
536=over 4
537
538=item Configures the Serialization Actions
539
540This class provides a default configuration for Serialization. It is currently:
541
542 __PACKAGE__->config(
95318468 543 'stash_key' => 'rest',
544 'map' => {
545 'text/html' => 'YAML::HTML',
546 'text/xml' => 'XML::Simple',
547 'text/x-yaml' => 'YAML',
548 'application/json' => 'JSON',
549 'text/x-json' => 'JSON',
550 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
551 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
552 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
553 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
554 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
555 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
556 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
557 },
e601adda 558 );
559
560You can read the full set of options for this configuration block in
561L<Catalyst::Action::Serialize>.
562
563=item Sets a C<begin> and C<end> method for you
564
565The C<begin> method uses L<Catalyst::Action::Deserialize>. The C<end>
566method uses L<Catalyst::Action::Serialize>. If you want to override
567either behavior, simply implement your own C<begin> and C<end> actions
355d4385 568and forward to another action with the Serialize and/or Deserialize
569action classes:
e601adda 570
10bcd217 571 package Foo::Controller::Monkey;
572 use Moose;
573 use namespace::autoclean;
355d4385 574
10bcd217 575 BEGIN { extends 'Catalyst::Controller::REST' }
e601adda 576
355d4385 577 sub begin : Private {
e601adda 578 my ($self, $c) = @_;
db8bb647 579 ... do things before Deserializing ...
355d4385 580 $c->forward('deserialize');
e601adda 581 ... do things after Deserializing ...
db8bb647 582 }
e601adda 583
355d4385 584 sub deserialize : ActionClass('Deserialize') {}
585
e601adda 586 sub end :Private {
587 my ($self, $c) = @_;
db8bb647 588 ... do things before Serializing ...
355d4385 589 $c->forward('serialize');
e601adda 590 ... do things after Serializing ...
591 }
592
355d4385 593 sub serialize : ActionClass('Serialize') {}
594
e540a1fa 595=back
596
e601adda 597=head1 A MILD WARNING
598
599I have code in production using L<Catalyst::Controller::REST>. That said,
600it is still under development, and it's possible that things may change
d6ece98c 601between releases. I promise to not break things unnecessarily. :)
e601adda 602
398c5a1b 603=head1 SEE ALSO
604
605L<Catalyst::Action::REST>, L<Catalyst::Action::Serialize>,
606L<Catalyst::Action::Deserialize>
607
608For help with REST in general:
609
610The HTTP 1.1 Spec is required reading. http://www.w3.org/Protocols/rfc2616/rfc2616.txt
611
612Wikipedia! http://en.wikipedia.org/wiki/Representational_State_Transfer
613
614The REST Wiki: http://rest.blueoxen.net/cgi-bin/wiki.pl?FrontPage
615
5cb5f6bb 616=head1 AUTHORS
e540a1fa 617
5cb5f6bb 618See L<Catalyst::Action::REST> for authors.
e540a1fa 619
398c5a1b 620=head1 LICENSE
621
622You may distribute this code under the same terms as Perl itself.
623
624=cut
625
256c894f 6261;