IoTGateway/RESTful API
Contents
1 Introduction
The WISE3310 exposes a comprehensive set of Web Service APIs for application integration purposes. The WISE3310 REST API allows you to build applications that use Representational State Transfer HTTP calls to retrieve, modify, or publish platform data. For example through the APIs, you are able to access all the functionality of the Server or to control a device from your application built on top of the WISE3310. The WISE3310 platform conforms to standard REpresentational State Transfer (REST) protocol to expose its Application Programming Interfaces (API). REST has emerged over the past few years as a predominant Web service design model. REST-style architectures consist of clients and servers. Clients initiate requests to servers, while servers process requests and return appropriate responses. Requests and responses are built around the transfer of representations of resources. A resource can be essentially any coherent and meaningful concept that may be addressed. A representation of a resource is typically a document that captures the current or intended state of a resource. WISE3310 RESTful APIs expose the standard action types (Create, Read, Update, and Delete) over the platform objects. They are capable of retrieving a resource representation in JSON format. You can use the REST HTTP Accept Header to specify the representation requested using the "application/json" Media Types.
2 Writing Web Services Client Applications
The WISE3310 provides a REST-style API over HTTP (or HTTPS). Users can write HTTP clients in their preferred programming language that get data/services from the WISE3310 and use or display the data in the way that they desire. Examples of such clients include Web pages and programs written in a language such as Python or Java. These clients send requests to the server using standard HTTP requests. The HTTP requests that WISE3310 supports are GET, PUT, POST, and DELETE. The server supports basic HTTP authentication and only valid users can access the database. To reduce the authentication overhead of multiple requests, either use an HTTP library that caches cookies, or cache the cookies JSESSIONID and SID yourself.
2.1 In a Web Browser
Any GET request can be typed into the URL field of a web browser. Some browser plug-ins (chrome plugin, DHC - REST/HTTP API Client) also allow other HTTP methods to be called.
2.2 Python
Python scripts can be written to send standard HTTP requests to the server. These scripts use Python libraries to handle connecting to the server, sending the request, and getting the reply. Use urllib2 to send request
Example:
GET:
import urllib2 import base64 username = 'NAME' password = 'PWD' url = 'http://localhost/restapi/AccountMgmt' base64string = base64.encodestring('%s:%s' % (username, password))[:-1] req = urllib2.Request(url) req.add_header("Authorization", "Basic %s" % base64string) req.add_header('Content-type', 'application/json') response = urllib2.urlopen(req).read() print(response)
PUT:
import urllib2 import base64 username = 'NAME' password = 'PWD' url = 'http://localhost/restapi/AccountMgmt/Login' data = '{"username":"admin","password":"1234"}' base64string = base64.encodestring('%s:%s' % (username, password))[:-1] req = urllib2.Request(url) req.get_method = lambda: 'PUT' req.add_header("Authorization", "Basic %s" % base64string) req.add_header('Content-Type', 'application/json') response = urllib2.urlopen(req, data).read() print(response)
2.3 C#
HTTP requests can be sent to the server through a Java program. The key classes are HttpWebRequest and HttpWebResponse from System.Net.
Example:
GET:
static string HttpGet(string url) { HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest; req.Credentials = new System.Net.NetworkCredential("NAME", "PWD"); string privilege = string.Format("{0}:{1}", acut, pwd); byte[] bytes = System.Text.Encoding.GetEncoding("utf-8").GetBytes(privilege); req.Headers.Add("Authorization", Convert.ToBase64String(bytes)); req.Accept = "application/json"; string result = null; using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(resp.GetResponseStream()); result = reader.ReadToEnd(); } return result; }
PUT:
static string HttpPost(string url) { HttpWebRequest req = WebRequest.Create(new Uri(url)) as HttpWebRequest; req.Credentials = new System.Net.NetworkCredential("NAME", "PWD"); req.Method = "PUT"; req.ContentType = "application/json"; req.Accept = "application/json"; string privilege = string.Format("{0}:{1}", acut, pwd); byte[] bytes = System.Text.Encoding.GetEncoding("utf-8").GetBytes(privilege); req.Headers.Add("Authorization", Convert.ToBase64String(bytes)); StringBuilder paramz = new StringBuilder(); paramz.Append("{\"username\":\"admin\",\"password\":\"1234\"}"); byte[] formData = UTF8Encoding.UTF8.GetBytes(paramz.ToString()); req.ContentLength = formData.Length; // Send Request: using (Stream post = req.GetRequestStream()) { post.Write(formData, 0, formData.Length); } // Response: string result = null; using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(resp.GetResponseStream()); result = reader.ReadToEnd(); } return result; }
2.4 Java
HTTP requests can be sent to the server through a Java program. use java.net.URL and java.net.HttpURLConnection to send request.
Example:
GET:
private static void HttpGet(String urlstr) { String username = "NAME", password = "PWD"; HttpURLConnection conn = null; String userPassword = username + ":" + password; String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes()); try{ URL url = new URL(urlstr); conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Authorization", "Basic " + encoding); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : "+ conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch(Exception e) {} }
PUT:
private static void HttpPOST(String urlstr) { String username = "NAME", password = "PWD"; HttpURLConnection conn = null; String userPassword = username + ":" + password; String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes()); try{ URL url = new URL(urlstr); conn = (HttpURLConnection)url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("PUT"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Authorization", "Basic " + encoding); String input = "{\"username\":\"admin\",\"password\":\"1234\"}"; OutputStream outputStream = conn.getOutputStream(); outputStream.write(input.getBytes()); outputStream.flush(); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : "+ conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch(Exception e){} }
2.5 Javascript
use jQuery's $.ajax() to send request
Example:
$.ajax( { type: put, url: 'http://localhost/restapi/AccountMgmt', data: '{"username":"admin","password":"1234"}', contentType: 'application/json', dataType: 'text', error: function(xhr, exception) { //TODO }, beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + $.base64.encode(user + ":" + password)); }, success: function(response) { } });