SlideShare a Scribd company logo
use Perl
All the Perl that's Practical to Extract and Report
http://use.perl.org/
Title  Creating Web Services with XML-RPC
Date   2001.02.05 10:29
Author jjohn
Topic
http://use.perl.org/article.pl?sid=01/02/05/1438258

XML-RPC. SOAP. CORBA. Buzzwords galore, but possibly useful ones: this is, essentially,
technology that allows you to use web sites as a big API. Below we have an article about
XML-RPC; you might also want to check out an article by Paul Kulchenko on
www.perl.com, "Quick Start with SOAP".


Web Services Are More Than HTTP
One of Perl's enduring strengths is in allowing the programmer to easily manipulate UNIX
system resources, like /etc/passwd files, syslog and the filesystem. Perl is also a great tool
for building network applications (for more on this, see Lincoln Stein's excellent Network
Programming with Perl). As Nathan Torkington pointed out at YAPC 19100, the Perl
community hasn't yet fully embraced a component model of programming. Components are
libraries that can be used by programs written in any language. If you've dealt with Windows
programming particularly ASP coding, you are probably familiar with COM objects already.
But COM is just one vendor's implementation of components. Jon Udell argues that web
applications can be used in a component fashion. How many of you have stolen the HTML
from your favorite search engine's FORM and pasted it into your homepage? (I hope I'm not
the only one raising my hand!)

Although LWP is a powerful tool for "page scraping", you probably don't want to be parsing
HTML every time you make an object call. Fortunately, others have been working on this
problem. XML-RPC is a protocol for Remote Procedure Calls whose conversation over TCP
port 80 is encoded into XML. There are XML-RPC implementations written in many
languages for many platforms, including Perl.

Every XML-RPC application must have two parts, but there's a third that ought to be
required. If your script is making an XML-RPC request to some web service, you are making
client calls. If your script is answering XML-RPC requests, it is a listener. This seems to
describe a typical client-server system; what could be the third piece? Because XML-RPC is
language and platform neutral, it is essential that the listener's API be adequately
documented. Listing what procedures are expecting for input and the datatypes of the return
values is a necessity when dealing with sub-Perl languages, like Microsoft's VBScript.

The XML-RPC protocol is a call and response system, very much akin to HTTP. One
consequence of this is that XML-RPC doesn't support transactions or maintaining state.
Another problem is the conversation between listener and client is in clear-text. Despite these
limitations, there are still a number of applications for which XML-RPC is well suited.
Building a Client
The first quandary the novice XML-RPC Perl programmer will encounter is the name of the
module. Ken MacLeod's implementation is called Frontier::RPC, because XML-RPC was
the brain child of UserLand's Dave Winer, also of Frontier Naming issues aside, you can find
this module on your local CPAN. Installation follows the normal "perl Makefile.PL &&
make test && make install" cycle.

Let's assume there's an existing XML-RPC service you want to talk to. It defines the
following API:

Procedure Name | Input    | Output
-------------------------------------
hello_world    | <STRING> | <STRING>
-------------------------------------
sum            | <INT>,   |
               | <INT>    | <INT>
--------------------------------------
                   Figure 1

Remember, XML-RPC is designed to be language neutral. Every language's implementation
of XML-RPC translates the RPC into an XML description that tags each argument with a
specific XML-RPC datatype. Although Perl's DWIM-FU is strong, other languages are
strongly typed and need this additional information. When the listener responds,
Frontier::RPC translates the XML back into Perl datatypes.

Besides the API, we need to know the URL of the listener. For this example, we will use an
NT machine on my private network.

Enough yakkin'. Here's a simple test of this web service.

     1 #!/usr/bin/perl --
     2
     3 use strict;
     4 use Frontier::Client;
     5
     6 my $rps = Frontier::Client->new(
     7            url =>
"http://durgan.daisypark.net/jjohn/rpc_simple.asp",
     8                                );
     9
    10 print "Calling hello_world()n";
    11 eval { print $rps->call("hello_world", "jjohn"), "n" };
    12
    13 print "n=-----------------=n";
    14 print "Calling sum()n";
    15 eval { print $rps->call("sum", "1024", "128"), "n" };
    16
    17 print "ndonen";

                                          Figure 2
After including the library, we instantiate a new Frontier::Client object by passing the
URL of the web service. We can now make our RPC by using the call() method, which
expects the name of the remote procedure followed by a list of its arguments. If all goes well,
call() converts the return value of the procedure into a normal Perl datatype. Why am I
wrapping the method calls in evals? According to the XML spec, an XML parser is
supposed to halt as soon as it finds a parsing error. Since Frontier::RPC is encoding and
decoding XML, this is a precaution. Sometimes, bad things happen to good network packets.

The output looks like this:

[jjohn@marian xmlrpc]$ ./test_simple
Calling hello_world()
Hello, jjohn

=-----------------=
Calling sum()
1152

done
                  Figure 3

Sure, strings and numbers are useful but Real Functions ™ use collection types like arrays
and dictionaries. XML-RPC can handle those datatypes as well.

Here's an example of a procedure that returns an array of hashes. It is getting all the records
from an Access database stored on the aforementioend NT system. Notice that we are talking
to a different XML-RPC listener now.

     1 #!/usr/bin/perl --
     2
     3 use strict;
     4 use Frontier::Client;
     5 use Data::Dumper;
     6
     7 my $rps = Frontier::Client->new(
     8            url =>
"http://durgan.daisypark.net/jjohn/rpc_addresses.asp",
     9                                );
    10
    11 print "nCalling dump_address_book()n";
    12
    13 eval { my $aref = $rps->call("dump_address_book");
    14          print Dumper($aref);
    15       };
    16
    17 print "ndonen";
                                          Figure 4

All the usual Frontier::RPC suspects are here. This time, we are explicitly assigning the
call method's return value. A collection type is always returned as a reference by this
library. We can use this reference as we would an normal Perl variable, but Data::Dumper is
a simple way to verify that the call succeed. For the record, here's a pared down version of
the output.
[jjohn@marian xmlrpc]$ ./use_perl_taddrs

Calling dump_address_book()
$VAR1 = [
           {
              'email' => 'mc@nowhere.com',
              'firstname' => 'Macky',
              'phone' => '999 555 1234',
              'lastname' => 'McCormack'
           },
           {
              'email' => 'jjohn@cs.umb.edu',
              'firstname' => 'Joe',
              'phone' => 'no way, dude!',
              'lastname' => 'Johnston'
           }
        ];
done

                     Figure 5


Building a Listener
For those system administrators out there who want to build a monitoring system for the
health of each machine on their network, installing simple XML-RPC listeners on each
machine is one easy way to collect system statistics. Here is the code for a listener that
returns a structure (really a hash) that is a snapshot of the current system health.

#!/usr/bin/perl --
use strict;
use Frontier::Daemon;

Frontier::Daemon->new( methods => {
                                  status => sub {
                                                              return {
                                                               uptime =>
                                                                  (join
"<BR>",`uptime`),
                                                                df        =>
                                                                     (join "<BR>", `df`),
                                                                       };
                                                     },
                                        },
                            LocalPort => 80,
                            LocalAddr => 'edith.daisypark.net',
                         );
                                          Figure 6

The Frontier::Daemon class is a sub-class of HTTP::Daemon. The new method doesn't
return; it waits to service requests. Because HTTP::Daemon is a sub-class of
IO::Socket::INET, we can control the TCP port and address to which this server will bind
(ain't Object Orient Programming grand?). The procedures that XML-RPC clients can call are
contained in the hash pointed to by the methods parameter. The keys of this hash are the
names of the procedures that clients call. The values of this hash are references to subroutines
that implement the given procedure. Here, there is only one procedure that our service
provides, status. To reduce the display burden on the clients, I'm converting newlines into
HTML <BR> tags. Here's a screenshot of an ASP page that is making XML-RPC calls to two
machines running this monitoring service.




Documenting Your API
Like the weather, everyone talks about documentation but no one ever does anything about it.
Without documenting the API to your XML-RPC web service, no one will be able to take
advantage of it. There is no official way to "discover" the procedures that a web service
offers, so I recommend a simple web page that lists the procedure names, the XML-RPC
datatypes expected for input and the XML-RPC datatypes that are returned. Something like
Figure 1 is good a minimum. Of course, it might be nice to explain what those procedures
do. POD is very amenable to this purpose.


Links to More Information
XML-RPC is a great tool for creating platform independent, network application gateways.
Its simplicity is its strength. For more information on XML-RPC, check out the homepage at
www.xmlrpc.com or wait for the O'Reilly book Programming Web Applications with XML-
RPC, due out this summer.

Links

    1. "www.perl.com" - http://www.perl.com/
    2. "Quick Start with SOAP" - http://www.perl.com/pub/2001/01/soap.html
    3. "Network Programming with Perl" -
       http://www.awlonline.com/product/0,2627,0201615711,00.html
    4. "Jon Udell" - http://udell.roninhouse.com/
    5. "Ken MacLeod" - http://bitsko.slc.ut.us/~ken/
    6. "Frontier" - http://frontier.userland.com/
    7. "www.xmlrpc.com" - http://www.xmlrpc.com/

                             © Copyright 2009 - pudge, All Rights Reserved

printed from use Perl, Creating Web Services with XML-RPC on 2009-06-24 16:11:44
Ad

More Related Content

What's hot (20)

Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In Java
Ankur Agrawal
 
Basic socket programming
Basic socket programmingBasic socket programming
Basic socket programming
Kristian Arjianto
 
JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5
Stephan Schmidt
 
Java sockets
Java socketsJava sockets
Java sockets
Stephen Pradeep
 
解读server.xml文件
解读server.xml文件解读server.xml文件
解读server.xml文件
wensheng wei
 
Building your First gRPC Service
Building your First gRPC ServiceBuilding your First gRPC Service
Building your First gRPC Service
Jessie Barnett
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
kamal kotecha
 
Psr 7 symfony-day
Psr 7 symfony-dayPsr 7 symfony-day
Psr 7 symfony-day
Marco Perone
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
sureshkarthick37
 
7.protocols 2
7.protocols 27.protocols 2
7.protocols 2
Marian Marinov
 
Psr-7
Psr-7Psr-7
Psr-7
Marco Perone
 
1. primary dns using bind for a and cname record for ipv4 and ipv6
1. primary dns using bind for a and cname record for ipv4 and ipv61. primary dns using bind for a and cname record for ipv4 and ipv6
1. primary dns using bind for a and cname record for ipv4 and ipv6
Piyush Kumar
 
MidwestPHP Symfony2 Internals
MidwestPHP Symfony2 InternalsMidwestPHP Symfony2 Internals
MidwestPHP Symfony2 Internals
Raul Fraile
 
Udp socket programming(Florian)
Udp socket programming(Florian)Udp socket programming(Florian)
Udp socket programming(Florian)
Flor Ian
 
How to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsHow to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking Needs
DigitalOcean
 
Np unit iii
Np unit iiiNp unit iii
Np unit iii
vamsitricks
 
2. reverse primarydns using bind for ptr and cname record ipv4
2. reverse primarydns using bind for ptr and cname record ipv42. reverse primarydns using bind for ptr and cname record ipv4
2. reverse primarydns using bind for ptr and cname record ipv4
Piyush Kumar
 
Railsconf
RailsconfRailsconf
Railsconf
Ezra Zygmuntowicz
 
JSON-RPC - JSON Remote Procedure Call
JSON-RPC - JSON Remote Procedure CallJSON-RPC - JSON Remote Procedure Call
JSON-RPC - JSON Remote Procedure Call
Peter R. Egli
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
phanleson
 
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In Java
Ankur Agrawal
 
JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5JSON-RPC Proxy Generation with PHP 5
JSON-RPC Proxy Generation with PHP 5
Stephan Schmidt
 
解读server.xml文件
解读server.xml文件解读server.xml文件
解读server.xml文件
wensheng wei
 
Building your First gRPC Service
Building your First gRPC ServiceBuilding your First gRPC Service
Building your First gRPC Service
Jessie Barnett
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
kamal kotecha
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
sureshkarthick37
 
1. primary dns using bind for a and cname record for ipv4 and ipv6
1. primary dns using bind for a and cname record for ipv4 and ipv61. primary dns using bind for a and cname record for ipv4 and ipv6
1. primary dns using bind for a and cname record for ipv4 and ipv6
Piyush Kumar
 
MidwestPHP Symfony2 Internals
MidwestPHP Symfony2 InternalsMidwestPHP Symfony2 Internals
MidwestPHP Symfony2 Internals
Raul Fraile
 
Udp socket programming(Florian)
Udp socket programming(Florian)Udp socket programming(Florian)
Udp socket programming(Florian)
Flor Ian
 
How to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsHow to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking Needs
DigitalOcean
 
2. reverse primarydns using bind for ptr and cname record ipv4
2. reverse primarydns using bind for ptr and cname record ipv42. reverse primarydns using bind for ptr and cname record ipv4
2. reverse primarydns using bind for ptr and cname record ipv4
Piyush Kumar
 
JSON-RPC - JSON Remote Procedure Call
JSON-RPC - JSON Remote Procedure CallJSON-RPC - JSON Remote Procedure Call
JSON-RPC - JSON Remote Procedure Call
Peter R. Egli
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
phanleson
 

Viewers also liked (20)

Agent web site_set_up_guide v2
Agent web site_set_up_guide v2Agent web site_set_up_guide v2
Agent web site_set_up_guide v2
Falcon Homes
 
Java 8 Concurrency Updates
Java 8 Concurrency UpdatesJava 8 Concurrency Updates
Java 8 Concurrency Updates
Damian Łukasik
 
Proyecto Incredibox
Proyecto IncrediboxProyecto Incredibox
Proyecto Incredibox
Vania C. Tovilla Quesada
 
47174915 bhopal-gas-tragedy
47174915 bhopal-gas-tragedy47174915 bhopal-gas-tragedy
47174915 bhopal-gas-tragedy
Prafulla Tekriwal
 
Fazd heartwater power point module final sept 2011
Fazd heartwater power point module final sept 2011Fazd heartwater power point module final sept 2011
Fazd heartwater power point module final sept 2011
AgriLife News-Texas AgriLife Extension Service/Texas AgriLife Research
 
Fazd bovine babesia paper final (2)
Fazd bovine babesia paper final (2)Fazd bovine babesia paper final (2)
Fazd bovine babesia paper final (2)
AgriLife News-Texas AgriLife Extension Service/Texas AgriLife Research
 
CETS 2011, Jan Saillard, slides for How to Create a Course from Short Self-Di...
CETS 2011, Jan Saillard, slides for How to Create a Course from Short Self-Di...CETS 2011, Jan Saillard, slides for How to Create a Course from Short Self-Di...
CETS 2011, Jan Saillard, slides for How to Create a Course from Short Self-Di...
Chicago eLearning & Technology Showcase
 
Callture turnkey platform presentation
Callture turnkey platform presentationCallture turnkey platform presentation
Callture turnkey platform presentation
Callture Inc
 
CETS 2011, Consuela Shorter, Leveraging Learning Technologies to Meet Busines...
CETS 2011, Consuela Shorter, Leveraging Learning Technologies to Meet Busines...CETS 2011, Consuela Shorter, Leveraging Learning Technologies to Meet Busines...
CETS 2011, Consuela Shorter, Leveraging Learning Technologies to Meet Busines...
Chicago eLearning & Technology Showcase
 
Case Study - France ICT Adoption Program for Small Businesses
Case Study - France ICT Adoption Program for Small BusinessesCase Study - France ICT Adoption Program for Small Businesses
Case Study - France ICT Adoption Program for Small Businesses
Technopreneurs Association of Malaysia
 
Nzas 2014
Nzas 2014Nzas 2014
Nzas 2014
Fabiana Kubke
 
Oii 4 social Открытые конкурсы в самоуправлении
Oii 4 social Открытые конкурсы в самоуправленииOii 4 social Открытые конкурсы в самоуправлении
Oii 4 social Открытые конкурсы в самоуправлении
Open Innovation Inc.
 
3 months before and 3 months after entering Japan market, by Liew Choon Lian ...
3 months before and 3 months after entering Japan market, by Liew Choon Lian ...3 months before and 3 months after entering Japan market, by Liew Choon Lian ...
3 months before and 3 months after entering Japan market, by Liew Choon Lian ...
Technopreneurs Association of Malaysia
 
Africa and Southeast Asia Business Forum 2011
Africa and Southeast Asia Business Forum 2011Africa and Southeast Asia Business Forum 2011
Africa and Southeast Asia Business Forum 2011
Technopreneurs Association of Malaysia
 
MSC Malaysia Innovation Voucher Handbook v1.4
MSC Malaysia Innovation Voucher Handbook v1.4MSC Malaysia Innovation Voucher Handbook v1.4
MSC Malaysia Innovation Voucher Handbook v1.4
Technopreneurs Association of Malaysia
 
Molabtvx
MolabtvxMolabtvx
Molabtvx
Nat Pham
 
Resumen de señalización
Resumen de señalizaciónResumen de señalización
Resumen de señalización
Fredys Mercado
 
Respiration (with review of photosynthesis)
Respiration (with review of photosynthesis)Respiration (with review of photosynthesis)
Respiration (with review of photosynthesis)
LM9
 
Dept. of defense driving toward 0
Dept. of defense   driving toward 0Dept. of defense   driving toward 0
Dept. of defense driving toward 0
Vaibhav Patni
 
Crcsd boe presentation 080910
Crcsd boe presentation 080910Crcsd boe presentation 080910
Crcsd boe presentation 080910
Cedar Rapids Community Schools
 
Agent web site_set_up_guide v2
Agent web site_set_up_guide v2Agent web site_set_up_guide v2
Agent web site_set_up_guide v2
Falcon Homes
 
Java 8 Concurrency Updates
Java 8 Concurrency UpdatesJava 8 Concurrency Updates
Java 8 Concurrency Updates
Damian Łukasik
 
CETS 2011, Jan Saillard, slides for How to Create a Course from Short Self-Di...
CETS 2011, Jan Saillard, slides for How to Create a Course from Short Self-Di...CETS 2011, Jan Saillard, slides for How to Create a Course from Short Self-Di...
CETS 2011, Jan Saillard, slides for How to Create a Course from Short Self-Di...
Chicago eLearning & Technology Showcase
 
Callture turnkey platform presentation
Callture turnkey platform presentationCallture turnkey platform presentation
Callture turnkey platform presentation
Callture Inc
 
CETS 2011, Consuela Shorter, Leveraging Learning Technologies to Meet Busines...
CETS 2011, Consuela Shorter, Leveraging Learning Technologies to Meet Busines...CETS 2011, Consuela Shorter, Leveraging Learning Technologies to Meet Busines...
CETS 2011, Consuela Shorter, Leveraging Learning Technologies to Meet Busines...
Chicago eLearning & Technology Showcase
 
Oii 4 social Открытые конкурсы в самоуправлении
Oii 4 social Открытые конкурсы в самоуправленииOii 4 social Открытые конкурсы в самоуправлении
Oii 4 social Открытые конкурсы в самоуправлении
Open Innovation Inc.
 
3 months before and 3 months after entering Japan market, by Liew Choon Lian ...
3 months before and 3 months after entering Japan market, by Liew Choon Lian ...3 months before and 3 months after entering Japan market, by Liew Choon Lian ...
3 months before and 3 months after entering Japan market, by Liew Choon Lian ...
Technopreneurs Association of Malaysia
 
Resumen de señalización
Resumen de señalizaciónResumen de señalización
Resumen de señalización
Fredys Mercado
 
Respiration (with review of photosynthesis)
Respiration (with review of photosynthesis)Respiration (with review of photosynthesis)
Respiration (with review of photosynthesis)
LM9
 
Dept. of defense driving toward 0
Dept. of defense   driving toward 0Dept. of defense   driving toward 0
Dept. of defense driving toward 0
Vaibhav Patni
 
Ad

Similar to Use perl creating web services with xml rpc (20)

XML-RPC and SOAP (April 2003)
XML-RPC and SOAP (April 2003)XML-RPC and SOAP (April 2003)
XML-RPC and SOAP (April 2003)
Kiran Jonnalagadda
 
Training Slides: 153 - Working with the CLI
Training Slides: 153 - Working with the CLITraining Slides: 153 - Working with the CLI
Training Slides: 153 - Working with the CLI
Continuent
 
Rpc (Distributed computing)
Rpc (Distributed computing)Rpc (Distributed computing)
Rpc (Distributed computing)
Sri Prasanna
 
How CPAN Testers helped me improve my module
How CPAN Testers helped me improve my moduleHow CPAN Testers helped me improve my module
How CPAN Testers helped me improve my module
acme
 
Remote Procedure Call
Remote Procedure CallRemote Procedure Call
Remote Procedure Call
Nadia Nahar
 
Troubleshooting common oslo.messaging and RabbitMQ issues
Troubleshooting common oslo.messaging and RabbitMQ issuesTroubleshooting common oslo.messaging and RabbitMQ issues
Troubleshooting common oslo.messaging and RabbitMQ issues
Michael Klishin
 
project_docs
project_docsproject_docs
project_docs
Andrey Lavrinovic
 
Hunting for APT in network logs workshop presentation
Hunting for APT in network logs workshop presentationHunting for APT in network logs workshop presentation
Hunting for APT in network logs workshop presentation
OlehLevytskyi1
 
Command.pptx presentation
Command.pptx presentationCommand.pptx presentation
Command.pptx presentation
Akshay193557
 
Red5 - PHUG Workshops
Red5 - PHUG WorkshopsRed5 - PHUG Workshops
Red5 - PHUG Workshops
Brendan Sera-Shriar
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
Zoran Jeremic
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHP
Zoran Jeremic
 
Code Red Security
Code Red SecurityCode Red Security
Code Red Security
Amr Ali
 
What I learned about APIs in my first year at Google
What I learned about APIs in my first year at GoogleWhat I learned about APIs in my first year at Google
What I learned about APIs in my first year at Google
Tim Burks
 
[Webinar Slides] Programming the Network Dataplane in P4
[Webinar Slides] Programming the Network Dataplane in P4[Webinar Slides] Programming the Network Dataplane in P4
[Webinar Slides] Programming the Network Dataplane in P4
Open Networking Summits
 
Case study ap log collector
Case study ap log collectorCase study ap log collector
Case study ap log collector
Jyun-Yao Huang
 
Tips
TipsTips
Tips
mclee
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streaming
phanleson
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packages
Ajay Ohri
 
Intro to web services
Intro to web servicesIntro to web services
Intro to web services
Neil Ghosh
 
Training Slides: 153 - Working with the CLI
Training Slides: 153 - Working with the CLITraining Slides: 153 - Working with the CLI
Training Slides: 153 - Working with the CLI
Continuent
 
Rpc (Distributed computing)
Rpc (Distributed computing)Rpc (Distributed computing)
Rpc (Distributed computing)
Sri Prasanna
 
How CPAN Testers helped me improve my module
How CPAN Testers helped me improve my moduleHow CPAN Testers helped me improve my module
How CPAN Testers helped me improve my module
acme
 
Remote Procedure Call
Remote Procedure CallRemote Procedure Call
Remote Procedure Call
Nadia Nahar
 
Troubleshooting common oslo.messaging and RabbitMQ issues
Troubleshooting common oslo.messaging and RabbitMQ issuesTroubleshooting common oslo.messaging and RabbitMQ issues
Troubleshooting common oslo.messaging and RabbitMQ issues
Michael Klishin
 
Hunting for APT in network logs workshop presentation
Hunting for APT in network logs workshop presentationHunting for APT in network logs workshop presentation
Hunting for APT in network logs workshop presentation
OlehLevytskyi1
 
Command.pptx presentation
Command.pptx presentationCommand.pptx presentation
Command.pptx presentation
Akshay193557
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
Zoran Jeremic
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHP
Zoran Jeremic
 
Code Red Security
Code Red SecurityCode Red Security
Code Red Security
Amr Ali
 
What I learned about APIs in my first year at Google
What I learned about APIs in my first year at GoogleWhat I learned about APIs in my first year at Google
What I learned about APIs in my first year at Google
Tim Burks
 
[Webinar Slides] Programming the Network Dataplane in P4
[Webinar Slides] Programming the Network Dataplane in P4[Webinar Slides] Programming the Network Dataplane in P4
[Webinar Slides] Programming the Network Dataplane in P4
Open Networking Summits
 
Case study ap log collector
Case study ap log collectorCase study ap log collector
Case study ap log collector
Jyun-Yao Huang
 
Tips
TipsTips
Tips
mclee
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streaming
phanleson
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packages
Ajay Ohri
 
Intro to web services
Intro to web servicesIntro to web services
Intro to web services
Neil Ghosh
 
Ad

Recently uploaded (20)

apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 

Use perl creating web services with xml rpc

  • 1. use Perl All the Perl that's Practical to Extract and Report http://use.perl.org/ Title Creating Web Services with XML-RPC Date 2001.02.05 10:29 Author jjohn Topic http://use.perl.org/article.pl?sid=01/02/05/1438258 XML-RPC. SOAP. CORBA. Buzzwords galore, but possibly useful ones: this is, essentially, technology that allows you to use web sites as a big API. Below we have an article about XML-RPC; you might also want to check out an article by Paul Kulchenko on www.perl.com, "Quick Start with SOAP". Web Services Are More Than HTTP One of Perl's enduring strengths is in allowing the programmer to easily manipulate UNIX system resources, like /etc/passwd files, syslog and the filesystem. Perl is also a great tool for building network applications (for more on this, see Lincoln Stein's excellent Network Programming with Perl). As Nathan Torkington pointed out at YAPC 19100, the Perl community hasn't yet fully embraced a component model of programming. Components are libraries that can be used by programs written in any language. If you've dealt with Windows programming particularly ASP coding, you are probably familiar with COM objects already. But COM is just one vendor's implementation of components. Jon Udell argues that web applications can be used in a component fashion. How many of you have stolen the HTML from your favorite search engine's FORM and pasted it into your homepage? (I hope I'm not the only one raising my hand!) Although LWP is a powerful tool for "page scraping", you probably don't want to be parsing HTML every time you make an object call. Fortunately, others have been working on this problem. XML-RPC is a protocol for Remote Procedure Calls whose conversation over TCP port 80 is encoded into XML. There are XML-RPC implementations written in many languages for many platforms, including Perl. Every XML-RPC application must have two parts, but there's a third that ought to be required. If your script is making an XML-RPC request to some web service, you are making client calls. If your script is answering XML-RPC requests, it is a listener. This seems to describe a typical client-server system; what could be the third piece? Because XML-RPC is language and platform neutral, it is essential that the listener's API be adequately documented. Listing what procedures are expecting for input and the datatypes of the return values is a necessity when dealing with sub-Perl languages, like Microsoft's VBScript. The XML-RPC protocol is a call and response system, very much akin to HTTP. One consequence of this is that XML-RPC doesn't support transactions or maintaining state. Another problem is the conversation between listener and client is in clear-text. Despite these limitations, there are still a number of applications for which XML-RPC is well suited.
  • 2. Building a Client The first quandary the novice XML-RPC Perl programmer will encounter is the name of the module. Ken MacLeod's implementation is called Frontier::RPC, because XML-RPC was the brain child of UserLand's Dave Winer, also of Frontier Naming issues aside, you can find this module on your local CPAN. Installation follows the normal "perl Makefile.PL && make test && make install" cycle. Let's assume there's an existing XML-RPC service you want to talk to. It defines the following API: Procedure Name | Input | Output ------------------------------------- hello_world | <STRING> | <STRING> ------------------------------------- sum | <INT>, | | <INT> | <INT> -------------------------------------- Figure 1 Remember, XML-RPC is designed to be language neutral. Every language's implementation of XML-RPC translates the RPC into an XML description that tags each argument with a specific XML-RPC datatype. Although Perl's DWIM-FU is strong, other languages are strongly typed and need this additional information. When the listener responds, Frontier::RPC translates the XML back into Perl datatypes. Besides the API, we need to know the URL of the listener. For this example, we will use an NT machine on my private network. Enough yakkin'. Here's a simple test of this web service. 1 #!/usr/bin/perl -- 2 3 use strict; 4 use Frontier::Client; 5 6 my $rps = Frontier::Client->new( 7 url => "http://durgan.daisypark.net/jjohn/rpc_simple.asp", 8 ); 9 10 print "Calling hello_world()n"; 11 eval { print $rps->call("hello_world", "jjohn"), "n" }; 12 13 print "n=-----------------=n"; 14 print "Calling sum()n"; 15 eval { print $rps->call("sum", "1024", "128"), "n" }; 16 17 print "ndonen"; Figure 2
  • 3. After including the library, we instantiate a new Frontier::Client object by passing the URL of the web service. We can now make our RPC by using the call() method, which expects the name of the remote procedure followed by a list of its arguments. If all goes well, call() converts the return value of the procedure into a normal Perl datatype. Why am I wrapping the method calls in evals? According to the XML spec, an XML parser is supposed to halt as soon as it finds a parsing error. Since Frontier::RPC is encoding and decoding XML, this is a precaution. Sometimes, bad things happen to good network packets. The output looks like this: [jjohn@marian xmlrpc]$ ./test_simple Calling hello_world() Hello, jjohn =-----------------= Calling sum() 1152 done Figure 3 Sure, strings and numbers are useful but Real Functions ™ use collection types like arrays and dictionaries. XML-RPC can handle those datatypes as well. Here's an example of a procedure that returns an array of hashes. It is getting all the records from an Access database stored on the aforementioend NT system. Notice that we are talking to a different XML-RPC listener now. 1 #!/usr/bin/perl -- 2 3 use strict; 4 use Frontier::Client; 5 use Data::Dumper; 6 7 my $rps = Frontier::Client->new( 8 url => "http://durgan.daisypark.net/jjohn/rpc_addresses.asp", 9 ); 10 11 print "nCalling dump_address_book()n"; 12 13 eval { my $aref = $rps->call("dump_address_book"); 14 print Dumper($aref); 15 }; 16 17 print "ndonen"; Figure 4 All the usual Frontier::RPC suspects are here. This time, we are explicitly assigning the call method's return value. A collection type is always returned as a reference by this library. We can use this reference as we would an normal Perl variable, but Data::Dumper is a simple way to verify that the call succeed. For the record, here's a pared down version of the output.
  • 4. [jjohn@marian xmlrpc]$ ./use_perl_taddrs Calling dump_address_book() $VAR1 = [ { 'email' => '[email protected]', 'firstname' => 'Macky', 'phone' => '999 555 1234', 'lastname' => 'McCormack' }, { 'email' => '[email protected]', 'firstname' => 'Joe', 'phone' => 'no way, dude!', 'lastname' => 'Johnston' } ]; done Figure 5 Building a Listener For those system administrators out there who want to build a monitoring system for the health of each machine on their network, installing simple XML-RPC listeners on each machine is one easy way to collect system statistics. Here is the code for a listener that returns a structure (really a hash) that is a snapshot of the current system health. #!/usr/bin/perl -- use strict; use Frontier::Daemon; Frontier::Daemon->new( methods => { status => sub { return { uptime => (join "<BR>",`uptime`), df => (join "<BR>", `df`), }; }, }, LocalPort => 80, LocalAddr => 'edith.daisypark.net', ); Figure 6 The Frontier::Daemon class is a sub-class of HTTP::Daemon. The new method doesn't return; it waits to service requests. Because HTTP::Daemon is a sub-class of IO::Socket::INET, we can control the TCP port and address to which this server will bind (ain't Object Orient Programming grand?). The procedures that XML-RPC clients can call are contained in the hash pointed to by the methods parameter. The keys of this hash are the names of the procedures that clients call. The values of this hash are references to subroutines that implement the given procedure. Here, there is only one procedure that our service
  • 5. provides, status. To reduce the display burden on the clients, I'm converting newlines into HTML <BR> tags. Here's a screenshot of an ASP page that is making XML-RPC calls to two machines running this monitoring service. Documenting Your API Like the weather, everyone talks about documentation but no one ever does anything about it. Without documenting the API to your XML-RPC web service, no one will be able to take advantage of it. There is no official way to "discover" the procedures that a web service offers, so I recommend a simple web page that lists the procedure names, the XML-RPC datatypes expected for input and the XML-RPC datatypes that are returned. Something like Figure 1 is good a minimum. Of course, it might be nice to explain what those procedures do. POD is very amenable to this purpose. Links to More Information XML-RPC is a great tool for creating platform independent, network application gateways. Its simplicity is its strength. For more information on XML-RPC, check out the homepage at
  • 6. www.xmlrpc.com or wait for the O'Reilly book Programming Web Applications with XML- RPC, due out this summer. Links 1. "www.perl.com" - http://www.perl.com/ 2. "Quick Start with SOAP" - http://www.perl.com/pub/2001/01/soap.html 3. "Network Programming with Perl" - http://www.awlonline.com/product/0,2627,0201615711,00.html 4. "Jon Udell" - http://udell.roninhouse.com/ 5. "Ken MacLeod" - http://bitsko.slc.ut.us/~ken/ 6. "Frontier" - http://frontier.userland.com/ 7. "www.xmlrpc.com" - http://www.xmlrpc.com/ © Copyright 2009 - pudge, All Rights Reserved printed from use Perl, Creating Web Services with XML-RPC on 2009-06-24 16:11:44