Strict Typing And XML-RPC

Strict Typing And XML-RPC

Photo of Greg Harvey
Wed, 2008-12-17 19:06By greg

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:

$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:' 

file.getNodeFiles

144

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:

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

It will build this envelope:

file.getNodeFiles

144

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:

$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! =)