[pm-h] JSON web services server side starting hints
Michael R. Davis
mrdvt92 at yahoo.com
Mon Oct 28 15:12:00 PDT 2013
> > I need to set up JSON web services (server side) as a simple interface to an existing database infrastructure. Can anyone recommend any building blocks, standards, etc.?
> From: Mark Allen <mrallen1 at yahoo.com>
> Sent: Saturday, October 26, 2013 12:13 AM
> http://advent.perldancer.org/2010/8-Writing REST web services with Dancer
So, I just wanted to follow up on my progress and research. It was a bit frustrating!
Even though REST is not a requirement, I looked into Dancer and it was okay but boy was it a lot of research to just get it to work under Apache CGI with Plack::Runner. I also DO NOT like that it's function based. To get there I had to write a session object which returns a lazy loading DBIx::Array database handle . But, overall I did like the dispatching (except I kept forgetting the sub is an anonymous sub to the function "get" so the "get" function needs a semicolon at the end of the anonymous sub block).
Next I'm going to look a the JSON RPC packages on CPAN. I've attached my code here as it really is throwaway at this time. I hope someone else can learn from it.
---
My Dancer CGI app,,,
$ cat dancer.cgi
#!/usr/bin/env perl
use Plack::Runner;
Plack::Runner->run('/var/www/cgi-bin/dancer.pl');
$ cat dancer.pl
#/usr/bin/perl
use strict;
use warnings;
use Dancer;
set 'logger' => 'console';
set 'show_errors' => 1;
set 'warnings' => 1;
our $session; #cannot set session here at compile time
sub session { #set session at run time
return $session||=STOP::Session->new(%{params()});
}
get '/' => sub {
content_type 'text/html';
return '<p>Hello World!<p>';
};
get '/env' => sub {
content_type 'text/plain';
return join "\n", map {sprintf "%s => %s", $_ => $ENV{$_}} sort keys %ENV;
};
get '/die' => sub {
die("Error: die\n");
};
prefix '/:database/:dag';
#content_type 'application/json';
content_type 'text/plain';
get '/params' => sub {
content_type 'text/plain';
return join "\n", map {sprintf "%s => %s", $_ => param($_)} sort keys %{params()};
};
get '/device/:id' => sub {
return to_json {
device => scalar({}),
id => param("id"),
schematxt => &session->schematxt,
date => &session->sdb->sqlscalar("SELECT SYSDATE FROM DUAL"),
};
};
get '/devices' => sub {
return to_json {
devices => scalar(&session->sdb->sqlarrayhash(&devices_sql(&session->schematxt), &session->userid)),
};
};
dance;
---
mrdvt92
More information about the Houston
mailing list