An example JSON endpoint in Perl

Tags:

We will be using a module from CPAN for this. A bit tricky to find, but quite simple once you've got it. Code mostly taken from the CPAN documents, but with a few holes filled in.

Here is test1.pl:

# Daemon version
use JSON::RPC::Server::Daemon;

# see documentation at:
# http://search.cpan.org/~dmaki/JSON-RPC-1.03/lib/JSON/RPC/Legacy.pm

my $server = JSON::RPC::Server::Daemon->new(LocalPort => 8080);
$server -> dispatch({'/test' => 'myApp'});
$server -> handle();

1;

And test2.pl:

#!/usr/bin/perl

use JSON::RPC::Client;

my $client = new JSON::RPC::Client;

my $uri = 'http://localhost:8080/test';
my $obj = {
method => 'sum', # or 'MyApp.sum'
params => [10, 20],
};

my $res = $client->call( $uri, $obj );

if($res){
if ($res->is_error) {
print "Error : ", $res->error_message;
} else {
print $res->result;
}
} else {
print $client->status_line;
}

# or

#$client->prepare($uri, ['sum', 'echo']);
#print $client->sum(10, 23);
#

And myApp.pl which is called by the server:

package myApp;

#optionally, you can also
use base qw(JSON::RPC::Procedure);  # for :Public and :Private attributes

sub sum : Public(a:num, b:num) {
my ($s, $obj) = @_;
return $obj->{a} + $obj->{b};
}

1;