Search

Dark theme | Light theme

February 19, 2015

Groovy Goodness: Access XML-RPC API

Recently I had to access the XML-RPC WordPress API for a small project. Luckily with Groovy we can access a XML-RPC server in a Groovy way. We need to use the Groovy XML-RPC module, which is a separate dependency. The module provides code to write a XML-RPC server, but also code to access a XML-RPC server as client. We use the class XMLRPCServerProxy in the package groovy.net.xmlrpc to act as a client to a XML-RPC API. The XMLRPCServerProxy class only needs to know the URL to access the API. All API methods are dynamically dispatched to the server, so it is very flexible.

In the following Groovy script we use the WordPress XML-RPC API to access posts:

@Grab('org.codehaus.groovy:groovy-xmlrpc:0.8')
import groovy.net.xmlrpc.*

// Use correct blog identifier.
def blogId = 0 

// Use correct URL for XML-RPC API.
def blogUrl = 'http://blog/xmlrpc' 

def blogUsername = 'mrhaki'
def blogPassword = 'secret'

// Create client access for XML-RPC API.
// The second parameter is set to true
// to autodetect encoding. Default encoding
// is ISO-8859-1.
def wordPress = new XMLRPCServerProxy(blogUrl, true)

// Now we can access the API methods from WordPress.
// Notice the API method wp.getPosts is dynamically
// available from the XMLRPCServerProxy instance.
def latestFivePost = 
    wordPress
        ."wp.getPosts"(
             blogId,
             blogUsername,
             blogPassword,       
             [number: 5, post_type: 'post'],
             ['post_id', 'post_title'])

latestFivePosts.each { post ->
    println "Blog post (#${post.post_id}): ${post.post_title}"
}

Written with Groovy 2.4.