Dancer-Plugin-REST-0.11/0000755000175000017500000000000012314270461014154 5ustar yanickyanickDancer-Plugin-REST-0.11/xt/0000755000175000017500000000000012314270461014607 5ustar yanickyanickDancer-Plugin-REST-0.11/xt/release/0000755000175000017500000000000012314270461016227 5ustar yanickyanickDancer-Plugin-REST-0.11/xt/release/unused-vars.t0000644000175000017500000000020712314270461020667 0ustar yanickyanick#!perl use Test::More; eval "use Test::Vars"; plan skip_all => "Test::Vars required for testing unused vars" if $@; all_vars_ok(); Dancer-Plugin-REST-0.11/lib/0000755000175000017500000000000012314270461014722 5ustar yanickyanickDancer-Plugin-REST-0.11/lib/Dancer/0000755000175000017500000000000012314270461016116 5ustar yanickyanickDancer-Plugin-REST-0.11/lib/Dancer/Plugin/0000755000175000017500000000000012314270461017354 5ustar yanickyanickDancer-Plugin-REST-0.11/lib/Dancer/Plugin/REST.pm0000644000175000017500000001670412314270461020477 0ustar yanickyanickpackage Dancer::Plugin::REST; BEGIN { $Dancer::Plugin::REST::AUTHORITY = 'cpan:SUKRIA'; } # ABSTRACT: A plugin for writing RESTful apps with Dancer $Dancer::Plugin::REST::VERSION = '0.11'; use strict; use warnings; use Carp 'croak'; use Dancer ':syntax'; use Dancer::Plugin; my $content_types = { json => 'application/json', yml => 'text/x-yaml', xml => 'application/xml', }; our $default_serializer; register prepare_serializer_for_format => sub { my $conf = plugin_setting; my $serializers = ( ($conf && exists $conf->{serializers}) ? $conf->{serializers} : { 'json' => 'JSON', 'yml' => 'YAML', 'xml' => 'XML', 'dump' => 'Dumper', } ); hook 'before' => sub { # remember what was there before $default_serializer ||= setting 'serializer'; my $format = params->{'format'} or return; my $serializer = $serializers->{$format} or return halt( Dancer::Error->new( code => 404, title => "unsupported format requested", message => "unsupported format requested: " . $format )->render ); set serializer => $serializer; # check if we were supposed to deserialize the request Dancer::Serializer->process_request( Dancer::SharedData->request ); content_type $content_types->{$format} || setting('content_type'); }; hook after => sub { # put it back the way it was set serializer => $default_serializer; } }; my %triggers_map = ( get => \&get, update => \&put, create => \&post, delete => \&del, ); register resource => sub { croak "resource invoked without arguments" unless @_; my ($resource, %triggers) = @_; while( my( $t, $sub ) = each %triggers ) { my $method = $triggers_map{$t} or croak "action '$t' not recognized"; if ( $t eq 'create' ) { $method->( "/${resource}" => $triggers{$t} ); $method->( "/${resource}.:format" => $triggers{$t} ); } else { for my $ext ( '.:format', '' ) { $method->( "/${resource}/:id$ext" => $triggers{$t} ); } } } }; register send_entity => sub { # entity, status_code status($_[1] || 200); $_[0]; }; my %http_codes = ( # 1xx 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', # 2xx 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-Status', 210 => 'Content Different', # 3xx 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect', 310 => 'Too many Redirect', # 4xx 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested range unsatisfiable', 417 => 'Expectation failed', 418 => 'Teapot', 422 => 'Unprocessable entity', 423 => 'Locked', 424 => 'Method failure', 425 => 'Unordered Collection', 426 => 'Upgrade Required', 449 => 'Retry With', 450 => 'Parental Controls', # 5xx 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported', 507 => 'Insufficient storage', 509 => 'Bandwidth Limit Exceeded', ); for my $code (keys %http_codes) { my $helper_name = lc($http_codes{$code}); $helper_name =~ s/[^\w]+/_/gms; $helper_name = "status_${helper_name}"; register $helper_name => sub { if ($code >= 400) { send_entity({error => $_[0]}, $code); } else { send_entity($_[0], $code); } }; } register_plugin; 1; __END__ =pod =encoding UTF-8 =head1 NAME Dancer::Plugin::REST - A plugin for writing RESTful apps with Dancer =head1 VERSION version 0.11 =head1 DESCRIPTION This plugin helps you write a RESTful webservice with Dancer. =head1 SYNOPSYS package MyWebService; use Dancer; use Dancer::Plugin::REST; prepare_serializer_for_format; get '/user/:id.:format' => sub { User->find(params->{id}); }; # curl http://mywebservice/user/42.json { "id": 42, "name": "John Foo", email: "john.foo@example.com"} # curl http://mywebservice/user/42.yml -- id: 42 name: "John Foo" email: "john.foo@example.com" =head1 KEYWORDS =head2 prepare_serializer_for_format When this pragma is used, a before filter is set by the plugin to automatically change the serializer when a format is detected in the URI. That means that each route you define with a B<:format> token will trigger a serializer definition, if the format is known. This lets you define all the REST actions you like as regular Dancer route handlers, without explicitly handling the outgoing data format. =head2 resource This keyword lets you declare a resource your application will handle. resource user => get => sub { # return user where id = params->{id} }, create => sub { # create a new user with params->{user} }, delete => sub { # delete user where id = params->{id} }, update => sub { # update user with params->{user} }; # this defines the following routes: # GET /user/:id # GET /user/:id.:format # POST /user # POST /user.:format # DELETE /user/:id # DELETE /user/:id.:format # PUT /user/:id # PUT /user/:id.:format =head2 helpers Some helpers are available. This helper will set an appropriate HTTP status for you. =head3 status_ok status_ok({users => {...}}); Set the HTTP status to 200 =head3 status_created status_created({users => {...}}); Set the HTTP status to 201 =head3 status_accepted status_accepted({users => {...}}); Set the HTTP status to 202 =head3 status_bad_request status_bad_request("user foo can't be found"); Set the HTTP status to 400. This function as for argument a scalar that will be used under the key B. =head3 status_not_found status_not_found("users doesn't exists"); Set the HTTP status to 404. This function as for argument a scalar that will be used under the key B. =head1 LICENCE This module is released under the same terms as Perl itself. =head1 AUTHORS This module has been written by Alexis Sukrieh C<< >> and Franck Cuny. =head1 SEE ALSO L L =head1 AUTHORS =over 4 =item * Alexis Sukrieh =item * Franck Cuny =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2010 by Alexis Sukrieh. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut Dancer-Plugin-REST-0.11/MANIFEST0000644000175000017500000000056112314270461015307 0ustar yanickyanickBuild.PL CONTRIBUTORS Changes INSTALL LICENSE MANIFEST META.json META.yml README README.mkdn SIGNATURE lib/Dancer/Plugin/REST.pm t/00-compile.t t/000-report-versions-tiny.t t/01_base.t t/02_prepare_serializer_for_format.t t/03_resource.t t/04_helpers.t t/04_plugin_settings.t t/05_serializer_and_resource.t t/default-serializer.t t/two-posts.t xt/release/unused-vars.t Dancer-Plugin-REST-0.11/Changes0000644000175000017500000000356312314270461015456 0ustar yanickyanickRevision history for 0.11 2014-03-25 [BUG FIXES] - Routes with ':id.:format' were not created properly. (GH#3, reported by garu) [STATISTICS] - code churn: 4 files changed, 68 insertions(+), 3 deletions(-) 0.10 2014-03-22 [BUG FIXES] - Requires Dancer v1.3111 or better. (GH#2, reported by OverlordQ) [ENHANCEMENTS] - 'resource' can now be used with a subset of its actions. [STATISTICS] - code churn: 4 files changed, 42 insertions(+), 25 deletions(-) 0.09 2014-03-11 [BUG FIXES] - Skip test if XML::Simple is not installed. [STATISTICS] - code churn: 2 files changed, 26 insertions(+), 3 deletions(-) 0.08 2014-03-10 [BUG FIXES] - 'prepare_serializer_for_format' was clobbering the default serializer. (RT#93478, reported by Pierre Vigier, fix by Yanick Champoux) - serializer not detected in time for first deserialization. (RT#78437, reported by Andrew Solomon, fix by Yanick Champoux) [STATISTICS] - code churn: 12 files changed, 172 insertions(+), 111 deletions(-) 0.07 2011-11-01 - Minor updates to fix warnings with Dancer 1.3080 - Fix POD (Alexis Sukrieh) 0.06 2011-05-28 [TEST SUITE] - Skip test t/03_resource.t if Dancer is not >= 1.3059_01 A bug in Dancer::Test in previous versions prevent the test from passing. 0.05 2011-03-04 [BUG FIXES] - Fix the test suite with dancer_response - Fix dependencies: Dancer 1.3014 0.04 2010-12-22 - Add all HTTP response status (Alexis Sukrieh) 0.03 2010-10-18 - New keywords for ReST response status (status_ok, status_created, ...) (Franck Cuny) 0.02 2010-10-14 - 100% coverage - fix a bug in 'resource' (order of route hander definition) 0.0001_01 2010-05-06 - Support for prepare_serializer_for_format keyword autoamtically set a serializer according to params->{format} - Support for resource definition When a resource is defined a set of routes are defined in a RESTful manner. Dancer-Plugin-REST-0.11/LICENSE0000644000175000017500000004366312314270461015175 0ustar yanickyanickThis software is copyright (c) 2010 by Alexis Sukrieh. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2010 by Alexis Sukrieh. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2010 by Alexis Sukrieh. This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Dancer-Plugin-REST-0.11/README.mkdn0000644000175000017500000000575412314270461015777 0ustar yanickyanick# NAME Dancer::Plugin::REST - A plugin for writing RESTful apps with Dancer # VERSION version 0.11 # DESCRIPTION This plugin helps you write a RESTful webservice with Dancer. # SYNOPSYS package MyWebService; use Dancer; use Dancer::Plugin::REST; prepare_serializer_for_format; get '/user/:id.:format' => sub { User->find(params->{id}); }; # curl http://mywebservice/user/42.json { "id": 42, "name": "John Foo", email: "john.foo@example.com"} # curl http://mywebservice/user/42.yml -- id: 42 name: "John Foo" email: "john.foo@example.com" # KEYWORDS ## prepare\_serializer\_for\_format When this pragma is used, a before filter is set by the plugin to automatically change the serializer when a format is detected in the URI. That means that each route you define with a __:format__ token will trigger a serializer definition, if the format is known. This lets you define all the REST actions you like as regular Dancer route handlers, without explicitly handling the outgoing data format. ## resource This keyword lets you declare a resource your application will handle. resource user => get => sub { # return user where id = params->{id} }, create => sub { # create a new user with params->{user} }, delete => sub { # delete user where id = params->{id} }, update => sub { # update user with params->{user} }; # this defines the following routes: # GET /user/:id # GET /user/:id.:format # POST /user # POST /user.:format # DELETE /user/:id # DELETE /user/:id.:format # PUT /user/:id # PUT /user/:id.:format ## helpers Some helpers are available. This helper will set an appropriate HTTP status for you. ### status\_ok status_ok({users => {...}}); Set the HTTP status to 200 ### status\_created status_created({users => {...}}); Set the HTTP status to 201 ### status\_accepted status_accepted({users => {...}}); Set the HTTP status to 202 ### status\_bad\_request status_bad_request("user foo can't be found"); Set the HTTP status to 400. This function as for argument a scalar that will be used under the key __error__. ### status\_not\_found status_not_found("users doesn't exists"); Set the HTTP status to 404. This function as for argument a scalar that will be used under the key __error__. # LICENCE This module is released under the same terms as Perl itself. # AUTHORS This module has been written by Alexis Sukrieh `` and Franck Cuny. # SEE ALSO [Dancer](https://metacpan.org/pod/Dancer) [http://en.wikipedia.org/wiki/Representational\_State\_Transfer](http://en.wikipedia.org/wiki/Representational_State_Transfer) # AUTHORS - Alexis Sukrieh - Franck Cuny # COPYRIGHT AND LICENSE This software is copyright (c) 2010 by Alexis Sukrieh. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Dancer-Plugin-REST-0.11/Build.PL0000644000175000017500000000301512314270461015447 0ustar yanickyanick # This file was automatically generated by Dist::Zilla::Plugin::ModuleBuild v5.013. use strict; use warnings; use Module::Build 0.3601; my %module_build_args = ( "build_requires" => { "Module::Build" => "0.3601" }, "configure_requires" => { "Module::Build" => "0.3601" }, "dist_abstract" => "A plugin for writing RESTful apps with Dancer", "dist_author" => [ "Alexis Sukrieh ", "Franck Cuny " ], "dist_name" => "Dancer-Plugin-REST", "dist_version" => "0.11", "license" => "perl", "module_name" => "Dancer::Plugin::REST", "recommends" => {}, "recursive_test_files" => 1, "requires" => { "Carp" => 0, "Dancer" => "1.3111", "Dancer::Plugin" => 0, "strict" => 0, "warnings" => 0 }, "script_files" => [], "test_requires" => { "Dancer::ModuleLoader" => 0, "Dancer::Test" => 0, "File::Spec" => 0, "HTTP::Headers" => 0, "IO::Handle" => 0, "IPC::Open3" => 0, "Test::More" => "0.88", "perl" => "5.006" } ); my %fallback_build_requires = ( "Dancer::ModuleLoader" => 0, "Dancer::Test" => 0, "File::Spec" => 0, "HTTP::Headers" => 0, "IO::Handle" => 0, "IPC::Open3" => 0, "Module::Build" => "0.3601", "Test::More" => "0.88", "perl" => "5.006" ); unless ( eval { Module::Build->VERSION(0.4004) } ) { delete $module_build_args{test_requires}; $module_build_args{build_requires} = \%fallback_build_requires; } my $build = Module::Build->new(%module_build_args); $build->create_build_script; Dancer-Plugin-REST-0.11/SIGNATURE0000644000175000017500000000406712314270461015447 0ustar yanickyanickThis file contains message digests of all files listed in MANIFEST, signed via the Module::Signature module, version 0.73. To verify the content in this distribution, first make sure you have Module::Signature installed, then type: % cpansign -v It will check each file's integrity, as well as the signature's validity. If "==> Signature verified OK! <==" is not displayed, the distribution may already have been compromised, and you should not run its Makefile.PL or Build.PL. -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 SHA1 2d1c1ff98b280102dcf70b7895b085f1a6addb5c Build.PL SHA1 7dc53534c94df76d2057090735afb613beb29e68 CONTRIBUTORS SHA1 62e4152e34b9bb91e74fdc279e878d68c627939f Changes SHA1 3a432efd402166ab271516bfc1622488f5ec10a4 INSTALL SHA1 275383eac567137660ff0ae7fd02ee0ac280093e LICENSE SHA1 baa3cc7cb28d84d2357575ec29a08d264e9eccfa MANIFEST SHA1 003937fc21148ca71ba5d09a1e9d58cf0d701ab0 META.json SHA1 bc9fab11c0395efb426ad649b6c780cb97352996 META.yml SHA1 e6a1c4595a9942425524dedd931280e10dc3491f README SHA1 50d9d1cdbbf88201455bdc68495f6626628739c0 README.mkdn SHA1 bf207240536bc06499373f97465d2148447bb3f5 lib/Dancer/Plugin/REST.pm SHA1 9ce10b7155607bbdfe5d7fdf7dfe9bb8ce7ca282 t/00-compile.t SHA1 a8fe39a3e423cf31fd5a1a53a229e628321ed089 t/000-report-versions-tiny.t SHA1 3a11e9ee017c11a3a2cdb45f096983806b236730 t/01_base.t SHA1 1b060d6e41bb1ebe2ddb720b0082f44802e9b804 t/02_prepare_serializer_for_format.t SHA1 7954f11befe96f3e523dfbbd40b9ee336ba40a65 t/03_resource.t SHA1 4a098f9b9c656097298be8fb3e5ceaa1d3fffe47 t/04_helpers.t SHA1 9cdbfdec34c6bd49010a26aeabbaa099ec5d40d4 t/04_plugin_settings.t SHA1 b4d4c0d05ee0b06df64fd7db185d742be2dabe6e t/05_serializer_and_resource.t SHA1 53d712ffb593f2ad5195c00a434cbab2352b7f51 t/default-serializer.t SHA1 ac4341858f8097a852c269a23fb9eef2bf997cb2 t/two-posts.t SHA1 ec3f84bfd7a9ce3246e7592f4134100c6b5ce02b xt/release/unused-vars.t -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.14 (GNU/Linux) iEYEARECAAYFAlMxcSQACgkQ34Hwf+GwC4xAVwCfeZZJHY/lf/3L4xjEYDxAQ4NH R5kAoJ4cFBiig8cG05zO9eduWSWSyIlP =nZeX -----END PGP SIGNATURE----- Dancer-Plugin-REST-0.11/INSTALL0000644000175000017500000000176112314270461015212 0ustar yanickyanick This is the Perl distribution Dancer-Plugin-REST. Installing Dancer-Plugin-REST is straightforward. ## Installation with cpanm If you have cpanm, you only need one line: % cpanm Dancer::Plugin::REST If you are installing into a system-wide directory, you may need to pass the "-S" flag to cpanm, which uses sudo to install the module: % cpanm -S Dancer::Plugin::REST ## Installing with the CPAN shell Alternatively, if your CPAN shell is set up, you should just be able to do: % cpan Dancer::Plugin::REST ## Manual installation As a last resort, you can manually install it. Download the tarball, untar it, then build it: % perl Build.PL % ./Build && ./Build test Then install it: % ./Build install If you are installing into a system-wide directory, you may need to run: % sudo ./Build install ## Documentation Dancer-Plugin-REST documentation is available as POD. You can run perldoc from a shell to read the documentation: % perldoc Dancer::Plugin::REST Dancer-Plugin-REST-0.11/CONTRIBUTORS0000644000175000017500000000057212314270461016040 0ustar yanickyanick # DANCER-PLUGIN-REST CONTRIBUTORS # This is the (likely incomplete) list of people who have helped make this distribution what it is, either via code contributions, patches, bug reports, help with troubleshooting, etc. A huge thank to all of them. * Breno G. de Oliveira * James Aitken * Yanick Champoux Dancer-Plugin-REST-0.11/META.json0000644000175000017500000000414212314270461015576 0ustar yanickyanick{ "abstract" : "A plugin for writing RESTful apps with Dancer", "author" : [ "Alexis Sukrieh ", "Franck Cuny " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 5.013, CPAN::Meta::Converter version 2.140640", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "Dancer-Plugin-REST", "prereqs" : { "build" : { "requires" : { "Module::Build" : "0.3601" } }, "configure" : { "requires" : { "Module::Build" : "0.3601" } }, "develop" : { "requires" : { "version" : "0.9901" } }, "runtime" : { "requires" : { "Carp" : "0", "Dancer" : "1.3111", "Dancer::Plugin" : "0", "strict" : "0", "warnings" : "0" } }, "test" : { "requires" : { "Dancer::ModuleLoader" : "0", "Dancer::Test" : "0", "File::Spec" : "0", "HTTP::Headers" : "0", "IO::Handle" : "0", "IPC::Open3" : "0", "Test::More" : "0.88", "perl" : "5.006" } } }, "provides" : { "Dancer::Plugin::REST" : { "file" : "lib/Dancer/Plugin/REST.pm", "version" : "0.11" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/perldancer/Dancer-Plugin-REST/issues" }, "homepage" : "http://search.cpan.org/dist/Dancer-Plugin-REST/", "repository" : { "type" : "git", "url" : "https://github.com/perldancer/Dancer-Plugin-REST.git", "web" : "https://github.com/perldancer/Dancer-Plugin-REST" } }, "version" : "0.11", "x_authority" : "cpan:SUKRIA", "x_contributors" : [ "Breno G. de Oliveira ", "James Aitken ", "Yanick Champoux " ] } Dancer-Plugin-REST-0.11/META.yml0000644000175000017500000000227112314270461015427 0ustar yanickyanick--- abstract: 'A plugin for writing RESTful apps with Dancer' author: - 'Alexis Sukrieh ' - 'Franck Cuny ' build_requires: Dancer::ModuleLoader: '0' Dancer::Test: '0' File::Spec: '0' HTTP::Headers: '0' IO::Handle: '0' IPC::Open3: '0' Module::Build: '0.3601' Test::More: '0.88' perl: '5.006' configure_requires: Module::Build: '0.3601' dynamic_config: 0 generated_by: 'Dist::Zilla version 5.013, CPAN::Meta::Converter version 2.140640' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Dancer-Plugin-REST provides: Dancer::Plugin::REST: file: lib/Dancer/Plugin/REST.pm version: '0.11' requires: Carp: '0' Dancer: '1.3111' Dancer::Plugin: '0' strict: '0' warnings: '0' resources: bugtracker: https://github.com/perldancer/Dancer-Plugin-REST/issues homepage: http://search.cpan.org/dist/Dancer-Plugin-REST/ repository: https://github.com/perldancer/Dancer-Plugin-REST.git version: '0.11' x_authority: cpan:SUKRIA x_contributors: - 'Breno G. de Oliveira ' - 'James Aitken ' - 'Yanick Champoux ' Dancer-Plugin-REST-0.11/t/0000755000175000017500000000000012314270461014417 5ustar yanickyanickDancer-Plugin-REST-0.11/t/04_helpers.t0000644000175000017500000000561712314270461016562 0ustar yanickyanickuse strict; use warnings; use Dancer::ModuleLoader; use Test::More import => ['!pass']; plan tests => 16; { package Webservice; use Dancer; use Dancer::Plugin::REST; resource user => 'get' => \&on_get_user, 'create' => \&on_create_user, 'delete' => \&on_delete_user, 'update' => \&on_update_user; my $users = {}; my $last_id = 0; sub on_get_user { my $id = params->{'id'}; return status_bad_request('id is missing') if !defined $users->{$id}; status_ok( { user => $users->{$id} } ); } sub on_create_user { my $id = ++$last_id; my $user = params('body'); $user->{id} = $id; $users->{$id} = $user; status_created( { user => $users->{$id} } ); } sub on_delete_user { my $id = params->{'id'}; my $deleted = $users->{$id}; delete $users->{$id}; status_accepted( { user => $deleted } ); } sub on_update_user { my $id = params->{'id'}; my $user = $users->{$id}; return status_not_found("user undef") unless defined $user; $users->{$id} = { %$user, %{ params('body') } }; status_accepted { user => $users->{$id} }; } } use Dancer::Test; my $r = dancer_response( GET => '/user/1' ); is $r->{status}, 400, 'HTTP code is 400'; is $r->{content}->{error}, 'id is missing', 'Valid content'; $r = dancer_response( POST => '/user', { body => { name => 'Alexis' } } ); is $r->{status}, 201, 'HTTP code is 201'; is_deeply $r->{content}, { user => { id => 1, name => "Alexis" } }, "create user works"; $r = dancer_response( GET => '/user/1' ); is $r->{status}, 200, 'HTTP code is 200'; is_deeply $r->{content}, { user => { id => 1, name => 'Alexis' } }, "user 1 is defined"; $r = dancer_response( PUT => '/user/1', { body => { nick => 'sukria', name => 'Alexis Sukrieh' } } ); is $r->{status}, 202, 'HTTP code is 202'; is_deeply $r->{content}, { user => { id => 1, name => 'Alexis Sukrieh', nick => 'sukria' } }, "user 1 is updated"; $r = dancer_response( PUT => '/user/23', { body => { nick => 'john doe', name => 'John Doe' } } ); is $r->{status}, 404, 'HTTP code is 404'; is_deeply $r->{content}->{error}, 'user undef', 'valid content'; $r = dancer_response( DELETE => '/user/1' ); is_deeply $r->{content}, { user => { id => 1, name => 'Alexis Sukrieh', nick => 'sukria' } }, "user 1 is deleted"; is $r->{status}, 202, 'HTTP code is 202'; $r = dancer_response( GET => '/user/1' ); is $r->{status}, 400, 'HTTP code is 400'; is_deeply $r->{content}->{error}, 'id is missing', 'valid response'; $r = dancer_response( POST => '/user', { body => { name => 'Franck Cuny' } } ); is_deeply $r->{content}, { user => { id => 2, name => "Franck Cuny" } }, "id is correctly increased"; is $r->{status}, 201, 'HTTP code is 201'; Dancer-Plugin-REST-0.11/t/01_base.t0000644000175000017500000000007312314270461016016 0ustar yanickyanickuse Test::More tests => 1; use_ok 'Dancer::Plugin::REST'; Dancer-Plugin-REST-0.11/t/two-posts.t0000644000175000017500000000123212314270461016561 0ustar yanickyanickuse strict; use warnings; { package Foo; use Dancer; use Dancer::Plugin::REST; prepare_serializer_for_format; post '/foo.:format' => sub { return params; }; } use Test::More; use Dancer::ModuleLoader; plan skip_all => 'tests require JSON' unless Dancer::ModuleLoader->load('JSON'); plan tests => 2; use Dancer::Test; use HTTP::Headers; my $head = HTTP::Headers->new; $head->header("content-type" => "application/json"); for ( 1..2 ) { my $resp = dancer_response( 'POST' => '/foo.json', { body => '{"yin":"yang","foo":"bar"}', headers => $head, }); like $resp->content, qr/yin/; } Dancer-Plugin-REST-0.11/t/02_prepare_serializer_for_format.t0000644000175000017500000000267612314270461023225 0ustar yanickyanickuse strict; use warnings; use Dancer::ModuleLoader; use Test::More import => ['!pass']; plan skip_all => "JSON is needed for this test" unless Dancer::ModuleLoader->load('JSON'); plan skip_all => "YAML is needed for this test" unless Dancer::ModuleLoader->load('YAML'); my $data = { foo => 42 }; my $json = JSON::encode_json($data); my $yaml = YAML::Dump($data); { package Webservice; use Dancer; use Dancer::Plugin::REST; setting environment => 'testing'; prepare_serializer_for_format; get '/' => sub { "root" }; get '/:something.:format' => sub { $data; }; } use Dancer::Test; my @tests = ( { request => [GET => '/'], content_type => 'text/html', response => 'root', }, { request => [GET => '/foo.json'], content_type => 'application/json', response => $json }, { request => [GET => '/foo.yml'], content_type => 'text/x-yaml', response => $yaml, }, { request => [GET => '/'], content_type => 'text/html', response => 'root', }, ); plan tests => scalar(@tests) * 2; for my $test ( @tests ) { my $response = dancer_response(@{ $test->{request} }); is($response->header('Content-Type'), $test->{content_type}, "headers have content_type set to ".$test->{content_type}); is( $response->{content}, $test->{response}, "\$data has been encoded" ); } Dancer-Plugin-REST-0.11/t/000-report-versions-tiny.t0000644000175000017500000000472012314270461021246 0ustar yanickyanickuse strict; use warnings; use Test::More 0.88; # This is a relatively nice way to avoid Test::NoWarnings breaking our # expectations by adding extra tests, without using no_plan. It also helps # avoid any other test module that feels introducing random tests, or even # test plans, is a nice idea. our $success = 0; END { $success && done_testing; } # List our own version used to generate this my $v = "\nGenerated by Dist::Zilla::Plugin::ReportVersions::Tiny v1.10\n"; eval { # no excuses! # report our Perl details my $want = '5.006'; $v .= "perl: $] (wanted $want) on $^O from $^X\n\n"; }; defined($@) and diag("$@"); # Now, our module version dependencies: sub pmver { my ($module, $wanted) = @_; $wanted = " (want $wanted)"; my $pmver; eval "require $module;"; if ($@) { if ($@ =~ m/Can't locate .* in \@INC/) { $pmver = 'module not found.'; } else { diag("${module}: $@"); $pmver = 'died during require.'; } } else { my $version; eval { $version = $module->VERSION; }; if ($@) { diag("${module}: $@"); $pmver = 'died during VERSION check.'; } elsif (defined $version) { $pmver = "$version"; } else { $pmver = ''; } } # So, we should be good, right? return sprintf('%-45s => %-10s%-15s%s', $module, $pmver, $wanted, "\n"); } eval { $v .= pmver('Carp','any version') }; eval { $v .= pmver('Dancer','1.3111') }; eval { $v .= pmver('Dancer::ModuleLoader','any version') }; eval { $v .= pmver('Dancer::Plugin','any version') }; eval { $v .= pmver('Dancer::Test','any version') }; eval { $v .= pmver('File::Spec','any version') }; eval { $v .= pmver('HTTP::Headers','any version') }; eval { $v .= pmver('IO::Handle','any version') }; eval { $v .= pmver('IPC::Open3','any version') }; eval { $v .= pmver('Module::Build','0.3601') }; eval { $v .= pmver('Test::More','0.88') }; eval { $v .= pmver('strict','any version') }; eval { $v .= pmver('warnings','any version') }; # All done. $v .= <<'EOT'; Thanks for using my code. I hope it works for you. If not, please try and include this output in the bug report. That will help me reproduce the issue and solve your problem. EOT diag($v); ok(1, "we really didn't test anything, just reporting data"); $success = 1; # Work around another nasty module on CPAN. :/ no warnings 'once'; $Template::Test::NO_FLUSH = 1; exit 0; Dancer-Plugin-REST-0.11/t/default-serializer.t0000644000175000017500000000123012314270461020373 0ustar yanickyanickuse strict; use warnings; use Test::More; plan skip_all => 'XML::Simple required' unless eval "use XML::Simple; 1"; plan tests => 3; { use Dancer ':tests'; use Dancer::Plugin::REST; prepare_serializer_for_format; set serializer => 'XML'; get '/foo' => sub { return { hello => 'world' }; }; get '/foo.:format' => sub { return { hello => 'world' }; }; } use Dancer::Test; response_content_like '/foo' => qr/ qr/"hello"\s*:\s*"world"/, "ask for JSON"; response_content_like '/foo' => qr/ 1 + ($ENV{AUTHOR_TESTING} ? 1 : 0); my @module_files = ( 'Dancer/Plugin/REST.pm' ); # no fake home requested my $inc_switch = -d 'blib' ? '-Mblib' : '-Ilib'; use File::Spec; use IPC::Open3; use IO::Handle; open my $stdin, '<', File::Spec->devnull or die "can't open devnull: $!"; my @warnings; for my $lib (@module_files) { # see L my $stderr = IO::Handle->new; my $pid = open3($stdin, '>&STDERR', $stderr, $^X, $inc_switch, '-e', "require q[$lib]"); binmode $stderr, ':crlf' if $^O eq 'MSWin32'; my @_warnings = <$stderr>; waitpid($pid, 0); is($?, 0, "$lib loaded ok"); if (@_warnings) { warn @_warnings; push @warnings, @_warnings; } } is(scalar(@warnings), 0, 'no warnings found') if $ENV{AUTHOR_TESTING}; Dancer-Plugin-REST-0.11/t/03_resource.t0000644000175000017500000000533112314270461016737 0ustar yanickyanickuse strict; use warnings; use Dancer::ModuleLoader; use Test::More import => ['!pass']; # Dancer::Test had a bug in version previous 1.3059_01 that prevent this test # from running correctly. my $dancer_version = eval "\$Dancer::VERSION"; $dancer_version =~ s/_//g; plan skip_all => "Dancer 1.3059_01 is needed for this test (you have $dancer_version)" if $dancer_version < 1.305901; plan tests => 8; { package Webservice; use Dancer; use Dancer::Plugin::REST; use Test::More import => ['!pass']; resource user => 'get' => \&on_get_user, 'create' => \&on_create_user, 'delete' => \&on_delete_user, 'update' => \&on_update_user; my $users = {}; my $last_id = 0; sub on_get_user { my $id = params->{'id'}; { user => $users->{$id} }; } sub on_create_user { my $id = ++$last_id; my $user = params('body'); $user->{id} = $id; $users->{$id} = $user; { user => $users->{$id} }; } sub on_delete_user { my $id = params->{'id'}; my $deleted = $users->{$id}; delete $users->{$id}; { user => $deleted }; } sub on_update_user { my $id = params->{'id'}; my $user = $users->{$id}; return { user => undef } unless defined $user; $users->{$id} = { %$user, %{params('body')} }; { user => $users->{$id} }; } eval { resource failure => get => sub { 'GET' }, woobly => sub { }, }; like $@, qr{action 'woobly' not recognized}, "resource must have 4 hooks"; } use Dancer::Test; my $r = dancer_response(GET => '/user/1'); is_deeply $r->{content}, {user => undef}, "user 1 is not defined"; $r = dancer_response(POST => '/user', { body => {name => 'Alexis' }}); is_deeply $r->{content}, { user => { id => 1, name => "Alexis" } }, "create user works"; $r = dancer_response(GET => '/user/1'); is_deeply $r->{content}, {user => { id => 1, name => 'Alexis'}}, "user 1 is defined"; $r = dancer_response(PUT => '/user/1', { body => { nick => 'sukria', name => 'Alexis Sukrieh' } }); is_deeply $r->{content}, {user => { id => 1, name => 'Alexis Sukrieh', nick => 'sukria'}}, "user 1 is updated"; $r = dancer_response(DELETE => '/user/1'); is_deeply $r->{content}, {user => { id => 1, name => 'Alexis Sukrieh', nick => 'sukria'}}, "user 1 is deleted"; $r = dancer_response(GET => '/user/1'); is_deeply $r->{content}, {user => undef}, "user 1 is not defined"; $r = dancer_response(POST => '/user', { body => { name => 'Franck Cuny' } }); is_deeply $r->{content}, { user => { id => 2, name => "Franck Cuny" } }, "id is correctly increased"; Dancer-Plugin-REST-0.11/t/04_plugin_settings.t0000644000175000017500000000302212314270461020322 0ustar yanickyanickuse strict; use warnings; use Dancer::ModuleLoader; use Test::More import => ['!pass']; plan skip_all => "JSON is needed for this test" unless Dancer::ModuleLoader->load('JSON'); plan skip_all => "YAML is needed for this test" unless Dancer::ModuleLoader->load('YAML'); my $data = { foo => 42 }; my $json = JSON::encode_json($data); my $yaml = YAML::Dump($data); { package Webservice; use Dancer; use Dancer::Plugin::REST; set environment => 'test'; set show_errors => 1; prepare_serializer_for_format; get '/' => sub { "root" }; get '/:something.:format' => sub { $data; }; } use Dancer::Test; my @tests = ( { request => [GET => '/'], response => 'root', }, { request => [GET => '/foo.json'], response => $json, }, { request => [GET => '/foo.yml'], response => $yaml, }, { request => [GET => '/'], response => 'root', }, ); plan tests => 6; for my $test ( @tests ) { my $response = dancer_response(@{$test->{request}}); if (ref($test->{response})) { like( $response->{content}, $test->{response}, "response looks good for '@{$test->{request}}'" ); } else { is( $response->{content}, $test->{response}, "response looks good for '@{$test->{request}}'" ); } } my $response = dancer_response( GET => '/foo.foobar' ); is $response->status => 404, 'error code 404'; like $response->content => qr/unsupported format requested: foobar/ms; Dancer-Plugin-REST-0.11/t/05_serializer_and_resource.t0000644000175000017500000000336512314270461022021 0ustar yanickyanickuse strict; use warnings; use Dancer::ModuleLoader; use Test::More import => ['!pass']; # Dancer::Test had a bug in version previous 1.3059_01 that prevent this test # from running correctly. my $dancer_version = eval "\$Dancer::VERSION"; $dancer_version =~ s/_//g; plan skip_all => "Dancer 1.3059_01 is needed for this test (you have $dancer_version)" if $dancer_version < 1.305901; plan skip_all => 'tests require JSON' unless Dancer::ModuleLoader->load('JSON'); { package Webservice; use Dancer; use Dancer::Plugin::REST; setting environment => 'testing'; prepare_serializer_for_format; resource user => get => sub { [ id => params->{id}, format => params->{format} ] }, delete => sub { [ id => params->{id}, format => params->{format} ] }, create => sub { [ user => params->{user}, format => params->{format} ] }, update => sub { [ user => params->{user}, format => params->{format} ] }; } use Dancer::Test; plan tests => 4; my $r = dancer_response GET => '/user/42.json'; is $r->{content}, '["id","42","format","json"]' => "'id' and 'format' params are properly set for resource during GET"; $r = dancer_response POST => '/user.json', { params => { user => 'test' } }; is $r->{content}, '["user","test","format","json"]' => "'user' and 'format' params properly set for resource during POST"; $r = dancer_response PUT => '/user/1.json', { params => { user => 'anothertest' } }; is $r->{content}, '["user","anothertest","format","json"]' => "'user' and 'format' params properly set for resource during PUT"; $r = dancer_response DELETE => '/user/6.json'; is $r->{content}, '["id","6","format","json"]' => "'id' and 'format' params properly set for resource during DELETE"; Dancer-Plugin-REST-0.11/README0000644000175000017500000000610312314270461015034 0ustar yanickyanickNAME Dancer::Plugin::REST - A plugin for writing RESTful apps with Dancer VERSION version 0.11 DESCRIPTION This plugin helps you write a RESTful webservice with Dancer. SYNOPSYS package MyWebService; use Dancer; use Dancer::Plugin::REST; prepare_serializer_for_format; get '/user/:id.:format' => sub { User->find(params->{id}); }; # curl http://mywebservice/user/42.json { "id": 42, "name": "John Foo", email: "john.foo@example.com"} # curl http://mywebservice/user/42.yml -- id: 42 name: "John Foo" email: "john.foo@example.com" KEYWORDS prepare_serializer_for_format When this pragma is used, a before filter is set by the plugin to automatically change the serializer when a format is detected in the URI. That means that each route you define with a :format token will trigger a serializer definition, if the format is known. This lets you define all the REST actions you like as regular Dancer route handlers, without explicitly handling the outgoing data format. resource This keyword lets you declare a resource your application will handle. resource user => get => sub { # return user where id = params->{id} }, create => sub { # create a new user with params->{user} }, delete => sub { # delete user where id = params->{id} }, update => sub { # update user with params->{user} }; # this defines the following routes: # GET /user/:id # GET /user/:id.:format # POST /user # POST /user.:format # DELETE /user/:id # DELETE /user/:id.:format # PUT /user/:id # PUT /user/:id.:format helpers Some helpers are available. This helper will set an appropriate HTTP status for you. status_ok status_ok({users => {...}}); Set the HTTP status to 200 status_created status_created({users => {...}}); Set the HTTP status to 201 status_accepted status_accepted({users => {...}}); Set the HTTP status to 202 status_bad_request status_bad_request("user foo can't be found"); Set the HTTP status to 400. This function as for argument a scalar that will be used under the key error. status_not_found status_not_found("users doesn't exists"); Set the HTTP status to 404. This function as for argument a scalar that will be used under the key error. LICENCE This module is released under the same terms as Perl itself. AUTHORS This module has been written by Alexis Sukrieh "" and Franck Cuny. SEE ALSO Dancer AUTHORS * Alexis Sukrieh * Franck Cuny COPYRIGHT AND LICENSE This software is copyright (c) 2010 by Alexis Sukrieh. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.