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