WordCamp OC: REST/JSON API Talk

XML-RPC

Specification: http://xmlrpc.scripting.com/spec.html
PHP Documentation: http://php.net/manual/en/book.xmlrpc.php
WordPress Documentation: http://codex.wordpress.org/XML-RPC_Support
Mimic (JS Library): http://mimic-xmlrpc.sourceforge.net/

Example Extension


<?php
/*
 * Plugin Name: XML-RPC Extensibility Demo for WordCamp OC
 * Description: Demonstrates how to add an XML-RPC endpoint
 * Author: Mike Adams, Automattic
 * License: GPL2+
 */

/**
 * XML-RPC Method: Get the email address for the given user
 *
 * Requires Authentication, but demo only.  Does not do the correct
 * things with permissions, etc.
 *
 * @param (array) $args XML-RPC Request args:
 *                0 => username
 *                1 => password
 *                2 => user_id for the user whose email address we want
 * @return (string|IXR_Error) Email address or IXR_Error on failure
 */
function user_email_rpc( $args ) {
	global $wp_xmlrpc_server;

	if ( !is_array( $args ) || 3 != count( $args ) ) {
		return new IXR_Error( 400, 'Bad input' );
	}

	// Best practice: Explicitly cast all inputs
	$username = (string) $args[0];
	$password = (string) $args[1];
	$user_id  = (int)    $args[2];

	if ( !$wp_xmlrpc_server->login( $username, $password ) ) {
		return $wp_xmlrpc_server->error;
	}

	$user = get_user_by( 'id', $user_id );

	if ( !$user || is_wp_error( $user ) ) {
		return new IXR_Error( 404, 'Unknown user_id' );
	}

	// Best practice: Explicitly cast all output
	return (string) $user->user_email;
}

function user_email_rpc_add_xmlrpc_method( $methods ) {
	$methods['napa.getUserEmail'] = 'user_email_rpc';
	return $methods;
}

add_filter( 'xmlrpc_methods', 'user_email_rpc_add_xmlrpc_method' );

XML-RPC via CLI “Example”

Generating and reading XML from the command line is annoying. It’s not really worth it.

#!/bin/bash

URL=${1-http://mdawaffe.wordpress.com/xmlrpc.php}

echo "COMMAND:"
echo "curl -i -H 'Content-Type: text/xml' --data '<?xml version="'"1.0"'"?><methodCall><methodName>demo.sayHello</methodName><params></params></methodCall>' '$URL'"
echo

echo "RESPONSE:"
curl -i -H 'Content-Type: text/xml' --data '<?xml version="1.0&"?><methodCall><methodName>demo.sayHello</methodName><params></params></methodCall>' "$URL"
echo

XML-RPC via PHP Example: xmlrpc_encode_request()

PHP’s xmlrpc_encode_request() and xmlrpc_decode() make it easy.

<?php

// Default XML-RPC endpoint
$xmlrpc_endpoint = isset( $argv[1] )
	? $argv[1]
	: 'http://mdawaffe.wordpress.com/xmlrpc.php';

// What method to call?
$method_name = 'demo.sayHello';

// What arguments to pass?
$method_arguments = null;

// Generate Request XML
$request = xmlrpc_encode_request(
	$method_name,
	$method_arguments,
	array( 'encoding' => 'UTF-8' )
);

echo "METHOD NAME:\n";
echo "$method_name\n\n";

echo "METHOD ARGUMENTS:\n";
var_dump( $method_arguments );
echo "\n";

echo "REQUEST:\n";
echo "$request\n";

// Do HTTP POST
$context = stream_context_create( array( 'http' => array(
	'method'  => 'POST',
	'header'  => 'Content-Type: text/xml',
	'content' => $request,
	'ignore_errors' => true,
) ) );
$response = file_get_contents( $xmlrpc_endpoint, false, $context );

echo "RESPONSE:\n";
echo "$response\n";

// Decode Response XML
$decoded = xmlrpc_decode( $response, 'UTF-8' );

if ( is_array( $decoded ) && xmlrpc_is_fault( $decoded ) ) {
        echo "RESPONSE ERROR CODE:\n";
        echo $decoded['faultCode'];
        echo "\n\n";

        echo "RESPONSE ERROR MESSAGE:\n";
        echo $decoded['faultString'];
        echo "\n\n";
	
} else {
	echo "DECODED RESPONSE:\n";
	var_dump( $decoded );
	echo "\n";
}

XML-RPC via WordPress Example: WP_HTTP_IXR_Client

WordPress’ WP_HTTP_IXR_Client makes it even easier.

<?php

// Load WordPress
require 'path/to/wordpress/wp-load.php';

// Load base IXR classes
require ABSPATH . WPINC . '/class-IXR.php';

// Load WP_HTTP_IXR_Client class
require ABSPATH . WPINC . '/class-wp-http-ixr-client.php';

$xmlrpc_endpoint = isset( $argv[1] )
	? $argv[1]
	: 'http://mdawaffe.wordpress.com/xmlrpc.php';

// What method to call?
$method_name = 'demo.addTwoNumbers';

// What arguments to pass?
$method_arguments = array( 1, 3 );

echo "METHOD NAME:\n";
echo "$method_name\n\n";

echo "METHOD ARGUMENTS:\n";
var_dump( $method_arguments );
echo "\n";

$xml_rpc_client = new WP_HTTP_IXR_Client( $xmlrpc_endpoint );

$xml_rpc_client->query( $method_name, $method_arguments );

if ( $xml_rpc_client->isError() ) {
	echo "RESPONSE ERROR CODE:\n";
	echo $xml_rpc_client->getErrorCode();
	echo "\n\n";

	echo "RESPONSE ERROR MESSAGE:\n";
	echo $xml_rpc_client->getErrorMessage();
	echo "\n\n";
} else {
	echo "DECODED RESPONSE:\n";
	var_dump( $xml_rpc_client->getResponse() );
	echo "\n";
}
About these ads

About Mike Adams (mdawaffe)

I work at Automattic...
This entry was posted in Automattic, WordPress. Bookmark the permalink.

2 Responses to WordCamp OC: REST/JSON API Talk

  1. Pingback: WordCamp OC: REST/JSON API Slides | real ultimate waffe (.net)

  2. Pingback: mdawaffe: WordCamp OC: REST/JSON API Slides | WordPress Planet

Comments are closed.