Debian Codegraph @

lib/Dancer2/Manual/Cookbook.pod

raw
1 package Dancer2::Manual::Cookbook;
2 # ABSTRACT: Example-driven quick-start to the Dancer2 web framework
3
4 __END__
5
6 =pod
7
8 =encoding UTF-8
9
10 =head1 NAME
11
12 Dancer2::Manual::Cookbook - Example-driven quick-start to the Dancer2 web framework
13
14 =head1 VERSION
15
16 version 2.2.2
17
18 =head1 Description
19
20 A quick-start guide with examples to get you up and running with the Dancer2
21 web framework. This document will be twice as useful if you finish reading
22 the manual (L<Dancer2::Manual>) first, but that is not required... :-)
23
24 =head1 Route Recipes
25
26 =head2 The simplest Dancer2 web app
27
28 Dancer2 has been designed to be easy to work with - it's trivial to write a
29 simple web app, but still has the power to work with larger projects. To
30 start with, let's make an incredibly simple "Hello World" example:
31
32 #!/usr/bin/env perl
33 package MyApp;
34 use Dancer2;
35
36 get '/' => sub {
37 return "Hello, world!";
38 };
39
40 MyApp->to_app();
41
42 Yes - the above is a fully-functioning web app; running that script with
43 C<plackup MyApp.psgi> will launch a webserver listening on the default
44 port (5000). Now you can make a request:
45
46 $ curl http://localhost:5000/
47 Hello, world!
48
49 Note that you don't need to use the C<strict> and C<warnings> pragmas; they
50 are already loaded by Dancer2.
51
52 =head2 Default Route
53
54 You can set up a default route to help trap C<404> errors in a
55 consistent way, or to handle multiple routes in a consistent
56 manner. A default route handler will handle any request that doesn't get
57 served by any other route.
58
59 All you need to do is set up the following route as the B<last> route:
60
61 any qr{.*} => sub {
62 status 'not_found';
63 template 'special_404', { path => request->path };
64 };
65
66 Then you can set up the F<special_404.tt> template like so:
67
68 You tried to reach [% path %], but it is unavailable at the moment.
69
70 Please try again or contact us at <[email protected]>.
71
72 =head2 Using the C<auto_page> feature for automatic route creation
73
74 For simple "static" pages you can simply enable the C<auto_page> config
75 setting; this means you don't need to declare a route handler for those
76 pages; if a request is for C</foo/bar>, Dancer2 will check for a matching
77 view (e.g. C</foo/bar.tt>) and render it with the default layout, if
78 found. For full details, see the documentation for the L<auto_page
79 setting|Dancer2::Config/"auto_page">.
80
81 =head2 Enabling and disabling routes with config and Module::Runtime
82
83 For various reasons you may want to be able to turn routes on and off in
84 your app without having to comment out sections of code. This is easily
85 accomplished if you encapsulate each route handler (or group of related
86 handlers) in a separate module, and load the wanted routes at runtime.
87
88 In C<MyApp::Route::Foo>:
89
90 package MyApp::Route::Foo;
91
92 use Dancer2 appname => 'MyApp';
93
94 get '/foo' => sub { return "bar" };
95
96 In C<MyApp::Route::Baz>:
97
98 package MyApp::Route::Baz;
99
100 use Dancer2 appname => 'MyApp';
101
102 get '/baz' => sub { return "qux" };
103
104 In your C<config.yaml>:
105
106 route_modules :
107 Foo : 1
108 Baz : 0
109
110 In your main route controller:
111
112 use Dancer2;
113 use Module::Runtime 'require_module';
114
115 my $module_base = 'MyApp::Route::';
116
117 my %modules = %{ config->{route_modules} };
118
119 my @required_modules = grep { $modules{$_} } keys %modules;
120
121 require_module( $module_base . $_ ) for @required_modules;
122
123 Now your app will expose C</foo> but requests to C</baz> will return a
124 404 response.
125
126 =head2 Using the prefix feature to split your application
127
128 For better maintainability, you may want to separate some of your application
129 components into different packages. Let's say we have a simple web app with an
130 admin section and want to maintain this in a different package:
131
132 package myapp;
133 use Dancer2;
134 use myapp::admin;
135
136 prefix undef;
137
138 get '/' => sub {...};
139
140 1;
141
142 package myapp::admin;
143 use Dancer2 appname => 'myapp';
144
145 prefix '/admin';
146
147 get '/' => sub {...};
148
149 1;
150
151 The following routes will be generated for us:
152
153 - get /
154 - get /admin/
155 - head /
156 - head /admin/
157
158 By default, a separate application is created for every package that uses
159 Dancer2. The C<appname> tag is used to collect routes and hooks into a
160 single Dancer2 application. In the above example, C<appname =E<gt> 'myapp'>
161 adds the routes from C<myapp::admin> to the routes of the app C<myapp>.
162
163 When using multiple applications please ensure that your path definitions do
164 not overlap. For example, if using a default route as described above, once
165 a request is matched to the default route then no further routes (or
166 applications) will be reached.
167
168 =head1 Template Recipes
169
170 =head2 UsingTemplate Toolkit's WRAPPER directive in Dancer2
171
172 Dancer2 already provides a WRAPPER-like ability, which we call a "layout".
173 The reason we don't use Template Toolkit's WRAPPER (which also makes us
174 incompatible with it) is because not all template systems support it.
175 In fact, most don't.
176
177 However, you might want to use it to be able to define C<META> and
178 regular L<Template::Toolkit> variables.
179
180 These few steps will get you there:
181
182 =over 4
183
184 =item * Disable the layout in Dancer2
185
186 You can do this by simply commenting (or removing) the C<layout>
187 configuration in the config file.
188
189 =item * Use the Template Toolkit template engine
190
191 Change the configuration of the template to Template Toolkit:
192
193 # in config.yml
194 template: "template_toolkit"
195
196 =item * Tell the Template Toolkit engine which wrapper to use
197
198 # in config.yml
199 # ...
200 engines:
201 template:
202 template_toolkit:
203 WRAPPER: layouts/main.tt
204
205 =back
206
207 Done! Everything will work fine out of the box, including variables and
208 C<META> variables.
209
210 Please note that disabling the internal layout it will also disable the
211 hooks C<before_layout_render> and C<after_layout_render>.
212
213 =head2 Customizing Template Toolkit in Dancer2
214
215 Please see L<Dancer2::Template::TemplateToolkit|Dancer2::Template::TemplateToolkit/"ADVANCED CUSTOMIZATION">
216 for more details.
217
218 =head1 Error Recipes
219
220 =head2 Delivering custom error pages
221
222 =head3 At the Core
223
224 In Dancer2, creating new errors is done by creating a new L<Dancer2::Core::Error>
225
226 my $oopsie = Dancer2::Core::Error->new(
227 status => 418,
228 message => "This is the Holidays. Tea not acceptable. We want eggnog.",
229 app => $app,
230 )
231
232 If not given, the status code defaults to a 500, there is no need for a message if
233 we feel taciturn, and while the C<$app> (which is a I<Dancer2::Core::App>
234 object holding all the pieces of information related to the current request) is
235 needed if we want to take advantage of the templates, we can also do without.
236
237 However, to be seen by the end user, we have to populate the L<Dancer2::Core::Response>
238 object with the error's data. This is done via:
239
240 $oopsie->throw($response);
241
242 Or, if we want to use the response object already present in the C<$app>
243 (which is usually the case):
244
245 $oopsie->throw;
246
247 This populates the status code of the response, sets its content, and throws a
248 I<halt()> in the dispatch process.
249
250 =head3 What it will look like?
251
252 The error object has quite a few ways to generate its content.
253
254 First, it can be explicitly given
255
256 my $oopsie = Dancer2::Core::Error->new(
257 content => '<html><body><h1>OMG</h1></body></html>',
258 );
259
260 If the C<$content> was not given, the error will check if there is a
261 template by the name of the status code (so, say you're using Template
262 Toolkit, F<418.tt>) and will use it to generate the content, passing it
263 the error's C<$message>, C<$status> code and C<$title> (which, if not
264 specified, will be the standard HTTP error definition for the status code).
265
266 If there is no template, the error will then look for a static page (to
267 continue with our example, F<418.html>) in the F<public/> directory.
268
269 And finally, if all of that failed, the error object will fall back on
270 an internal template.
271
272 =head3 Errors in Routes
273
274 The simplest way to use errors in routes is:
275
276 get '/xmas/gift/:gift' => sub {
277 die "sorry, we're all out of ponies\n"
278 if route_parameters->get('gift') eq 'pony';
279 };
280
281 The die will be intercepted by Dancer, converted into an error (status
282 code 500, message set to the dying words) and passed to the response.
283
284 In the cases where more control is required, C<send_error()> is the way to go:
285
286 get '/glass/eggnog' => sub {
287 send_error "Sorry, no eggnog here", 418;
288 };
289
290 And if total control is needed:
291
292 get '/xmas/wishlist' => sub {
293 Dancer2::Core::Error->new(
294 response => response(),
295 status => 406,
296 message => "nothing but coal for you, I'm afraid",
297 template => 'naughty/index',
298 )->throw unless user_was_nice();
299
300 ...;
301 };
302
303 =head1 Configuration Recipes
304
305 =head2 Accessing configuration information from a separate script
306
307 You may want to access your webapp's configuration from outside your
308 webapp. You could, of course, use the YAML module of your choice and load
309 your webapps's F<config.yml>, but chances are that this is not convenient.
310
311 Use Dancer2 instead. You can simply use the values from F<config.yml>
312 and some additional default values:
313
314 # bin/show_app_config.pl
315 use Dancer2;
316 printf "template: %s\n", config->{'template'}; # simple
317 printf "log: %s\n", config->{'log'}; # undef
318
319 Note that C<< config->{log} >> should result in an uninitialized warning
320 on a default scaffold since the environment isn't loaded and
321 log is defined in the environment but not in F<config.yml>. Hence C<undef>.
322
323 Dancer2 will load your F<config.yml> configuration file along with the
324 correct environment file located in your F<environments/> directory.
325
326 The environment is determined by two environment variables in the following
327 order:
328
329 =over 4
330
331 =item * DANCER_ENVIRONMENT
332
333 =item * PLACK_ENV
334
335 =back
336
337 If neither of those is set, it will default to loading the development
338 environment (typically C<$webapp/environment/development.yml>).
339
340 If you wish to load a different environment, you need to override these
341 variables.
342
343 You can call your script with the environment changed:
344
345 $ PLACK_ENV=production perl bin/show_app_config.pl
346
347 Or you can override them directly in the script (less recommended):
348
349 BEGIN { $ENV{'DANCER_ENVIRONMENT'} = 'production' }
350 use Dancer2;
351
352 ...
353
354 =head1 Database Recipes
355
356 =head2 Using DBIx::Class
357
358 L<DBIx::Class>, also known as DBIC, is one of the many Perl ORM
359 (I<Object Relational Mapper>) frameworks. It is easy to use DBIC in Dancer2
360 using L<Dancer2::Plugin::DBIx::Class>.
361
362 This example demonstrates a simple Dancer2 application that allows one to search
363 for authors or books. The application is connected to a database that contains
364 authors and their books. The website will have a single page with a form
365 that allows one to query books or authors and display the results.
366
367 =head3 Creating the application
368
369 $ dancer2 gen -a bookstore
370
371 To use the Template Toolkit as the template engine, specify it in the
372 configuration file:
373
374 # add in bookstore/config.yml
375 template: template_toolkit
376
377 =head3 Creating the view
378
379 We need a view to display the search form and the results, if any. The
380 results will be fed by the route to the view as an arrayref of results. Each
381 result is a hashref, with a author key containing the name of the author, and
382 a books key containing an arrayref of strings: the books' names.
383
384 # example of a list of results
385 [ { author => 'author 1',
386 books => [ 'book 1', 'book 2' ],
387 },
388 { author => 'author 2',
389 books => [ 'book 3', 'book 4' ],
390 }
391 ]
392
393 # bookstore/views/search.tt
394 <p>
395 <form action="/search">
396 Search query: <input type="text" name="query" />
397 </form>
398 </p>
399 <br>
400
401 An example of the view displaying the search form and results, if any:
402
403 <% IF query.length %>
404 <p>Search query was : <% query %>.</p>
405 <% IF results.size %>
406 Results:
407 <ul>
408 <% FOREACH result IN results %>
409 <li>Author: <% result.author.replace("((?i)$query)", '<b>$1</b>') %>
410 <ul>
411 <% FOREACH book IN result.books %>
412 <li><% book.replace("((?i)$query)", '<b>$1</b>') %>
413 <% END %>
414 </ul>
415 <% END %>
416 <% ELSE %>
417 No result
418 <% END %>
419 <% END %>
420
421 =head3 Creating a Route
422
423 A simple route, to be added in the C<Bookstore.pm> module:
424
425 # add in bookstore/lib/Bookstore.pm
426 get '/search' => sub {
427 my $query = query_parameters->get('query');
428 my @results = ();
429
430 if ( length $query ) {
431 @results = _perform_search($query);
432 }
433
434 template search => {
435 query => $query,
436 results => \@results,
437 };
438 };
439
440 =head3 Creating a database
441
442 We create a SQLite file database:
443
444 $ sqlite3 bookstore.db
445 CREATE TABLE author(
446 id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
447 firstname text default '' not null,
448 lastname text not null
449 );
450
451 CREATE TABLE book(
452 id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
453 author INTEGER REFERENCES author (id),
454 title text default '' not null
455 );
456
457 Now, to populate the database with some data, we use L<DBIx::Class>:
458
459 # populate_database.pl
460 package My::Bookstore::Schema;
461 use base qw(DBIx::Class::Schema::Loader);
462 package main;
463 my $schema = My::Bookstore::Schema->connect('dbi:SQLite:dbname=bookstore.db');
464 $schema->populate('Author', [
465 [ 'firstname', 'lastname'],
466 [ 'Ian M.', 'Banks' ],
467 [ 'Richard', 'Matheson'],
468 [ 'Frank', 'Herbert' ],
469 ]);
470 my @books_list = (
471 [ 'Consider Phlebas', 'Banks' ],
472 [ 'The Player of Games', 'Banks' ],
473 [ 'Use of Weapons', 'Banks' ],
474 [ 'Dune', 'Herbert' ],
475 [ 'Dune Messiah', 'Herbert' ],
476 [ 'Children of Dune', 'Herbert' ],
477 [ 'The Night Stalker', 'Matheson' ],
478 [ 'The Night Strangler', 'Matheson' ],
479 );
480 # transform author names into ids
481 $_->[1] = $schema->resultset('Author')->find({ lastname => $_->[1] })->id
482 foreach (@books_list);
483 $schema->populate('Book', [
484 [ 'title', 'author' ],
485 @books_list,
486 ]);
487
488 Then run it in the directory where F<bookstore.db> sits:
489
490 perl populate_database.db
491
492 =head3 Using Dancer2::Plugin::DBIx::Class
493
494 There are 2 ways of configuring DBIC to understand how the data is organized
495 in your database:
496
497 =over 4
498
499 =item * Use auto-detection
500
501 The configuration file needs to be updated to indicate the use of the
502 Dancer2::Plugin::DBIx::Class plugin, define a new DBIC schema called C<Bookstore> and
503 to indicate that this schema is connected to the SQLite database we created.
504
505 # add in bookstore/config.yml
506 plugins:
507 DBIC:
508 Bookstore:
509 dsn: "dbi:SQLite:dbname=bookstore.db"
510
511 Now, C<_perform_search> can be implemented using L<Dancer2::Plugin::DBIx::Class>. The
512 plugin gives you access to an additional keyword called B<schema>, which you
513 give the name of schema you want to retrieve. It returns a C<DBIx::Class::Schema::Loader>
514 which can be used to get a resultset and perform searches, as per standard
515 usage of DBIX::Class.
516
517 # add in bookstore/lib/Bookstore.pm
518 sub _perform_search {
519 my ($query) = @_;
520 my $bookstore_schema = schema 'Bookstore';
521 my @results;
522 # search in authors
523 my @authors = $bookstore_schema->resultset('Author')->search({
524 -or => [
525 firstname => { like => "%$query%" },
526 lastname => { like => "%$query%" },
527 ]
528 });
529 push @results, map {
530 { author => join(' ', $_->firstname, $_->lastname),
531 books => [],
532 }
533 } @authors;
534 my %book_results;
535 # search in books
536 my @books = $bookstore_schema->resultset('Book')->search({
537 title => { like => "%$query%" },
538 });
539 foreach my $book (@books) {
540 my $author_name = join(' ', $book->author->firstname, $book->author->lastname);
541 push @{$book_results{$author_name}}, $book->title;
542 }
543 push @results, map {
544 { author => $_,
545 books => $book_results{$_},
546 }
547 } keys %book_results;
548 return @results;
549 }
550
551 =item * Use home made schema classes
552
553 The L<DBIx::Class::MooseColumns> lets you write the DBIC schema classes
554 using L<Moose>. The schema classes should be put in a place that Dancer2
555 will find. A good place is in F<bookstore/lib/>.
556
557 Once your schema classes are in place, all you need to do is modify F<config.yml>
558 to specify that you want to use them, instead of the default auto-detection method:
559
560 # change in bookstore/config.yml
561 plugins:
562 DBIC:
563 bookstore:
564 schema_class: My::Bookstore::Schema
565 dsn: "dbi:SQLite:dbname=bookstore.db"
566
567 =back
568
569 Our bookstore lookup application can now be started using the built-in server:
570
571 # start the web application
572 plackup bin/app.psgi
573
574 =head1 Authentication Recipes
575
576 Writing a form for authentication is simple: we check the user credentials
577 on a request and decide whether to continue or redirect them to a form.
578 The form allows them to submit their username and password; we save that
579 and create a session for them so when they try the original request,
580 we recognize the user and allow them in.
581
582 =head2 Basic Application
583
584 The application is fairly simple. We have a route that needs authentication,
585 we have a route for showing the login page, and we have a route for posting
586 login information and creating a session.
587
588 package MyApp;
589 use Dancer2;
590
591 get '/' => sub {
592 session('user')
593 or redirect('/login');
594
595 template index => {};
596 };
597
598 get '/login' => sub {
599 template login => {};
600 };
601
602 post '/login' => sub {
603 my $username = query_parameters->get('username');
604 my $password = query_parameters->get('password');
605 my $redir_url = query_parameters->get('redirect_url') || '/login';
606
607 $username eq 'john' && $password eq 'correcthorsebatterystaple'
608 or redirect $redir_url;
609
610 session user => $username;
611 redirect $redir_url;
612 };
613
614 =head2 Tiny Authentication Helper
615
616 L<Dancer2::Plugin::Auth::Tiny> allows you to abstract away not only the
617 part that checks whether the session exists, but to also generate a
618 redirect with the right path and return URL.
619
620 We simply have to define what routes needs a login using Auth::Tiny's
621 C<needs> keyword.
622
623 get '/' => needs login => sub {
624 template index => {};
625 };
626
627 It creates a proper return URL using C<uri_for> and the address from which
628 the user arrived.
629
630 We can thus decorate all of our private routes to require authentication in
631 this manner. If a user does not have a session, it will automatically forward
632 it to I</login>, in which we would render a form for the user to send a login request.
633
634 Auth::Tiny even provides a new parameter, C<return_url>, which can be used to send
635 the user back to their original requested path.
636
637 =head2 Password Hashing
638
639 L<Dancer2::Plugin::Passphrase> provides a simple passwords-as-objects interface with
640 sane defaults for hashed passwords which you can use in your web application. It uses
641 B<bcrypt> as the default but supports anything the L<Digest> interface does.
642
643 Assuming we have the original user-creation form submitting a username and password:
644
645 package MyApp;
646 use Dancer2;
647 use Dancer2::Plugin::Passphrase;
648 post '/register' => sub {
649 my $username = query_parameters->get('username');
650 my $password = passphrase(
651 query_parameters->get('password')
652 )->generate;
653
654 # $password is now a hashed password object
655 save_user_in_db( $username, $password->rfc2307 );
656
657 template registered => { success => 1 };
658 };
659
660 We can now add the B<POST> method for verifying that username and password:
661
662 post '/login' => sub {
663 my $username = query_parameters->get('username');
664 my $password = query_parameters->get('password');
665 my $saved_pass = fetch_password_from_db($username);
666
667 if ( passphrase($password)->matches($saved_pass) ) {
668 session user => $username;
669 redirect query_parameters->get('return_url') || '/';
670 }
671
672 # let's render instead of redirect...
673 template login => { error => 'Invalid username or password' };
674 };
675
676 =head1 JSON/Serialization/API Recipes
677
678 =head2 Writing a REST application
679
680 With Dancer2, it's easy to write REST applications. Dancer2 provides helpers
681 to serialize and deserialize for the following data formats:
682
683 =over 4
684
685 =item JSON
686
687 =item YAML
688
689 =item XML
690
691 =item Data::Dumper
692
693 =back
694
695 To activate this feature, you only have to set the C<serializer> setting to
696 the format you require, for instance in your config file:
697
698 serializer: JSON
699
700 Or directly in your code:
701
702 set serializer => 'JSON';
703
704 From now, all hashrefs or arrayrefs returned by a route will be serialized
705 to the format you chose, and all data received from B<POST> or B<PUT>
706 requests will be automatically deserialized.
707
708 get '/hello/:name' => sub {
709 # this structure will be returned to the client as
710 # {"name":"$name"}
711 return { name => query_parameters->get('name') };
712 };
713
714 It's possible to let the client choose which serializer to use. For
715 this, use L<Dancer2::Serializer::Mutable>, and an appropriate serializer will be
716 chosen from the C<Content-Type> header.
717
718 It's also possible to return a custom error using the
719 L<send_error|Dancer2::Manual::Keywords/send_error> keyword. When you don't
720 use a serializer, the C<send_error> function will take a string as first
721 parameter (the message), and an optional HTTP code. When using a serializer,
722 the message can be a string, an arrayref or a hashref:
723
724 get '/hello/:name' => sub {
725 if (...) {
726 send_error("you can't do that");
727 # or
728 send_error({reason => 'access denied', message => "no"});
729 }
730 };
731
732 The content of the error will be serialized using the appropriate
733 serializer.
734
735 =head2 Using the serializer
736
737 Serializers essentially do two things:
738
739 =over 4
740
741 =item * Deserialize incoming requests
742
743 When a user makes a request with serialized input, the serializer
744 automatically deserializes it into actual input parameters.
745
746 =item * Serialize outgoing responses
747
748 When you return a data structure from a route, it will automatically
749 serialize it for you before returning it to the user.
750
751 =back
752
753 =head3 Configuring
754
755 In order to configure a serializer, you just need to pick which format
756 you want for encoding/decoding (e.g. L<JSON|Dancer2::Serializer::JSON>)
757 and set it up using the C<serializer> configuration keyword.
758
759 It is recommended to explicitly add it in the actual code instead of the
760 configuration file so it doesn't apply automatically to every app that
761 reads the configuration file (unless that's what you want):
762
763 package MyApp;
764 use Dancer2;
765 set serializer => 'JSON'; # Dancer2::Serializer::JSON
766
767 ...
768
769 =head3 Using
770
771 Now that we have a serializer set up, we can just return data structures:
772
773 get '/' => sub {
774 return { resources => \%resources };
775 };
776
777 When we return this data structure, it will automatically be serialized
778 into JSON. No other code is necessary.
779
780 We also now receive requests in JSON:
781
782 post '/:entity/:id' => sub {
783 my $entity = route_parameters->get('entity');
784 my $id = route_parameters->get('id');
785
786 # input which was sent serialized
787 my $user = body_parameters->get('user');
788
789 ...
790 };
791
792 We can now make a serialized request:
793
794 $ curl -X POST http://ourdomain/person/16 -d '{"user":"sawyer_x"}'
795
796 =head3 Supporting both serialized and non-serialized routes
797
798 Serializers are engines. They affect a Dancer Application, which means
799 that once you've set a serializer, B<all> routes within that package
800 will be serialized and deserialized. This is how the feature works.
801
802 As suggested above, if you would like to have both, you need to create
803 another application which will not be serialized.
804
805 A common usage for this is an API providing serialized endpoints (and
806 receiving serialized requests) and providing rendered pages.
807
808 # MyApp.pm
809 package MyApp;
810 use Dancer2;
811
812 # another useful feature:
813 set auto_page => 1;
814
815 get '/' => sub { template 'index' => {...} };
816
817 # MyApp/API.pm
818 package MyApp::API;
819 use Dancer2;
820 set serializer => 'JSON'; # or any other serializer
821
822 get '/' => sub { +{ resources => \%resources, ... } };
823
824 # user-specific routes, for example
825 prefix '/users' => sub {
826 get '/view' => sub {...};
827 get '/view/:id' => sub {...};
828 put '/add' => sub {...}; # automatically deserialized params
829 };
830
831 ...
832
833 Then those will be mounted together for a single app:
834
835 # handler: app.pl:
836 use MyApp;
837 use MyApp::API;
838 use Plack::Builder;
839
840 builder {
841 mount '/' => MyApp->to_app;
842 mount '/api' => MyApp::API->to_app;
843 };
844
845 If you want use redirect from a mounted package to the application's root
846 URI, L<Dancer2::Plugin::RootURIFor> makes this possible:
847
848 package OurWiki;
849 use Dancer;
850 use Dancer2::Plugin::RootURIFor;
851
852 get '/:some_path' => sub {
853 redirect root_uri_for('/');
854 }
855
856 =head3 An example: Writing API interfaces
857
858 This example demonstrates an app that makes a request to a weather
859 API and then displays it dynamically in a web page.
860
861 Other than L<Dancer2> for defining routes, we will use L<HTTP::Tiny>
862 to make the weather API request, L<JSON> to decode it from JSON format,
863 and finally L<Path::Tiny> to provide a fully-qualified path to our
864 template engine.
865
866 use JSON;
867 use Dancer2;
868 use HTTP::Tiny;
869 use Path::Tiny;
870
871 =head4 Configuration
872
873 We use the L<Template::Toolkit> template system for this app.
874 Dancer searches for our templates in our views directory, which defaults
875 to I<views> directory in our current directory. Since we want to put our
876 template in our current directory, we will configure that. However,
877 I<Template::Toolkit> does not want us to provide a relative path without
878 configuring it to allow it. This is a security issue. So, we're using
879 L<Path::Tiny> to create a full path to where we are.
880
881 We also unset the default layout, so Dancer won't try to wrap our template
882 with another one. This is a feature in Dancer to allow you to wrap your
883 templates with a layout when your templating system doesn't support it. Since
884 we're not using a layout here, we don't need it.
885
886 set template => 'template_toolkit'; # set template engine
887 set layout => undef; # disable layout
888 set views => Path::Tiny->cwd->absolute; # full path to views
889
890 Now, we define our URL:
891
892 my $url = 'http://api.openweathermap.org/data/2.5/weather?id=5110629&units=imperial';
893
894 =head4 Route
895
896 We will define a main route which, upon a request, will fetch the information
897 from the weather API, decode it, and then display it to the user.
898
899 Route definition:
900
901 get '/' => sub {
902 ...
903 };
904
905 Editing the stub of route dispatching code, we start by making the request
906 and decoding it:
907
908 # fetch data
909 my $res = HTTP::Tiny->new->get($url);
910
911 # decode request
912 my $data = decode_json $res->{'content'};
913
914 The data is not just a flat hash. It's a deep structure. In this example, we
915 will filter it for only the simple keys in the retrieved data:
916
917 my $metrics = { map +(
918 ref $data->{$_} ? () : ( $_ => $data->{$_} )
919 ), keys %{$data} };
920
921 All that is left now is to render it:
922
923 template index => { metrics => $metrics };
924
925 =head3 Example: Feeding graph data through AJAX
926
927 Let us assume we are building an application that uses a plotting library
928 to generate a graph and expects to get its data, which is in the form
929 of word count from an AJAX call.
930
931 For the graph, we need the url C</data> to return a JSON representation
932 of the word count data. Dancer in fact has a C<encode_json()> function that takes
933 care of the JSON encapsulation.
934
935 get '/data' => sub {
936 open my $fh, '<', $count_file;
937
938 my %contestant;
939 while (<$fh>) {
940 chomp;
941 my ( $date, $who, $count ) = split '\s*,\s*';
942
943 my $epoch = DateTime::Format::Flexible->parse_datetime($date)->epoch;
944 my $time = 1000 * $epoch;
945 $contestant{$who}{$time} = $count;
946 }
947
948 my @json; # data structure that is going to be JSONified
949
950 while ( my ( $peep, $data ) = each %contestant ) {
951 push @json, {
952 label => $peep,
953 hoverable => \1, # so that it becomes JavaScript's 'true'
954 data => [ map { [ $_, $data->{$_} ] }
955 sort { $a <=> $b }
956 keys %$data ],
957 };
958 }
959
960 my $beginning = DateTime::Format::Flexible->parse_datetime( "2010-11-01")->epoch;
961 my $end = DateTime::Format::Flexible->parse_datetime( "2010-12-01")->epoch;
962
963 push @json, {
964 label => 'de par',
965 data => [
966 [$beginning * 1000, 0],
967 [ DateTime->now->epoch * 1_000,
968 50_000
969 * (DateTime->now->epoch - $beginning)
970 / ($end - $beginning)
971 ]
972 ],
973
974 };
975
976 send_as JSON => \@json ;
977 };
978
979 =head1 Dessert Recipes
980
981 (these are tasty tips and tricks that don't fit anywhere else)
982
983 =head2 Turning off warnings
984
985 The C<warnings> pragma is already used when one loads Dancer2. However, if
986 you I<really> do not want the C<warnings> pragma (for example, due to an
987 undesired warning about use of undef values), add a C<no warnings> pragma to
988 the appropriate block in your module or psgi file.
989
990 =head2 Troubleshooting hooks
991
992 You can make troubleshooting hook entries easier by ensuring their coderefs
993 are named, either by using L<Sub::Util> or using the refs of regular
994 functions.
995
996 package MyApp;
997
998 use Dancer2;
999
1000 use Sub::Util qw/ set_subname /;
1001
1002 hook 'before_request' =>
1003 set_subname my_before => sub { ... };
1004
1005 sub my_after { $::hook_counter++ }
1006
1007 hook 'after_request' => \&my_after;
1008
1009 ...
1010
1011 If you do so, they will appear as part of the core logs:
1012
1013 [MyApp] core @2025-06-15 15:02:36> Entering hook core.app.before_request in (eval 274) l. 1
1014 [MyApp] core @2025-06-15 15:02:36> running hook entry App::HookEntries::my_before in (eval 274) l. 1
1015 [MyApp] core @2025-06-15 15:02:36> Entering hook core.app.after_request in (eval 274) l. 1
1016 [MyApp] core @2025-06-15 15:02:36> running hook entry Dancer2::Core::App::__ANON__ in (eval 274) l. 1
1017 [MyApp] core @2025-06-15 15:02:36> running hook entry App::HookEntries::my_after in (eval 274) l. 1
1018
1019 =head1 AUTHOR
1020
1021 Dancer Core Developers
1022
1023 =head1 COPYRIGHT AND LICENSE
1024
1025 This software is copyright (c) 2026 by Alexis Sukrieh.
1026
1027 This is free software; you can redistribute it and/or modify it under
1028 the same terms as the Perl 5 programming language system itself.
1029
1030 =cut