perlmojoliciousmojolicious-lite

Optional POST Parameters in Mojolicious Lite with Perl


Is there a way to denote a POST parameter as optional in Perl using Mojolicious Lite? For instance, is there a way to make the server not return 404 if param2 is not defined in the request body?

post "/my_post" => \&render(post_callback);

sub post_callback {
    my ($mojo) = @_;
    my $param1 = $mojo->param("param1");
    my $param2 = $mojo->param("param2");
}

Solution

  • My problem was that I misunderstood how mojolicious was routing to the callback. The following code works with both parameters being optional:

    #!/usr/bin/env perl
    use strict;
    use warnings;
    use Mojolicious::Lite;
    
    post '/' => sub {
        my ($mojo) = @_;
        my $param1 = $mojo->param("param1");
        my $param2 = $mojo->param("param2");
        $mojo->render(text => "param1: $param1, param2: $param2");
    };
    
    app->start;
    

    If you run this using: ./my_server.pl daemon you will be able to send POST requests with any combination of parameters.