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