1 package Catalyst::Controller::REST;
3 use namespace::autoclean;
6 $VERSION = eval $VERSION;
10 Catalyst::Controller::REST - A RESTful controller
14 package Foo::Controller::Bar;
16 use namespace::autoclean;
18 BEGIN { extends 'Catalyst::Controller::REST' }
20 sub thing : Local : ActionClass('REST') { }
22 # Answer GET requests to "thing"
24 my ( $self, $c ) = @_;
26 # Return a 200 OK, with the data in entity
27 # serialized in the body
32 foo => 'is real bar-y',
37 # Answer PUT requests to "thing"
39 my ( $self, $c ) = @_;
41 $radiohead = $c->req->data->{radiohead};
43 $self->status_created(
45 location => $c->req->uri,
47 radiohead => $radiohead,
54 Catalyst::Controller::REST implements a mechanism for building
55 RESTful services in Catalyst. It does this by extending the
56 normal Catalyst dispatch mechanism to allow for different
57 subroutines to be called based on the HTTP Method requested,
58 while also transparently handling all the serialization/deserialization for
61 This is probably best served by an example. In the above
62 controller, we have declared a Local Catalyst action on
63 "sub thing", and have used the ActionClass('REST').
65 Below, we have declared "thing_GET" and "thing_PUT". Any
66 GET requests to thing will be dispatched to "thing_GET",
67 while any PUT requests will be dispatched to "thing_PUT".
69 Any unimplemented HTTP methods will be met with a "405 Method Not Allowed"
70 response, automatically containing the proper list of available methods. You
71 can override this behavior through implementing a custom
72 C<thing_not_implemented> method.
74 If you do not provide an OPTIONS handler, we will respond to any OPTIONS
75 requests with a "200 OK", populating the Allowed header automatically.
77 Any data included in C<< $c->stash->{'rest'} >> will be serialized for you.
78 The serialization format will be selected based on the content-type
79 of the incoming request. It is probably easier to use the L<STATUS HELPERS>,
80 which are described below.
82 "The HTTP POST, PUT, and OPTIONS methods will all automatically
83 L<deserialize|Catalyst::Action::Deserialize> the contents of
84 C<< $c->request->body >> into the C<< $c->request->data >> hashref", based on
85 the request's C<Content-type> header. A list of understood serialization
86 formats is L<below|/AVAILABLE SERIALIZERS>.
88 If we do not have (or cannot run) a serializer for a given content-type, a 415
89 "Unsupported Media Type" error is generated.
91 To make your Controller RESTful, simply have it
93 BEGIN { extends 'Catalyst::Controller::REST' }
97 See L<Catalyst::Action::Serialize/CONFIGURATION>. Note that the C<serialize>
98 key has been deprecated.
102 Catalyst::Controller::REST will automatically serialize your
103 responses, and deserialize any POST, PUT or OPTIONS requests. It evaluates
104 which serializer to use by mapping a content-type to a Serialization module.
105 We select the content-type based on:
109 =item B<The Content-Type Header>
111 If the incoming HTTP Request had a Content-Type header set, we will use it.
113 =item B<The content-type Query Parameter>
115 If this is a GET request, you can supply a content-type query parameter.
117 =item B<Evaluating the Accept Header>
119 Finally, if the client provided an Accept header, we will evaluate
120 it and use the best-ranked choice.
124 =head1 AVAILABLE SERIALIZERS
126 A given serialization mechanism is only available if you have the underlying
127 modules installed. For example, you can't use XML::Simple if it's not already
130 In addition, each serializer has its quirks in terms of what sorts of data
131 structures it will properly handle. L<Catalyst::Controller::REST> makes
132 no attempt to save you from yourself in this regard. :)
136 =item * C<text/x-yaml> => C<YAML::Syck>
138 Returns YAML generated by L<YAML::Syck>.
140 =item * C<text/html> => C<YAML::HTML>
142 This uses L<YAML::Syck> and L<URI::Find> to generate YAML with all URLs turned
143 to hyperlinks. Only usable for Serialization.
145 =item * C<application/json> => C<JSON>
147 Uses L<JSON> to generate JSON output. It is strongly advised to also have
148 L<JSON::XS> installed. The C<text/x-json> content type is supported but is
149 deprecated and you will receive warnings in your log.
151 You can also add a hash in your controller config to pass options to the json object.
152 For instance, to relax permissions when deserializing input, add:
154 json_options => { relaxed => 1 }
157 =item * C<text/javascript> => C<JSONP>
159 If a callback=? parameter is passed, this returns javascript in the form of: $callback($serializedJSON);
161 Note - this is disabled by default as it can be a security risk if you are unaware.
163 The usual MIME types for this serialization format are: 'text/javascript', 'application/x-javascript',
164 'application/javascript'.
166 =item * C<text/x-data-dumper> => C<Data::Serializer>
168 Uses the L<Data::Serializer> module to generate L<Data::Dumper> output.
170 =item * C<text/x-data-denter> => C<Data::Serializer>
172 Uses the L<Data::Serializer> module to generate L<Data::Denter> output.
174 =item * C<text/x-data-taxi> => C<Data::Serializer>
176 Uses the L<Data::Serializer> module to generate L<Data::Taxi> output.
178 =item * C<application/x-storable> => C<Data::Serializer>
180 Uses the L<Data::Serializer> module to generate L<Storable> output.
182 =item * C<application/x-freezethaw> => C<Data::Serializer>
184 Uses the L<Data::Serializer> module to generate L<FreezeThaw> output.
186 =item * C<text/x-config-general> => C<Data::Serializer>
188 Uses the L<Data::Serializer> module to generate L<Config::General> output.
190 =item * C<text/x-php-serialization> => C<Data::Serializer>
192 Uses the L<Data::Serializer> module to generate L<PHP::Serialization> output.
194 =item * C<text/xml> => C<XML::Simple>
196 Uses L<XML::Simple> to generate XML output. This is probably not suitable
197 for any real heavy XML work. Due to L<XML::Simple>s requirement that the data
198 you serialize be a HASHREF, we transform outgoing data to be in the form of:
200 { data => $yourdata }
204 Uses a regular Catalyst view. For example, if you wanted to have your
205 C<text/html> and C<text/xml> views rendered by TT, set:
209 'text/html' => [ 'View', 'TT' ],
210 'text/xml' => [ 'View', 'XML' ],
214 Your views should have a C<process> method like this:
217 my ( $self, $c, $stash_key ) = @_;
221 $output = $self->serialize( $c->stash->{$stash_key} );
225 $c->response->body( $output );
226 return 1; # important
230 my ( $self, $data ) = @_;
232 my $serialized = ... process $data here ...
239 For infinite flexibility, you can provide a callback for the
240 deserialization/serialization steps.
244 'text/xml' => [ 'Callback', { deserialize => \&parse_xml, serialize => \&render_xml } ],
248 The C<deserialize> callback is passed a string that is the body of the
249 request and is expected to return a scalar value that results from
250 the deserialization. The C<serialize> callback is passed the data
251 structure that needs to be serialized and must return a string suitable
252 for returning in the HTTP response. In addition to receiving the scalar
253 to act on, both callbacks are passed the controller object and the context
254 (i.e. C<$c>) as the second and third arguments.
258 By default, L<Catalyst::Controller::REST> will return a
259 C<415 Unsupported Media Type> response if an attempt to use an unsupported
260 content-type is made. You can ensure that something is always returned by
261 setting the C<default> config option:
263 __PACKAGE__->config(default => 'text/x-yaml');
265 would make it always fall back to the serializer plugin defined for
268 =head1 CUSTOM SERIALIZERS
270 Implementing new Serialization formats is easy! Contributions
271 are most welcome! If you would like to implement a custom serializer,
272 you should create two new modules in the L<Catalyst::Action::Serialize>
273 and L<Catalyst::Action::Deserialize> namespace. Then assign your new
274 class to the content-type's you want, and you're done.
276 See L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>
277 for more information.
279 =head1 STATUS HELPERS
281 Since so much of REST is in using HTTP, we provide these Status Helpers.
282 Using them will ensure that you are responding with the proper codes,
283 headers, and entities.
285 These helpers try and conform to the HTTP 1.1 Specification. You can
286 refer to it at: L<http://www.w3.org/Protocols/rfc2616/rfc2616.txt>.
287 These routines are all implemented as regular subroutines, and as
288 such require you pass the current context ($c) as the first argument.
294 BEGIN { extends 'Catalyst::Controller' }
295 use Params::Validate qw(SCALAR OBJECT);
297 __PACKAGE__->mk_accessors(qw(serialize));
300 'stash_key' => 'rest',
302 'text/html' => 'YAML::HTML',
303 'text/xml' => 'XML::Simple',
304 'text/x-yaml' => 'YAML',
305 'application/json' => 'JSON',
306 'text/x-json' => 'JSON',
307 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
308 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
309 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
310 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
311 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
312 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
313 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
317 sub begin : ActionClass('Deserialize') { }
319 sub end : ActionClass('Serialize') { }
323 Returns a "200 OK" response. Takes an "entity" to serialize.
330 radiohead => "Is a good band!",
339 my %p = Params::Validate::validate( @_, { entity => 1, }, );
341 $c->response->status(200);
342 $self->_set_entity( $c, $p{'entity'} );
348 Returns a "201 CREATED" response. Takes an "entity" to serialize,
349 and a "location" where the created object can be found.
353 $self->status_created(
355 location => $c->req->uri,
357 radiohead => "Is a good band!",
361 In the above example, we use the requested URI as our location.
362 This is probably what you want for most PUT requests.
369 my %p = Params::Validate::validate(
372 location => { type => SCALAR | OBJECT },
373 entity => { optional => 1 },
377 $c->response->status(201);
378 $c->response->header( 'Location' => $p{location} );
379 $self->_set_entity( $c, $p{'entity'} );
383 =item status_accepted
385 Returns a "202 ACCEPTED" response. Takes an "entity" to serialize.
386 Also takes optional "location" for queue type scenarios.
390 $self->status_accepted(
392 location => $c->req->uri,
400 sub status_accepted {
403 my %p = Params::Validate::validate(
406 location => { type => SCALAR | OBJECT, optional => 1 },
411 $c->response->status(202);
412 $c->response->header( 'Location' => $p{location} ) if exists $p{location};
413 $self->_set_entity( $c, $p{'entity'} );
417 =item status_no_content
419 Returns a "204 NO CONTENT" response.
423 sub status_no_content {
426 $c->response->status(204);
427 $self->_set_entity( $c, undef );
431 =item status_multiple_choices
433 Returns a "300 MULTIPLE CHOICES" response. Takes an "entity" to serialize, which should
434 provide list of possible locations. Also takes optional "location" for preferred choice.
438 sub status_multiple_choices {
441 my %p = Params::Validate::validate(
445 location => { type => SCALAR | OBJECT, optional => 1 },
449 $c->response->status(300);
450 $c->response->header( 'Location' => $p{location} ) if exists $p{'location'};
451 $self->_set_entity( $c, $p{'entity'} );
457 Returns a "302 FOUND" response. Takes an "entity" to serialize.
458 Also takes optional "location".
465 my %p = Params::Validate::validate(
469 location => { type => SCALAR | OBJECT, optional => 1 },
473 $c->response->status(302);
474 $c->response->header( 'Location' => $p{location} ) if exists $p{'location'};
475 $self->_set_entity( $c, $p{'entity'} );
479 =item status_bad_request
481 Returns a "400 BAD REQUEST" response. Takes a "message" argument
482 as a scalar, which will become the value of "error" in the serialized
487 $self->status_bad_request(
489 message => "Cannot do what you have asked!",
494 sub status_bad_request {
497 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
499 $c->response->status(400);
500 $c->log->debug( "Status Bad Request: " . $p{'message'} ) if $c->debug;
501 $self->_set_entity( $c, { error => $p{'message'} } );
505 =item status_forbidden
507 Returns a "403 FORBIDDEN" response. Takes a "message" argument
508 as a scalar, which will become the value of "error" in the serialized
513 $self->status_forbidden(
515 message => "access denied",
520 sub status_forbidden {
523 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
525 $c->response->status(403);
526 $c->log->debug( "Status Forbidden: " . $p{'message'} ) if $c->debug;
527 $self->_set_entity( $c, { error => $p{'message'} } );
531 =item status_not_found
533 Returns a "404 NOT FOUND" response. Takes a "message" argument
534 as a scalar, which will become the value of "error" in the serialized
539 $self->status_not_found(
541 message => "Cannot find what you were looking for!",
546 sub status_not_found {
549 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
551 $c->response->status(404);
552 $c->log->debug( "Status Not Found: " . $p{'message'} ) if $c->debug;
553 $self->_set_entity( $c, { error => $p{'message'} } );
559 Returns a "41O GONE" response. Takes a "message" argument as a scalar,
560 which will become the value of "error" in the serialized response.
566 message => "The document have been deleted by foo",
574 my %p = Params::Validate::validate( @_, { message => { type => SCALAR }, }, );
576 $c->response->status(410);
577 $c->log->debug( "Status Gone " . $p{'message'} ) if $c->debug;
578 $self->_set_entity( $c, { error => $p{'message'} } );
586 if ( defined($entity) ) {
587 $c->stash->{ $self->{'stash_key'} } = $entity;
594 =head1 MANUAL RESPONSES
596 If you want to construct your responses yourself, all you need to
597 do is put the object you want serialized in $c->stash->{'rest'}.
599 =head1 IMPLEMENTATION DETAILS
601 This Controller ties together L<Catalyst::Action::REST>,
602 L<Catalyst::Action::Serialize> and L<Catalyst::Action::Deserialize>. It should be suitable for most applications. You should be aware that it:
606 =item Configures the Serialization Actions
608 This class provides a default configuration for Serialization. It is currently:
611 'stash_key' => 'rest',
613 'text/html' => 'YAML::HTML',
614 'text/xml' => 'XML::Simple',
615 'text/x-yaml' => 'YAML',
616 'application/json' => 'JSON',
617 'text/x-json' => 'JSON',
618 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
619 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
620 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
621 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
622 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
623 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
624 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
628 You can read the full set of options for this configuration block in
629 L<Catalyst::Action::Serialize>.
631 =item Sets a C<begin> and C<end> method for you
633 The C<begin> method uses L<Catalyst::Action::Deserialize>. The C<end>
634 method uses L<Catalyst::Action::Serialize>. If you want to override
635 either behavior, simply implement your own C<begin> and C<end> actions
636 and forward to another action with the Serialize and/or Deserialize
639 package Foo::Controller::Monkey;
641 use namespace::autoclean;
643 BEGIN { extends 'Catalyst::Controller::REST' }
645 sub begin : Private {
647 ... do things before Deserializing ...
648 $c->forward('deserialize');
649 ... do things after Deserializing ...
652 sub deserialize : ActionClass('Deserialize') {}
656 ... do things before Serializing ...
657 $c->forward('serialize');
658 ... do things after Serializing ...
661 sub serialize : ActionClass('Serialize') {}
663 If you need to deserialize multipart requests (i.e. REST data in
664 one part and file uploads in others) you can do so by using the
665 L<Catalyst::Action::DeserializeMultiPart> action class.
669 =head1 A MILD WARNING
671 I have code in production using L<Catalyst::Controller::REST>. That said,
672 it is still under development, and it's possible that things may change
673 between releases. I promise to not break things unnecessarily. :)
677 L<Catalyst::Action::REST>, L<Catalyst::Action::Serialize>,
678 L<Catalyst::Action::Deserialize>
680 For help with REST in general:
682 The HTTP 1.1 Spec is required reading. http://www.w3.org/Protocols/rfc2616/rfc2616.txt
684 Wikipedia! http://en.wikipedia.org/wiki/Representational_State_Transfer
686 The REST Wiki: http://rest.blueoxen.net/cgi-bin/wiki.pl?FrontPage
690 See L<Catalyst::Action::REST> for authors.
694 You may distribute this code under the same terms as Perl itself.
698 __PACKAGE__->meta->make_immutable;