FIXUP
[catagits/Catalyst-Action-REST.git] / lib / Catalyst / Controller / REST.pm
CommitLineData
256c894f 1package Catalyst::Controller::REST;
930013e6 2use Moose;
3use namespace::autoclean;
256c894f 4
7cc6122a 5our $VERSION = '1.12';
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;
259c53c7 17
5cb5f6bb 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 {
ace04991 39 my ( $self, $c ) = @_;
40
fcf45ed9 41 $radiohead = $c->req->data->{radiohead};
259c53c7 42
10bcd217 43 $self->status_created(
44 $c,
259c53c7 45 location => $c->req->uri,
10bcd217 46 entity => {
47 radiohead => $radiohead,
48 }
49 );
259c53c7 50 }
398c5a1b 51
52=head1 DESCRIPTION
53
54Catalyst::Controller::REST implements a mechanism for building
55RESTful services in Catalyst. It does this by extending the
db8bb647 56normal Catalyst dispatch mechanism to allow for different
57subroutines to be called based on the HTTP Method requested,
398c5a1b 58while also transparently handling all the serialization/deserialization for
59you.
60
61This is probably best served by an example. In the above
62controller, we have declared a Local Catalyst action on
db8bb647 63"sub thing", and have used the ActionClass('REST').
398c5a1b 64
65Below, we have declared "thing_GET" and "thing_PUT". Any
db8bb647 66GET requests to thing will be dispatched to "thing_GET",
67while any PUT requests will be dispatched to "thing_PUT".
398c5a1b 68
e601adda 69Any unimplemented HTTP methods will be met with a "405 Method Not Allowed"
70response, automatically containing the proper list of available methods. You
71can override this behavior through implementing a custom
db8bb647 72C<thing_not_implemented> method.
e601adda 73
74If you do not provide an OPTIONS handler, we will respond to any OPTIONS
75requests with a "200 OK", populating the Allowed header automatically.
76
77Any data included in C<< $c->stash->{'rest'} >> will be serialized for you.
78The serialization format will be selected based on the content-type
79of the incoming request. It is probably easier to use the L<STATUS HELPERS>,
80which are described below.
398c5a1b 81
10bcd217 82"The HTTP POST, PUT, and OPTIONS methods will all automatically
83L<deserialize|Catalyst::Action::Deserialize> the contents of
259c53c7 84C<< $c->request->body >> into the C<< $c->request->data >> hashref", based on
10bcd217 85the request's C<Content-type> header. A list of understood serialization
86formats is L<below|/AVAILABLE SERIALIZERS>.
398c5a1b 87
e601adda 88If we do not have (or cannot run) a serializer for a given content-type, a 415
db8bb647 89"Unsupported Media Type" error is generated.
398c5a1b 90
91To make your Controller RESTful, simply have it
92
5cb5f6bb 93 BEGIN { extends 'Catalyst::Controller::REST' }
398c5a1b 94
9cd203c9 95=head1 CONFIGURATION
96
97See L<Catalyst::Action::Serialize/CONFIGURATION>. Note that the C<serialize>
98key has been deprecated.
99
398c5a1b 100=head1 SERIALIZATION
101
102Catalyst::Controller::REST will automatically serialize your
e601adda 103responses, and deserialize any POST, PUT or OPTIONS requests. It evaluates
104which serializer to use by mapping a content-type to a Serialization module.
db8bb647 105We select the content-type based on:
e601adda 106
5cb5f6bb 107=over
e601adda 108
109=item B<The Content-Type Header>
110
111If the incoming HTTP Request had a Content-Type header set, we will use it.
112
113=item B<The content-type Query Parameter>
114
115If this is a GET request, you can supply a content-type query parameter.
116
117=item B<Evaluating the Accept Header>
118
119Finally, if the client provided an Accept header, we will evaluate
db8bb647 120it and use the best-ranked choice.
e601adda 121
122=back
123
124=head1 AVAILABLE SERIALIZERS
125
126A given serialization mechanism is only available if you have the underlying
127modules installed. For example, you can't use XML::Simple if it's not already
db8bb647 128installed.
e601adda 129
95318468 130In addition, each serializer has its quirks in terms of what sorts of data
e601adda 131structures it will properly handle. L<Catalyst::Controller::REST> makes
db8bb647 132no attempt to save you from yourself in this regard. :)
e601adda 133
134=over 2
135
95318468 136=item * C<text/x-yaml> => C<YAML::Syck>
e601adda 137
138Returns YAML generated by L<YAML::Syck>.
139
95318468 140=item * C<text/html> => C<YAML::HTML>
e601adda 141
142This uses L<YAML::Syck> and L<URI::Find> to generate YAML with all URLs turned
26b59bcb 143to hyperlinks. Only usable for Serialization.
e601adda 144
95318468 145=item * C<application/json> => C<JSON>
e601adda 146
db8bb647 147Uses L<JSON> to generate JSON output. It is strongly advised to also have
e540a1fa 148L<JSON::XS> installed. The C<text/x-json> content type is supported but is
149deprecated and you will receive warnings in your log.
e601adda 150
838f49dc 151You can also add a hash in your controller config to pass options to the json object.
152For instance, to relax permissions when deserializing input, add:
153 __PACKAGE__->config(
154 json_options => { relaxed => 1 }
155 )
156
d0d292d4 157=item * C<text/javascript> => C<JSONP>
158
159If a callback=? parameter is passed, this returns javascript in the form of: $callback($serializedJSON);
160
92d78e8f 161Note - this is disabled by default as it can be a security risk if you are unaware.
162
163The usual MIME types for this serialization format are: 'text/javascript', 'application/x-javascript',
164'application/javascript'.
165
95318468 166=item * C<text/x-data-dumper> => C<Data::Serializer>
e601adda 167
168Uses the L<Data::Serializer> module to generate L<Data::Dumper> output.
169
95318468 170=item * C<text/x-data-denter> => C<Data::Serializer>
e601adda 171
172Uses the L<Data::Serializer> module to generate L<Data::Denter> output.
173
95318468 174=item * C<text/x-data-taxi> => C<Data::Serializer>
e601adda 175
176Uses the L<Data::Serializer> module to generate L<Data::Taxi> output.
177
95318468 178=item * C<text/x-config-general> => C<Data::Serializer>
e601adda 179
180Uses the L<Data::Serializer> module to generate L<Config::General> output.
181
95318468 182=item * C<text/x-php-serialization> => C<Data::Serializer>
e601adda 183
184Uses the L<Data::Serializer> module to generate L<PHP::Serialization> output.
185
95318468 186=item * C<text/xml> => C<XML::Simple>
e601adda 187
188Uses L<XML::Simple> to generate XML output. This is probably not suitable
189for any real heavy XML work. Due to L<XML::Simple>s requirement that the data
190you serialize be a HASHREF, we transform outgoing data to be in the form of:
191
192 { data => $yourdata }
193
95318468 194=item * L<View>
9a76221e 195
db8bb647 196Uses a regular Catalyst view. For example, if you wanted to have your
3d8a0645 197C<text/html> and C<text/xml> views rendered by TT, set:
198
199 __PACKAGE__->config(
200 map => {
201 'text/html' => [ 'View', 'TT' ],
202 'text/xml' => [ 'View', 'XML' ],
203 }
5cb5f6bb 204 );
3d8a0645 205
206Your views should have a C<process> method like this:
207
208 sub process {
209 my ( $self, $c, $stash_key ) = @_;
5cb5f6bb 210
3d8a0645 211 my $output;
212 eval {
213 $output = $self->serialize( $c->stash->{$stash_key} );
214 };
215 return $@ if $@;
5cb5f6bb 216
3d8a0645 217 $c->response->body( $output );
218 return 1; # important
219 }
259c53c7 220
3d8a0645 221 sub serialize {
222 my ( $self, $data ) = @_;
5cb5f6bb 223
3d8a0645 224 my $serialized = ... process $data here ...
5cb5f6bb 225
3d8a0645 226 return $serialized;
227 }
9a76221e 228
178f8470 229=item * Callback
230
231For infinite flexibility, you can provide a callback for the
232deserialization/serialization steps.
233
234 __PACKAGE__->config(
235 map => {
236 'text/xml' => [ 'Callback', { deserialize => \&parse_xml, serialize => \&render_xml } ],
237 }
238 );
239
240The C<deserialize> callback is passed a string that is the body of the
241request and is expected to return a scalar value that results from
242the deserialization. The C<serialize> callback is passed the data
243structure that needs to be serialized and must return a string suitable
244for returning in the HTTP response. In addition to receiving the scalar
245to act on, both callbacks are passed the controller object and the context
246(i.e. C<$c>) as the second and third arguments.
247
e601adda 248=back
249
259c53c7 250By default, L<Catalyst::Controller::REST> will return a
95318468 251C<415 Unsupported Media Type> response if an attempt to use an unsupported
252content-type is made. You can ensure that something is always returned by
253setting the C<default> config option:
398c5a1b 254
5cb5f6bb 255 __PACKAGE__->config(default => 'text/x-yaml');
398c5a1b 256
95318468 257would make it always fall back to the serializer plugin defined for
258C<text/x-yaml>.
398c5a1b 259
e601adda 260=head1 CUSTOM SERIALIZERS
261
95318468 262Implementing new Serialization formats is easy! Contributions
259c53c7 263are most welcome! If you would like to implement a custom serializer,
95318468 264you should create two new modules in the L<Catalyst::Action::Serialize>
265and L<Catalyst::Action::Deserialize> namespace. Then assign your new
266class to the content-type's you want, and you're done.
267
259c53c7 268See L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>
95318468 269for more information.
e601adda 270
398c5a1b 271=head1 STATUS HELPERS
272
e601adda 273Since so much of REST is in using HTTP, we provide these Status Helpers.
274Using them will ensure that you are responding with the proper codes,
275headers, and entities.
276
398c5a1b 277These helpers try and conform to the HTTP 1.1 Specification. You can
db8bb647 278refer to it at: L<http://www.w3.org/Protocols/rfc2616/rfc2616.txt>.
398c5a1b 279These routines are all implemented as regular subroutines, and as
280such require you pass the current context ($c) as the first argument.
281
5cb5f6bb 282=over
398c5a1b 283
284=cut
285
930013e6 286BEGIN { extends 'Catalyst::Controller' }
d4611771 287use Params::Validate qw(SCALAR OBJECT);
256c894f 288
289__PACKAGE__->mk_accessors(qw(serialize));
290
291__PACKAGE__->config(
e540a1fa 292 'stash_key' => 'rest',
293 'map' => {
e540a1fa 294 'text/xml' => 'XML::Simple',
e540a1fa 295 'application/json' => 'JSON',
296 'text/x-json' => 'JSON',
e540a1fa 297 },
256c894f 298);
299
e540a1fa 300sub begin : ActionClass('Deserialize') { }
5511d1ff 301
0ba73721 302sub end : ActionClass('Serialize') { }
303
398c5a1b 304=item status_ok
305
306Returns a "200 OK" response. Takes an "entity" to serialize.
307
308Example:
309
310 $self->status_ok(
db8bb647 311 $c,
398c5a1b 312 entity => {
313 radiohead => "Is a good band!",
314 }
315 );
316
317=cut
318
319sub status_ok {
320 my $self = shift;
e601adda 321 my $c = shift;
d4611771 322 my %p = Params::Validate::validate( @_, { entity => 1, }, );
398c5a1b 323
324 $c->response->status(200);
e601adda 325 $self->_set_entity( $c, $p{'entity'} );
398c5a1b 326 return 1;
327}
328
329=item status_created
330
331Returns a "201 CREATED" response. Takes an "entity" to serialize,
332and a "location" where the created object can be found.
333
334Example:
335
336 $self->status_created(
db8bb647 337 $c,
259c53c7 338 location => $c->req->uri,
398c5a1b 339 entity => {
340 radiohead => "Is a good band!",
341 }
342 );
343
344In the above example, we use the requested URI as our location.
345This is probably what you want for most PUT requests.
346
347=cut
bb4130f6 348
5511d1ff 349sub status_created {
350 my $self = shift;
e601adda 351 my $c = shift;
d4611771 352 my %p = Params::Validate::validate(
e601adda 353 @_,
5511d1ff 354 {
e601adda 355 location => { type => SCALAR | OBJECT },
356 entity => { optional => 1 },
5511d1ff 357 },
358 );
256c894f 359
5511d1ff 360 $c->response->status(201);
259c53c7 361 $c->response->header( 'Location' => $p{location} );
e601adda 362 $self->_set_entity( $c, $p{'entity'} );
bb4130f6 363 return 1;
364}
365
398c5a1b 366=item status_accepted
367
368Returns a "202 ACCEPTED" response. Takes an "entity" to serialize.
259c53c7 369Also takes optional "location" for queue type scenarios.
398c5a1b 370
371Example:
372
373 $self->status_accepted(
db8bb647 374 $c,
259c53c7 375 location => $c->req->uri,
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;
259c53c7 386 my %p = Params::Validate::validate(
387 @_,
388 {
389 location => { type => SCALAR | OBJECT, optional => 1 },
390 entity => 1,
391 },
392 );
bb4130f6 393
398c5a1b 394 $c->response->status(202);
259c53c7 395 $c->response->header( 'Location' => $p{location} ) if exists $p{location};
e601adda 396 $self->_set_entity( $c, $p{'entity'} );
bb4130f6 397 return 1;
398}
399
bbf0feae 400=item status_no_content
401
402Returns a "204 NO CONTENT" response.
403
404=cut
405
406sub status_no_content {
407 my $self = shift;
408 my $c = shift;
409 $c->response->status(204);
410 $self->_set_entity( $c, undef );
042656b6 411 return 1;
bbf0feae 412}
413
bdff70a9 414=item status_multiple_choices
415
416Returns a "300 MULTIPLE CHOICES" response. Takes an "entity" to serialize, which should
417provide list of possible locations. Also takes optional "location" for preferred choice.
418
419=cut
420
421sub status_multiple_choices {
422 my $self = shift;
423 my $c = shift;
424 my %p = Params::Validate::validate(
425 @_,
426 {
427 entity => 1,
428 location => { type => SCALAR | OBJECT, optional => 1 },
429 },
430 );
431
bdff70a9 432 $c->response->status(300);
259c53c7 433 $c->response->header( 'Location' => $p{location} ) if exists $p{'location'};
bdff70a9 434 $self->_set_entity( $c, $p{'entity'} );
435 return 1;
436}
437
e52456a4 438=item status_found
439
440Returns a "302 FOUND" response. Takes an "entity" to serialize.
259c53c7 441Also takes optional "location".
e52456a4 442
443=cut
444
445sub status_found {
446 my $self = shift;
447 my $c = shift;
448 my %p = Params::Validate::validate(
449 @_,
450 {
451 entity => 1,
452 location => { type => SCALAR | OBJECT, optional => 1 },
453 },
454 );
455
e52456a4 456 $c->response->status(302);
259c53c7 457 $c->response->header( 'Location' => $p{location} ) if exists $p{'location'};
e52456a4 458 $self->_set_entity( $c, $p{'entity'} );
459 return 1;
460}
461
b71ad3a4 462=item status_not_modified
463
464Returns a "304 NOT MODIFIED" response.
465
466=cut
467
5ad39b51 468sub status_not_modified {
b71ad3a4 469 my $self = shift;
470 my $c = shift;
471
472 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
473
474 $c->response->status(304);
475 $c->log->debug( "Status Not Modified: " . $p{'message'} ) if $c->debug;
476 $self->_set_entity( $c, { error => $p{'message'} } );
477 return 1;
478 }
479
398c5a1b 480=item status_bad_request
481
482Returns a "400 BAD REQUEST" response. Takes a "message" argument
483as a scalar, which will become the value of "error" in the serialized
484response.
485
486Example:
487
488 $self->status_bad_request(
db8bb647 489 $c,
33e5de96 490 message => "Cannot do what you have asked!",
398c5a1b 491 );
492
493=cut
e601adda 494
cc186a5b 495sub status_bad_request {
496 my $self = shift;
e601adda 497 my $c = shift;
d4611771 498 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
cc186a5b 499
500 $c->response->status(400);
faf5c20b 501 $c->log->debug( "Status Bad Request: " . $p{'message'} ) if $c->debug;
e601adda 502 $self->_set_entity( $c, { error => $p{'message'} } );
cc186a5b 503 return 1;
504}
505
550807bc 506=item status_forbidden
507
508Returns a "403 FORBIDDEN" response. Takes a "message" argument
509as a scalar, which will become the value of "error" in the serialized
510response.
511
512Example:
513
514 $self->status_forbidden(
515 $c,
516 message => "access denied",
517 );
518
519=cut
520
521sub status_forbidden {
522 my $self = shift;
523 my $c = shift;
524 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
525
526 $c->response->status(403);
527 $c->log->debug( "Status Forbidden: " . $p{'message'} ) if $c->debug;
528 $self->_set_entity( $c, { error => $p{'message'} } );
529 return 1;
530}
531
398c5a1b 532=item status_not_found
533
534Returns a "404 NOT FOUND" response. Takes a "message" argument
535as a scalar, which will become the value of "error" in the serialized
536response.
537
538Example:
539
540 $self->status_not_found(
db8bb647 541 $c,
33e5de96 542 message => "Cannot find what you were looking for!",
398c5a1b 543 );
544
545=cut
e601adda 546
bb4130f6 547sub status_not_found {
548 my $self = shift;
e601adda 549 my $c = shift;
d4611771 550 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
bb4130f6 551
552 $c->response->status(404);
faf5c20b 553 $c->log->debug( "Status Not Found: " . $p{'message'} ) if $c->debug;
e601adda 554 $self->_set_entity( $c, { error => $p{'message'} } );
bb4130f6 555 return 1;
556}
557
bbf0feae 558=item gone
559
560Returns a "41O GONE" response. Takes a "message" argument as a scalar,
561which will become the value of "error" in the serialized response.
562
563Example:
564
565 $self->status_gone(
566 $c,
567 message => "The document have been deleted by foo",
568 );
569
570=cut
571
572sub status_gone {
573 my $self = shift;
574 my $c = shift;
575 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
576
577 $c->response->status(410);
578 $c->log->debug( "Status Gone " . $p{'message'} ) if $c->debug;
579 $self->_set_entity( $c, { error => $p{'message'} } );
580 return 1;
581}
582
bb4130f6 583sub _set_entity {
e601adda 584 my $self = shift;
585 my $c = shift;
bb4130f6 586 my $entity = shift;
e601adda 587 if ( defined($entity) ) {
faf5c20b 588 $c->stash->{ $self->{'stash_key'} } = $entity;
5511d1ff 589 }
590 return 1;
eccb2137 591}
256c894f 592
398c5a1b 593=back
594
595=head1 MANUAL RESPONSES
596
597If you want to construct your responses yourself, all you need to
598do is put the object you want serialized in $c->stash->{'rest'}.
599
e601adda 600=head1 IMPLEMENTATION DETAILS
601
602This Controller ties together L<Catalyst::Action::REST>,
603L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>. It should be suitable for most applications. You should be aware that it:
604
605=over 4
606
607=item Configures the Serialization Actions
608
609This class provides a default configuration for Serialization. It is currently:
610
611 __PACKAGE__->config(
95318468 612 'stash_key' => 'rest',
613 'map' => {
614 'text/html' => 'YAML::HTML',
615 'text/xml' => 'XML::Simple',
616 'text/x-yaml' => 'YAML',
617 'application/json' => 'JSON',
618 'text/x-json' => 'JSON',
619 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
620 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
621 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
622 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
623 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
624 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
625 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
626 },
e601adda 627 );
628
629You can read the full set of options for this configuration block in
630L<Catalyst::Action::Serialize>.
631
632=item Sets a C<begin> and C<end> method for you
633
634The C<begin> method uses L<Catalyst::Action::Deserialize>. The C<end>
635method uses L<Catalyst::Action::Serialize>. If you want to override
636either behavior, simply implement your own C<begin> and C<end> actions
355d4385 637and forward to another action with the Serialize and/or Deserialize
638action classes:
e601adda 639
10bcd217 640 package Foo::Controller::Monkey;
641 use Moose;
642 use namespace::autoclean;
355d4385 643
10bcd217 644 BEGIN { extends 'Catalyst::Controller::REST' }
e601adda 645
355d4385 646 sub begin : Private {
e601adda 647 my ($self, $c) = @_;
db8bb647 648 ... do things before Deserializing ...
355d4385 649 $c->forward('deserialize');
e601adda 650 ... do things after Deserializing ...
db8bb647 651 }
e601adda 652
355d4385 653 sub deserialize : ActionClass('Deserialize') {}
654
e601adda 655 sub end :Private {
656 my ($self, $c) = @_;
db8bb647 657 ... do things before Serializing ...
355d4385 658 $c->forward('serialize');
e601adda 659 ... do things after Serializing ...
660 }
661
355d4385 662 sub serialize : ActionClass('Serialize') {}
663
8bf1f20e 664If you need to deserialize multipart requests (i.e. REST data in
665one part and file uploads in others) you can do so by using the
666L<Catalyst::Action::DeserializeMultiPart> action class.
667
e540a1fa 668=back
669
e601adda 670=head1 A MILD WARNING
671
672I have code in production using L<Catalyst::Controller::REST>. That said,
673it is still under development, and it's possible that things may change
d6ece98c 674between releases. I promise to not break things unnecessarily. :)
e601adda 675
398c5a1b 676=head1 SEE ALSO
677
678L<Catalyst::Action::REST>, L<Catalyst::Action::Serialize>,
679L<Catalyst::Action::Deserialize>
680
681For help with REST in general:
682
683The HTTP 1.1 Spec is required reading. http://www.w3.org/Protocols/rfc2616/rfc2616.txt
684
685Wikipedia! http://en.wikipedia.org/wiki/Representational_State_Transfer
686
687The REST Wiki: http://rest.blueoxen.net/cgi-bin/wiki.pl?FrontPage
688
5cb5f6bb 689=head1 AUTHORS
e540a1fa 690
5cb5f6bb 691See L<Catalyst::Action::REST> for authors.
e540a1fa 692
398c5a1b 693=head1 LICENSE
694
695You may distribute this code under the same terms as Perl itself.
696
697=cut
698
24748286 699__PACKAGE__->meta->make_immutable;
700
256c894f 7011;