SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

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
 
MidwestPHP Symfony2 Internals
MidwestPHP Symfony2 InternalsMidwestPHP Symfony2 Internals
MidwestPHP Symfony2 Internals
Raul Fraile
 

Mais procurados (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
 

Destaque

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

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

Semelhante a Use perl creating web services with xml rpc

Rpc (Distributed computing)
Rpc (Distributed computing)Rpc (Distributed computing)
Rpc (Distributed computing)
Sri Prasanna
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
Zoran Jeremic
 
[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
 
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
 

Semelhante a 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
 

Último

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
heathfieldcps1
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Último (20)

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
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
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Ữ Â...
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
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
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 

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