ZetCode

Build a JSON API with Mojolicious::Lite

last modified November 25, 2026 Perl 5.44

Mojolicious::Lite is a way to write a Mojolicious web application in one Perl file. This tutorial builds a small library API with two operations: look up a book and record a loan. Programs use the API by sending HTTP requests and reading JSON responses rather than web pages.

Both Mojolicious::Lite and Test::Mojo come with the Mojolicious distribution. Install it with cpanm Mojolicious if needed. The examples were tested with Mojolicious 9.53. They use book records defined in the script and do not need a database or an external service.

One GET route

A route connects an HTTP method and a path to the code that handles the request. Here, a GET request for /status returns a short text message.

status_api.pl
#!/usr/bin/perl

use v5.34.0;
use warnings;
use Mojolicious::Lite;

get '/status' => sub {
    my ($c) = @_;
    $c->render(text => 'Library API is running');
};

app->start;

The module supplies get, which registers the route, and app, which returns the application. Mojolicious passes a controller object to the route's subroutine. We use it to build the response with render.

app->start runs the command given on the command line. The get command makes one request to the local app and prints the response body. It does not require a separately running server. -m production suppresses the development request trace.

$ perl status_api.pl get -m production /status
Library API is running

Read a route parameter

A route can match more than one path. The :id placeholder in /books/:id captures the book identifier from the path, so one subroutine handles requests for different books.

book_path.pl
#!/usr/bin/perl

use v5.34.0;
use warnings;
use Mojolicious::Lite;

get '/books/:id' => sub {
    my ($c) = @_;
    my $id = $c->param('id');
    $c->render(text => "Requested book: $id");
};

app->start;

When the request path is /books/dune, param('id') returns dune. The colon belongs in the route definition, not the request URL. At this stage the route echoes the ID without checking whether the book exists.

$ perl book_path.pl get -m production /books/dune
Requested book: dune

Return JSON

Instead of echoing the ID, look up its record in a hash keyed by book ID. Successful lookups return a JSON object with the title. A missing book returns an error object and HTTP status 404 Not Found.

book_lookup.pl
#!/usr/bin/perl

use v5.34.0;
use warnings;
use Mojolicious::Lite;

my %books = (
    dune => {title => 'Dune'},
    emma => {title => 'Emma'},
);

get '/books/:id' => sub {
    my ($c) = @_;
    my $id = $c->param('id');

    return $c->render(status => 404, json => {error => 'book not found'})
        unless exists $books{$id};

    $c->render(json => $books{$id});
};

app->start;

render(json => ...) encodes a Perl data structure as JSON and sets the Content-Type response header to application/json. The response defaults to 200 OK when no status is set. The return after the missing-book response exits the subroutine so it cannot try to render a second response. The commands below print only the bodies; the final example checks the status codes and content type directly.

$ perl book_lookup.pl get -m production /books/dune
{"title":"Dune"}
$ perl book_lookup.pl get -m production /books/missing
{"error":"book not found"}

Accept a JSON request

Keep the book lookup and add POST /loans. Unlike the lookup, this request sends a JSON body with the book ID. On success the app records a loan and returns its ID with 201 Created.

books_api.pl
#!/usr/bin/perl

use v5.34.0;
use warnings;
use Mojolicious::Lite;

my %books = (
    dune => {title => 'Dune'},
    emma => {title => 'Emma'},
);
my @loans;

get '/books/:id' => sub {
    my ($c) = @_;
    my $id = $c->param('id');

    return $c->render(status => 404, json => {error => 'book not found'})
        unless exists $books{$id};

    $c->render(json => $books{$id});
};

post '/loans' => sub {
    my ($c) = @_;
    my $data = $c->req->json;

    if (ref $data ne 'HASH' || !defined $data->{book} || ref $data->{book}) {
        return $c->render(status => 400, json => {error => 'a book ID is required'});
    }

    my $id = $data->{book};
    return $c->render(status => 404, json => {error => 'book not found'})
        unless exists $books{$id};

    my $loan_id = push @loans, $id;
    $c->render(status => 201, json => {loan_id => $loan_id});
};

app->start;

$c->req->json decodes the request body. A JSON object becomes a hash reference, while malformed JSON returns undef. The first check rejects anything other than an object with a defined, non-reference book value and sends 400 Bad Request. If the object has that field but the ID is not in the catalog, the route sends 404.

push returns the new length of @loans, giving the loan its ID. The array persists only as long as the app process runs, and each command below starts a fresh process. The command is still named get, but -M POST changes the HTTP method. -H sets the request content type and -c supplies the body.

$ perl books_api.pl get -m production -M POST \
    -H 'Content-Type: application/json' -c '{"book":"dune"}' /loans
{"loan_id":1}
$ perl books_api.pl get -m production -M POST \
    -H 'Content-Type: application/json' -c '{}' /loans
{"error":"a book ID is required"}

Test the API with Test::Mojo

Test::Mojo loads the application and sends it local requests without a separate server. Put the test beside books_api.pl so it can load the same application used above.

books_api.t
use v5.34.0;
use warnings;
use FindBin qw($Bin);
use Mojo::File qw(path);
use Test::More;
use Test::Mojo;

my $t = Test::Mojo->new(path($Bin, 'books_api.pl'));

$t->get_ok('/books/dune')
    ->status_is(200)
    ->content_type_like(qr{^application/json\b})
    ->json_is('/title', 'Dune');

$t->get_ok('/books/missing')
    ->status_is(404)
    ->json_is('/error', 'book not found');

$t->post_ok('/loans' => json => {book => 'dune'})
    ->status_is(201)
    ->json_is('/loan_id', 1);

$t->post_ok('/loans' => json => {book => 'emma'})
    ->status_is(201)
    ->json_is('/loan_id', 2);

$t->post_ok('/loans' => json => {})
    ->status_is(400)
    ->json_is('/error', 'a book ID is required');

$t->post_ok('/loans' => {'Content-Type' => 'application/json'} => '{')
    ->status_is(400)
    ->json_is('/error', 'a book ID is required');

done_testing;

$Bin is the directory containing the test script, and path builds the file object that Test::Mojo uses to load the Lite app. The get_ok and post_ok methods check that the requests complete; status_is checks the HTTP status separately. In json_is, a JSON Pointer such as /title selects one field in the decoded response, so the test need not compare raw JSON text.

post_ok with json => ... encodes the request body and sets the content type. To send intentionally malformed JSON, the last request instead supplies the header and raw body. All requests use the same app instance, so the two successful loans receive consecutive IDs.

$ perl books_api.t
ok 1 - GET /books/dune
ok 2 - 200 OK
ok 3 - Content-Type is similar
ok 4 - exact match for JSON Pointer "/title"
ok 5 - GET /books/missing
ok 6 - 404 Not Found
ok 7 - exact match for JSON Pointer "/error"
ok 8 - POST /loans
ok 9 - 201 Created
ok 10 - exact match for JSON Pointer "/loan_id"
ok 11 - POST /loans
ok 12 - 201 Created
ok 13 - exact match for JSON Pointer "/loan_id"
ok 14 - POST /loans
ok 15 - 400 Bad Request
ok 16 - exact match for JSON Pointer "/error"
ok 17 - POST /loans
ok 18 - 400 Bad Request
ok 19 - exact match for JSON Pointer "/error"
1..19

Best practices

To try the API from a browser, run perl books_api.pl daemon -l http://127.0.0.1:3000 and open http://127.0.0.1:3000/books/dune. The address limits connections to your own machine. Stop the server with Ctrl-C when finished.

Keep this example local. A real loan API needs to check who is allowed to record a loan and store the records outside the web process. If multiple workers handle requests, each has its own copy of @loans; use a database-generated ID instead of the array length.

Source

Mojolicious::Lite · Mojolicious::Controller · Mojolicious get command · Test::Mojo

In this article we defined routes, used a path parameter to find a book, decoded a JSON request to record a loan, and verified the API with Test::Mojo. See also Perl JSON, Perl Test::More and Perl CPAN.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Perl tutorials.