Strict Typing And XML-RPC

You may or may not be aware web services are very strictly typed (well, XML is, period). That means if you send a web service a string, e.g. '233', when it wants an integer, e.g. 233 (note the very subtle difference) it will break!

Consider this XML-RPC call to the Services module in Drupal:

<?php
$nid
= 144;
$result = xmlrpc('http://www.mydomain.com/services/xmlrpc', 'file.getNodeFiles', $nid);
?>

This will make Drupal's XML-RPC handling functions build the following XML envelope to send to the web service at http://www.mydomain.com/services/xmlrpc:

<?xml version="1.0" encoding="iso-8859-1"?>
<methodCall>
<methodName>file.getNodeFiles</methodName>
<params>
<param>
  <value>
   <int>144</int>
  </value>
</param>
</params>
</methodCall>

This is great, and exactly what we want. The method we're calling expects a Drupal node ID, as an integer, and that's what it gets.

But consider this:

<?php
$nid
= '144';
$result = xmlrpc('http://www.mydomain.com/services/xmlrpc', 'file.getNodeFiles', $nid);
?>

It will build this envelope:

<?xml version="1.0" encoding="iso-8859-1"?>
<methodCall>
<methodName>file.getNodeFiles</methodName>
<params>
<param>
  <value>
   <string>144</string>
  </value>
</param>
</params>
</methodCall>

Which is WRONG! Note it is now sending our node ID explicitly typed as a string. We will only get an error from this. =(

"Oh, that's ok" you say, "I won't be that dumb!" ... but what if that XML-RPC call is in a function? What if you're not the only one calling it? What if someone else *is* that dumb?

Their problem? Possibly. But yours when they tell you your function is broken and you spend three hours working out it isn't. Easy fix is to get in to the habit of explicitly typing any variables destined for a web service in PHP, something like this:

<?php
$nid
= '144';
$result = xmlrpc('http://www.mydomain.com/services/xmlrpc', 'file.getNodeFiles', (int) $nid);
?>

With the above code, even though some dufus has sent the node ID over as a string it doesn't matter. Because right when I send it off to Drupal's core XML-RPC functions I explicitly say "this is an integer, mmmkaay?"

Cool! No more phantom XML-RPC failures caused by variable type! =)

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.