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

More Related Content

What's hot

Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In JavaAnkur 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 5Stephan 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 ServiceJessie Barnett
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sksureshkarthick37
 
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 ipv6Piyush Kumar
 
MidwestPHP Symfony2 Internals
MidwestPHP Symfony2 InternalsMidwestPHP Symfony2 Internals
MidwestPHP Symfony2 InternalsRaul 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 NeedsDigitalOcean
 
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 ipv4Piyush Kumar
 
JSON-RPC - JSON Remote Procedure Call
JSON-RPC - JSON Remote Procedure CallJSON-RPC - JSON Remote Procedure Call
JSON-RPC - JSON Remote Procedure CallPeter R. Egli
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.comphanleson
 

What's hot (20)

Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In Java
 
Basic socket programming
Basic socket programmingBasic socket programming
Basic socket programming
 
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
 
Java sockets
Java socketsJava sockets
Java sockets
 
解读server.xml文件
解读server.xml文件解读server.xml文件
解读server.xml文件
 
Building your First gRPC Service
Building your First gRPC ServiceBuilding your First gRPC Service
Building your First gRPC Service
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Psr 7 symfony-day
Psr 7 symfony-dayPsr 7 symfony-day
Psr 7 symfony-day
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 
7.protocols 2
7.protocols 27.protocols 2
7.protocols 2
 
Psr-7
Psr-7Psr-7
Psr-7
 
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
 
MidwestPHP Symfony2 Internals
MidwestPHP Symfony2 InternalsMidwestPHP Symfony2 Internals
MidwestPHP Symfony2 Internals
 
Udp socket programming(Florian)
Udp socket programming(Florian)Udp socket programming(Florian)
Udp socket programming(Florian)
 
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
 
Np unit iii
Np unit iiiNp unit iii
Np unit iii
 
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
 
Railsconf
RailsconfRailsconf
Railsconf
 
JSON-RPC - JSON Remote Procedure Call
JSON-RPC - JSON Remote Procedure CallJSON-RPC - JSON Remote Procedure Call
JSON-RPC - JSON Remote Procedure Call
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
 

Viewers also liked

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 v2Falcon Homes
 
Java 8 Concurrency Updates
Java 8 Concurrency UpdatesJava 8 Concurrency Updates
Java 8 Concurrency UpdatesDamian Ł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 presentationCallture 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ónFredys 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 0Vaibhav Patni
 

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
 
Java 8 Concurrency Updates
Java 8 Concurrency UpdatesJava 8 Concurrency Updates
Java 8 Concurrency Updates
 
Proyecto Incredibox
Proyecto IncrediboxProyecto Incredibox
Proyecto Incredibox
 
47174915 bhopal-gas-tragedy
47174915 bhopal-gas-tragedy47174915 bhopal-gas-tragedy
47174915 bhopal-gas-tragedy
 
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
 
Fazd bovine babesia paper final (2)
Fazd bovine babesia paper final (2)Fazd bovine babesia paper final (2)
Fazd bovine babesia paper final (2)
 
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...
 
Callture turnkey platform presentation
Callture turnkey platform presentationCallture turnkey platform presentation
Callture turnkey platform presentation
 
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...
 
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
 
Nzas 2014
Nzas 2014Nzas 2014
Nzas 2014
 
Oii 4 social Открытые конкурсы в самоуправлении
Oii 4 social Открытые конкурсы в самоуправленииOii 4 social Открытые конкурсы в самоуправлении
Oii 4 social Открытые конкурсы в самоуправлении
 
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 ...
 
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
 
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
 
Molabtvx
MolabtvxMolabtvx
Molabtvx
 
Resumen de señalización
Resumen de señalizaciónResumen de señalización
Resumen de señalización
 
Respiration (with review of photosynthesis)
Respiration (with review of photosynthesis)Respiration (with review of photosynthesis)
Respiration (with review of photosynthesis)
 
Dept. of defense driving toward 0
Dept. of defense   driving toward 0Dept. of defense   driving toward 0
Dept. of defense driving toward 0
 
Crcsd boe presentation 080910
Crcsd boe presentation 080910Crcsd boe presentation 080910
Crcsd boe presentation 080910
 

Similar to Use perl creating web services with xml rpc

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 CLIContinuent
 
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 moduleacme
 
Remote Procedure Call
Remote Procedure CallRemote Procedure Call
Remote Procedure CallNadia 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 issuesMichael 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 presentationOlehLevytskyi1
 
Command.pptx presentation
Command.pptx presentationCommand.pptx presentation
Command.pptx presentationAkshay193557
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHPZoran Jeremic
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHPZoran Jeremic
 
Code Red Security
Code Red SecurityCode Red Security
Code Red SecurityAmr 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 GoogleTim 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 P4Open Networking Summits
 
Case study ap log collector
Case study ap log collectorCase study ap log collector
Case study ap log collectorJyun-Yao Huang
 
Tips
TipsTips
Tipsmclee
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streamingphanleson
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packagesAjay Ohri
 
Intro to web services
Intro to web servicesIntro to web services
Intro to web servicesNeil Ghosh
 

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)
 
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
 
Rpc (Distributed computing)
Rpc (Distributed computing)Rpc (Distributed computing)
Rpc (Distributed computing)
 
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
 
Remote Procedure Call
Remote Procedure CallRemote Procedure Call
Remote Procedure Call
 
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
 
project_docs
project_docsproject_docs
project_docs
 
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
 
Command.pptx presentation
Command.pptx presentationCommand.pptx presentation
Command.pptx presentation
 
Red5 - PHUG Workshops
Red5 - PHUG WorkshopsRed5 - PHUG Workshops
Red5 - PHUG Workshops
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHP
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
 
Code Red Security
Code Red SecurityCode Red Security
Code Red Security
 
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
 
[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
 
Case study ap log collector
Case study ap log collectorCase study ap log collector
Case study ap log collector
 
Tips
TipsTips
Tips
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streaming
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packages
 
Intro to web services
Intro to web servicesIntro to web services
Intro to web services
 

Recently uploaded

Matatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxMatatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxJenilouCasareno
 
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfINU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfbu07226
 
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptxSolid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptxDenish Jangid
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsCol Mukteshwar Prasad
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationDelapenabediema
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxricssacare
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdfCarlosHernanMontoyab2
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPCeline George
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...Nguyen Thanh Tu Collection
 
plant breeding methods in asexually or clonally propagated crops
plant breeding methods in asexually or clonally propagated cropsplant breeding methods in asexually or clonally propagated crops
plant breeding methods in asexually or clonally propagated cropsparmarsneha2
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasiemaillard
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345beazzy04
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePedroFerreira53928
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasGeoBlogs
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismDeeptiGupta154
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxJisc
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfjoachimlavalley1
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonSteve Thomason
 
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfDanh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfQucHHunhnh
 

Recently uploaded (20)

Matatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxMatatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
 
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfINU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
 
B.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdfB.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdf
 
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptxSolid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
Solid waste management & Types of Basic civil Engineering notes by DJ Sir.pptx
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
plant breeding methods in asexually or clonally propagated crops
plant breeding methods in asexually or clonally propagated cropsplant breeding methods in asexually or clonally propagated crops
plant breeding methods in asexually or clonally propagated crops
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfDanh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
 

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' => '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
  • 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