SlideShare une entreprise Scribd logo
1  sur  6
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

Contenu connexe

Tendances

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
 

Tendances (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
 

En vedette

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
 

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Dernier

Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 

Dernier (20)

Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 

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