1Catalyst::Controller::RUEsSeTr(3C)ontributed Perl DocumeCnattaatliyosnt::Controller::REST(3)
2
3
4
6 Catalyst::Controller::REST - A RESTful controller
7
9 package Foo::Controller::Bar;
10 use Moose;
11 use namespace::autoclean;
12
13 BEGIN { extends '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 $radiohead = $req->data->{radiohead};
35
36 $self->status_created(
37 $c,
38 location => $c->req->uri->as_string,
39 entity => {
40 radiohead => $radiohead,
41 }
42 );
43 }
44
46 Catalyst::Controller::REST implements a mechanism for building RESTful
47 services in Catalyst. It does this by extending the normal Catalyst
48 dispatch mechanism to allow for different subroutines to be called
49 based on the HTTP Method requested, while also transparently handling
50 all the serialization/deserialization for you.
51
52 This is probably best served by an example. In the above controller,
53 we have declared a Local Catalyst action on "sub thing", and have used
54 the ActionClass('REST').
55
56 Below, we have declared "thing_GET" and "thing_PUT". Any GET requests
57 to thing will be dispatched to "thing_GET", while any PUT requests will
58 be dispatched to "thing_PUT".
59
60 Any unimplemented HTTP methods will be met with a "405 Method Not
61 Allowed" response, automatically containing the proper list of
62 available methods. You can override this behavior through implementing
63 a custom "thing_not_implemented" method.
64
65 If you do not provide an OPTIONS handler, we will respond to any
66 OPTIONS requests with a "200 OK", populating the Allowed header
67 automatically.
68
69 Any data included in "$c->stash->{'rest'}" will be serialized for you.
70 The serialization format will be selected based on the content-type of
71 the incoming request. It is probably easier to use the "STATUS
72 HELPERS", which are described below.
73
74 "The HTTP POST, PUT, and OPTIONS methods will all automatically
75 deserialize the contents of "$c->request->body" into the
76 "$c->request->data" hashref", based on the request's "Content-type"
77 header. A list of understood serialization formats is below.
78
79 If we do not have (or cannot run) a serializer for a given content-
80 type, a 415 "Unsupported Media Type" error is generated.
81
82 To make your Controller RESTful, simply have it
83
84 BEGIN { extends 'Catalyst::Controller::REST' }
85
87 See "CONFIGURATION" in Catalyst::Action::Serialize. Note that the
88 "serialize" key has been deprecated.
89
91 Catalyst::Controller::REST will automatically serialize your responses,
92 and deserialize any POST, PUT or OPTIONS requests. It evaluates which
93 serializer to use by mapping a content-type to a Serialization module.
94 We select the content-type based on:
95
96 The Content-Type Header
97 If the incoming HTTP Request had a Content-Type header set, we will
98 use it.
99
100 The content-type Query Parameter
101 If this is a GET request, you can supply a content-type query
102 parameter.
103
104 Evaluating the Accept Header
105 Finally, if the client provided an Accept header, we will evaluate
106 it and use the best-ranked choice.
107
109 A given serialization mechanism is only available if you have the
110 underlying modules installed. For example, you can't use XML::Simple
111 if it's not already installed.
112
113 In addition, each serializer has its quirks in terms of what sorts of
114 data structures it will properly handle. Catalyst::Controller::REST
115 makes no attempt to save you from yourself in this regard. :)
116
117 · "text/x-yaml" => "YAML::Syck"
118
119 Returns YAML generated by YAML::Syck.
120
121 · "text/html" => "YAML::HTML"
122
123 This uses YAML::Syck and URI::Find to generate YAML with all URLs
124 turned to hyperlinks. Only usable for Serialization.
125
126 · "application/json" => "JSON"
127
128 Uses JSON to generate JSON output. It is strongly advised to also
129 have JSON::XS installed. The "text/x-json" content type is supported
130 but is deprecated and you will receive warnings in your log.
131
132 You can also add a hash in your controller config to pass options to
133 the json object. For instance, to relax permissions when
134 deserializing input, add:
135 __PACKAGE__->config(
136 json_options => { relaxed => 1 }
137 )
138
139 · "text/javascript" => "JSONP"
140
141 If a callback=? parameter is passed, this returns javascript in the
142 form of: $callback($serializedJSON);
143
144 Note - this is disabled by default as it can be a security risk if
145 you are unaware.
146
147 The usual MIME types for this serialization format are:
148 'text/javascript', 'application/x-javascript',
149 'application/javascript'.
150
151 · "text/x-data-dumper" => "Data::Serializer"
152
153 Uses the Data::Serializer module to generate Data::Dumper output.
154
155 · "text/x-data-denter" => "Data::Serializer"
156
157 Uses the Data::Serializer module to generate Data::Denter output.
158
159 · "text/x-data-taxi" => "Data::Serializer"
160
161 Uses the Data::Serializer module to generate Data::Taxi output.
162
163 · "application/x-storable" => "Data::Serializer"
164
165 Uses the Data::Serializer module to generate Storable output.
166
167 · "application/x-freezethaw" => "Data::Serializer"
168
169 Uses the Data::Serializer module to generate FreezeThaw output.
170
171 · "text/x-config-general" => "Data::Serializer"
172
173 Uses the Data::Serializer module to generate Config::General output.
174
175 · "text/x-php-serialization" => "Data::Serializer"
176
177 Uses the Data::Serializer module to generate PHP::Serialization
178 output.
179
180 · "text/xml" => "XML::Simple"
181
182 Uses XML::Simple to generate XML output. This is probably not
183 suitable for any real heavy XML work. Due to XML::Simples requirement
184 that the data you serialize be a HASHREF, we transform outgoing data
185 to be in the form of:
186
187 { data => $yourdata }
188
189 · View
190
191 Uses a regular Catalyst view. For example, if you wanted to have
192 your "text/html" and "text/xml" views rendered by TT, set:
193
194 __PACKAGE__->config(
195 map => {
196 'text/html' => [ 'View', 'TT' ],
197 'text/xml' => [ 'View', 'XML' ],
198 }
199 );
200
201 Your views should have a "process" method like this:
202
203 sub process {
204 my ( $self, $c, $stash_key ) = @_;
205
206 my $output;
207 eval {
208 $output = $self->serialize( $c->stash->{$stash_key} );
209 };
210 return $@ if $@;
211
212 $c->response->body( $output );
213 return 1; # important
214 }
215
216 sub serialize {
217 my ( $self, $data ) = @_;
218
219 my $serialized = ... process $data here ...
220
221 return $serialized;
222 }
223
224 By default, Catalyst::Controller::REST will return a "415 Unsupported
225 Media Type" response if an attempt to use an unsupported content-type
226 is made. You can ensure that something is always returned by setting
227 the "default" config option:
228
229 __PACKAGE__->config(default => 'text/x-yaml');
230
231 would make it always fall back to the serializer plugin defined for
232 "text/x-yaml".
233
235 Implementing new Serialization formats is easy! Contributions are most
236 welcome! If you would like to implement a custom serializer, you
237 should create two new modules in the Catalyst::Action::Serialize and
238 Catalyst::Action::Deserialize namespace. Then assign your new class to
239 the content-type's you want, and you're done.
240
241 See Catalyst::Action::Serialize and Catalyst::Action::Deserialize for
242 more information.
243
245 Since so much of REST is in using HTTP, we provide these Status
246 Helpers. Using them will ensure that you are responding with the
247 proper codes, headers, and entities.
248
249 These helpers try and conform to the HTTP 1.1 Specification. You can
250 refer to it at: <http://www.w3.org/Protocols/rfc2616/rfc2616.txt>.
251 These routines are all implemented as regular subroutines, and as such
252 require you pass the current context ($c) as the first argument.
253
254 status_ok
255 Returns a "200 OK" response. Takes an "entity" to serialize.
256
257 Example:
258
259 $self->status_ok(
260 $c,
261 entity => {
262 radiohead => "Is a good band!",
263 }
264 );
265
266 status_created
267 Returns a "201 CREATED" response. Takes an "entity" to serialize,
268 and a "location" where the created object can be found.
269
270 Example:
271
272 $self->status_created(
273 $c,
274 location => $c->req->uri->as_string,
275 entity => {
276 radiohead => "Is a good band!",
277 }
278 );
279
280 In the above example, we use the requested URI as our location.
281 This is probably what you want for most PUT requests.
282
283 status_accepted
284 Returns a "202 ACCEPTED" response. Takes an "entity" to serialize.
285
286 Example:
287
288 $self->status_accepted(
289 $c,
290 entity => {
291 status => "queued",
292 }
293 );
294
295 status_no_content
296 Returns a "204 NO CONTENT" response.
297
298 status_multiple_choices
299 Returns a "300 MULTIPLE CHOICES" response. Takes an "entity" to
300 serialize, which should provide list of possible locations. Also
301 takes optional "location" for preferred choice.
302
303 status_bad_request
304 Returns a "400 BAD REQUEST" response. Takes a "message" argument
305 as a scalar, which will become the value of "error" in the
306 serialized response.
307
308 Example:
309
310 $self->status_bad_request(
311 $c,
312 message => "Cannot do what you have asked!",
313 );
314
315 status_not_found
316 Returns a "404 NOT FOUND" response. Takes a "message" argument as
317 a scalar, which will become the value of "error" in the serialized
318 response.
319
320 Example:
321
322 $self->status_not_found(
323 $c,
324 message => "Cannot find what you were looking for!",
325 );
326
327 gone
328 Returns a "41O GONE" response. Takes a "message" argument as a
329 scalar, which will become the value of "error" in the serialized
330 response.
331
332 Example:
333
334 $self->status_gone(
335 $c,
336 message => "The document have been deleted by foo",
337 );
338
340 If you want to construct your responses yourself, all you need to do is
341 put the object you want serialized in $c->stash->{'rest'}.
342
344 This Controller ties together Catalyst::Action::REST,
345 Catalyst::Action::Serialize and Catalyst::Action::Deserialize. It
346 should be suitable for most applications. You should be aware that it:
347
348 Configures the Serialization Actions
349 This class provides a default configuration for Serialization. It
350 is currently:
351
352 __PACKAGE__->config(
353 'stash_key' => 'rest',
354 'map' => {
355 'text/html' => 'YAML::HTML',
356 'text/xml' => 'XML::Simple',
357 'text/x-yaml' => 'YAML',
358 'application/json' => 'JSON',
359 'text/x-json' => 'JSON',
360 'text/x-data-dumper' => [ 'Data::Serializer', 'Data::Dumper' ],
361 'text/x-data-denter' => [ 'Data::Serializer', 'Data::Denter' ],
362 'text/x-data-taxi' => [ 'Data::Serializer', 'Data::Taxi' ],
363 'application/x-storable' => [ 'Data::Serializer', 'Storable' ],
364 'application/x-freezethaw' => [ 'Data::Serializer', 'FreezeThaw' ],
365 'text/x-config-general' => [ 'Data::Serializer', 'Config::General' ],
366 'text/x-php-serialization' => [ 'Data::Serializer', 'PHP::Serialization' ],
367 },
368 );
369
370 You can read the full set of options for this configuration block
371 in Catalyst::Action::Serialize.
372
373 Sets a "begin" and "end" method for you
374 The "begin" method uses Catalyst::Action::Deserialize. The "end"
375 method uses Catalyst::Action::Serialize. If you want to override
376 either behavior, simply implement your own "begin" and "end"
377 actions and use MRO::Compat:
378
379 package Foo::Controller::Monkey;
380 use Moose;
381 use namespace::autoclean;
382
383 BEGIN { extends 'Catalyst::Controller::REST' }
384
385 sub begin :Private {
386 my ($self, $c) = @_;
387 ... do things before Deserializing ...
388 $self->maybe::next::method($c);
389 ... do things after Deserializing ...
390 }
391
392 sub end :Private {
393 my ($self, $c) = @_;
394 ... do things before Serializing ...
395 $self->maybe::next::method($c);
396 ... do things after Serializing ...
397 }
398
400 I have code in production using Catalyst::Controller::REST. That said,
401 it is still under development, and it's possible that things may change
402 between releases. I promise to not break things unnecessarily. :)
403
405 Catalyst::Action::REST, Catalyst::Action::Serialize,
406 Catalyst::Action::Deserialize
407
408 For help with REST in general:
409
410 The HTTP 1.1 Spec is required reading.
411 http://www.w3.org/Protocols/rfc2616/rfc2616.txt
412
413 Wikipedia! http://en.wikipedia.org/wiki/Representational_State_Transfer
414
415 The REST Wiki: http://rest.blueoxen.net/cgi-bin/wiki.pl?FrontPage
416
418 See Catalyst::Action::REST for authors.
419
421 You may distribute this code under the same terms as Perl itself.
422
423
424
425perl v5.12.1 2010-09-01 Catalyst::Controller::REST(3)