GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||
GeezerVison is showing docs.voltdb.com — 8.2. JSON HTTP Interface Using VoltDB8.2. JSON HTTP InterfaceJSON (JavaScript Object Notation) is not a programming language; it is a data format. The JSON "interface" to VoltDB is actually a web interface that the Volt Management Center service makes available for processing requests and returning data in JSON format. The JSON interface lets you invoke VoltDB stored procedures and receive their results through HTTP requests. To invoke a stored procedure, you pass VoltDB the procedure name and parameters as a querystring to the HTTP request, using either the GET or POST method. Although many programming languages provide methods to simplify the encoding and decoding of JSON strings, you still
need to understand the data structures that are created. So if you are not familiar with JSON encoding, you may want to read
more about it at 8.2.1. How the JSON Interface WorksWhen you start the Volt Management Center (VMC) service and point it at a VoltDB cluster, it opens port 8080 as a simple web server. You can customize this service through the VMC configuration options, including:
See the section on the "Web Interface Port" in the VoltDB Administrator's Guide for more information on configuring the HTTP port. This section assumes the VMC service is using the default httpd configuration. In which case, any HTTP requests sent to the location /api/2.0/ on that port are interpreted as JSON requests to run a stored procedure. The structure of the request is:
The arguments can be passed either using the GET or the POST method. For example, the following URL uses the GET method (where the arguments are appended to the URL) to execute the system procedure @SystemInformation on the VoltDB database cluster connected to the VMC service at vmc.mycompany.com: http://vmc.mycompany.com:8080/api/2.0/?Procedure=@SystemInformation Note that only the You can also include the parameters on the request. However, it is important to note that the parameters — and the response returned by the stored procedure — are JSON encoded. The parameters are an array (even if there is only one element to that array) and therefore must be enclosed in square brackets. Also, although there is an upper limit of 2 megabytes for the entire length of the parameter string, large parameter sets must be sent using POST to avoid stricter limitations on allowable URL lengths. The Perhaps the best way to understand the JSON interface is to see it in action. If you build and start the Hello World example application that is provided in the VoltDB distribution kit (including the client that loads data into the database and the VMC service), you can then open a web browser and connect to the local system through port 8080, to retrieve the French translation of "Hello World". For example: http://localhost:8080/api/2.0/?Procedure=Select&Parameters=["French"] The query returns the following results: {"status":1,"appstatus":-128,"statusstring":null,"appstatusstring":null,
"results":{"0":[{ "HELLO":"Bonjour","WORLD":"Monde"}]}}As you can see, the JSON-encoded results are not particularly easy to read. But they do provide a simple, generic interface accessible from almost any programming language, most of which provide methods for encoding and decoding JSON strings and interpreting their results. 8.2.2. Using the JSON Interface from Client ApplicationsThe general process for using the JSON interface from within a program is:
The following are examples of invoking the Hello World Insert stored procedure from several different languages. In each case, the three arguments (the name of the language and the words for "Hello" and "World") are encoded as a JSON string. PHP<?php
// Construct the procedure name, parameter list, and URL.
$voltdbserver = "http://myserver:8080/api/2.0/";
$proc = "Insert";
$a = array("Croatian","Pozdrav","Svijet");
$params = json_encode($a);
$params = urlencode($params);
$querystring = "Procedure=$proc&Parameters=$params";
// create a new cURL resource and set options
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $voltdbserver);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $querystring);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the request
$resultstring = curl_exec($ch);
?>Pythonimport urllib
import urllib2
import json
# Construct the procedure name, parameter list, and URL.
url = 'http://myserver:8080/api/2.0/'
voltparams = json.dumps(["Croatian","Pozdrav","Svijet"])
httpparams = urllib.urlencode({
'Procedure': 'Insert',
'Parameters' : voltparams
})
print httpparams
# Execute the request
data = urllib2.urlopen(url, httpparams).read()
# Decode the results
result = json.loads(data)Perluse LWP::Simple; my $server = 'http://myserver:8080/api/2.0/'; # Insert "Hello World" in Croatian my $proc = 'Insert'; my $params = '["Croatian","Pozdrav","Svijet"]'; my $url = $server . "?Procedure=$proc&Parameters=$params"; my $content = get $url; die "Couldn't get $url" unless defined $content; C#using System;
using System.Text;
using System.Net;
using System.IO;
namespace hellovolt
{
class Program
{
static void Main(string[] args)
{
string VoltDBServer = "http://myserver:8080/api/2.0/";
string VoltDBProc = "Insert";
string VoltDBParams = "[\"Croatian\",\"Pozdrav\",\"Svijet\"]";
string Url = VoltDBServer + "?Procedure=" + VoltDBProc
+ "&Parameters=" + VoltDBParams;
string result = null;
WebResponse response = null;
StreamReader reader = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "GET";
response = request.GetResponse();
reader = new StreamReader(response.GetResponseStream(),Encoding.UTF8 );
result = reader.ReadToEnd();
}
catch (Exception ex)
{ // handle error
Console.WriteLine( ex.Message );
}
finally
{
if (reader != null)reader.Close();
if (response != null) response.Close();
}
}
}
}8.2.3. How Parameters Are InterpretedWhen you pass arguments to the stored procedure through the JSON interface, VoltDB does its best to map the data to the datatype required by the stored procedure. This is important to make sure partitioning values are interpreted correctly. For integer values, the JSON interface maps the parameter to the smallest possible integer type capable of holding the value. (For example, BYTE for values less than 128). Any values containing a decimal point are interpreted as DOUBLE. String values (those that are quoted) are handled in several different ways:
Table 8.1, “Datatypes in the JSON Interface” summarizes how to pass different datatypes in the JSON interface. Table 8.1. Datatypes in the JSON Interface
8.2.4. Interpreting the JSON ResultsMaking the request and decoding the result string are only the first steps. Once the request is completed, your application needs to interpret the results. When you decode a JSON string, it is converted into a language-specific structure within your application, composed of objects and arrays. If your request is successful, VoltDB returns a JSON-encoded string that represents the same ClientResponse object returned by calls to the callProcedure method in the Java client interface. Figure 8.1, “The Structure of the VoltDB JSON Response” shows the structure of the object returned by the JSON interface. Figure 8.1. The Structure of the VoltDB JSON Response { status (integer)
appstatus (integer)
statusstring (string)
appstatusstring (string)
results (list)
{ result-index (array)
[
{ column-name (any type) ,...
}
]
}
}The key components of the JSON response are the following:
It is possible to create a generic procedure for testing and evaluating the result values from any VoltDB stored procedure. However, in most cases it is far more expedient to evaluate the values that you know the individual procedures return. For example, again using the Hello World example that is provided with the VoltDB software, it is possible to use the JSON interface to call the Select stored procedure and return the values for "Hello" and "World" in a specific language. Rather than evaluate the entire results array (including the name and type fields), we know we are only receiving one result object with two column values. So we can simplify the code, as in the following python example: import urllib
import urllib2
import json
import pprint
# Construct the procedure name, parameter list, and URL.
url = 'http://localhost:8080/api/2.0/'
voltparams = json.dumps(["French"])
httpparams = urllib.urlencode({
'Procedure': 'Select',
'Parameters' : voltparams
})
# Execute the request
data = urllib2.urlopen(url, httpparams).read()
# Decode the results
results = json.loads(data)[u'results']
volttable = results[u'0']
row = volttable[0]
# Get the data by column name and display them
hello = row[u'HELLO']
world = row[u'WORLD']
print hello, world8.2.5. Error Handling using the JSON InterfaceThere are a number of different reasons why a stored procedure request using the JSON interface may fail: the VoltDB server may be unreachable, the database may not be started yet, the stored procedure name may be misspelled, the stored procedure itself may fail... When using the standard Java client interface, these different situations are handled at different times. (For example, server and database access issues are addressed when instantiating the client, whereas stored procedure errors can be handled when the procedures themselves are called.) The JSON interface simplifies the programming by rolling all of these activities into a single call. But you must be more organized in how you handle errors as a consequence. When using the JSON interface, you should check for errors in the following order:
8.2.6. Managing Client SessionsFor intermittent use, the JSON Interface can be very effective and easy to use. The API server creates a new client connection for each request which, for occasional ad hoc queries, is simple and performs sufficiently well. However, if you intend to make frequent repeated requests, the cumulative cost of opening and closing separate client connections for each request can be significant — both in terms of latency for your application and memory usage on the server to manage so many transient client connections. The better approach is to have all of your requests share the same client connection. The JSON interface allows for this through the use of cookies. When your application first makes a successful request to the server, the server response includes a cookie that identifies the client session. The cookie, JSESSIONID_nnnn, consists of a name (JSESSIONID) plus the client port number of the server. For all subsequent calls to the JSON interface, your application can return that cookie to the server and the server will reuse the initial client connection. This makes subsequent calls much faster, since they do not have to bear the cost of creating a new session. Every few minutes, the server will close the connection and open a new client. At which point it passes a new value for the cookie and your application can then return this new cookie value for subsequent calls. [2] Hashing the password stops the text of your password from being detectable from network traffic. However, it does not make the database access any more secure. To secure the transmission of credentials and data between client applications and VoltDB, enable TLS encryption for the HTTP port using the configuration file. | ||||||||||||||||||||||||||||
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |