Creating a JSON-RPC service using Zend Json Server
In this post I am going to show how easy it is to create a JSON-RPC web service using the built in support in Zend Framework.
First we need to create the php-file that will handle the incoming RPC calls. It is not advised to put this inside the MVC structure of a Zend web application, since that will lead to unessesary complexity and overhead. The Zend people recommend that we create the JSON-RPC under /public/api/vX/
, so lets create the file /public/api/v1/jsonrpc.php
(if you haven’t setup your Zend MVC structure, read my blog post Getting started with the zend framework to get started).
We will have to do the regular bootstrapping to get our application up and running:
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../../application'));
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath('../../../library'),
get_include_path(),
)));
/** Zend_Application */
require_once 'Zend/Application.php';
// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap();
The next step is to create the class that will be exposed through the service. I will create a very simple class that will simply perform an addition of two ints. It is very important to describe the input parameters using the @param directive in the comment. This information is used by the Json Server when creating the SMD (Service Mapping Description).
/**
* Simple - sample class to expose via JSON-RPC
*/
class Simple
{
/**
* Return sum of two variables
*
* @param int $x
* @param int $y
* @return array
*/
public function add($x, $y)
{
return array('result' => $x + $y);
}
}
The last step to get the JSON-RPC server running:
// Instantiate server, etc.
$server = new Zend_Json_Server();
$server->setClass('Simple');
if ('GET' == $_SERVER['REQUEST_METHOD']) {
// Indicate the URL endpoint, and the JSON-RPC version used:
$server->setTarget('/api/v1/jsonrpc.php')
->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_2);
// Grab the SMD
$smd = $server->getServiceMap();
// Return the SMD to the client
header('Content-Type: application/json');
echo $smd;
return;
}
$server->handle();
Now your JSON-RPC Server should be up running. Browsing http://{your web server}/api/v1/jsonrpc.php
should result in the following SMD:
{
"transport":"POST",
"envelope":"JSON-RPC-2.0",
"contentType":"application\/json",
"SMDVersion":"2.0",
"target":"\/api\/v1\/jsonrpc.php",
"services": {
"add":{
"envelope":"JSON-RPC-2.0",
"transport":"POST",
"parameters":[
{"type":"integer","name":"x","optional":false},
{"type":"integer","name":"y","optional":false}],
"returns":"array"
}
},
"methods":{
"add":{
"envelope":"JSON-RPC-2.0",
"transport":"POST",
"parameters":[
{"type":"integer","name":"x","optional":false},
{"type":"integer","name":"y","optional":false}],
"returns":"array"}
}
}
jQuery does not support calling JSON-RPC services out of the box, but fourtenly there is plenty of plugins for jquery that fixes this. One is the JSON-RPC client found here. Download the client and put the javascript files into your /js
folder. Then create a new file test.html
and add the following html:
We are all done! Browsing test.html should result in an alert box containg the result.

Congratulations! You have created a JSON-RPC service!
Read more about the Zend Framework:
test.add(1,1)[‘result’],in this code u send two integer arguments to add() method.How to send a complicated object as a argument.
i mean
var ob=new Object();
ob.name=”udara”;
how can i send ob as a argument.
for the momnet im doing JSON.stringify(ob) andsent json string as a argument.
What about authentication for webservice? How would you implement it?
I’m also curious about how you would implement authentication via API keys. Thoughts?
Hi,
Where does the simple.php class reside in the application structure?
I’ve tried putting it in the library folder but I get this error:
( ! ) Fatal error: Uncaught exception ‘Zend_Server_Reflection_Exception’ with message ‘Invalid class or object passed to attachClass()’ in C:\Zend_Framework\library\Zend\Server\Reflection.php on line 68
( ! ) Zend_Server_Reflection_Exception: Invalid class or object passed to attachClass() in C:\Zend_Framework\library\Zend\Server\Reflection.php on line 68
Thanks,
Steve