Difference between revisions of "IoTGateway/RESTful API"

From ESS-WIKI
Jump to: navigation, search
(Add section 3-4.1)
(Add 4.x items)
Line 1: Line 1:
== 1. Introduction ==
+
== 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 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.
 
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.
 
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 ==
+
== 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.
 
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 ===
+
=== In a Web Browser ===
 
Any GET request can be typed into the URL field of 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.
 
Some browser plug-ins (chrome plugin, DHC - REST/HTTP API Client) also allow other HTTP methods to be called.
 
[[File:Restfulapi dhc.png]]
 
[[File:Restfulapi dhc.png]]
  
=== 2.2 Python ===
+
=== 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.  
 
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
 
Use urllib2 to send request
Line 46: Line 46:
 
   print(response)
 
   print(response)
  
=== 2.3 C# ===
+
=== C# ===
 
HTTP requests can be sent to the server through a Java program.  
 
HTTP requests can be sent to the server through a Java program.  
 
The key classes are HttpWebRequest and HttpWebResponse from System.Net.
 
The key classes are HttpWebRequest and HttpWebResponse from System.Net.
Line 101: Line 101:
 
   }
 
   }
  
=== 2.4 Java ===
+
=== Java ===
 
HTTP requests can be sent to the server through a Java program.  
 
HTTP requests can be sent to the server through a Java program.  
 
use java.net.URL and java.net.HttpURLConnection to send request.
 
use java.net.URL and java.net.HttpURLConnection to send request.
Line 171: Line 171:
 
   }
 
   }
  
=== 2.5 Javascript ===
+
=== Javascript ===
 
use jQuery's $.ajax() to send request
 
use jQuery's $.ajax() to send request
  
Line 196: Line 196:
 
   });
 
   });
  
== 3. Web Services ==
+
== Web Services ==
=== 3.1 URL Specification ===
+
=== URL Specification ===
 
WISE3310 Web Services APIs are RESTful in nature. Every URL relates to a specific resource or list of resources.  
 
WISE3310 Web Services APIs are RESTful in nature. Every URL relates to a specific resource or list of resources.  
  
Line 208: Line 208:
 
| HTTP VERB|| POST/PUT* || GET || PUT || DELETE
 
| HTTP VERB|| POST/PUT* || GET || PUT || DELETE
 
|}
 
|}
=== 3.2 Return Error Code ===
+
=== Return Error Code ===
 
{| class="wikitable"
 
{| class="wikitable"
 
|-
 
|-
Line 237: Line 237:
 
   }
 
   }
  
== 4. REST Resource ==
+
== REST Resource ==
 
[[File:Restfulapi resource.png]]
 
[[File:Restfulapi resource.png]]
=== API Information ===
+
 
 +
* <big>API Information</big>
 +
 
 
The following resources are applicable:
 
The following resources are applicable:
 
* /APIInfoMgmt
 
* /APIInfoMgmt
==== /APIInfoMgmt ====
 
  
 +
<big>/APIInfoMgmt</big>
 
<big>GET</big>
 
<big>GET</big>
  
Line 264: Line 266:
 
   } }
 
   } }
  
=== 4.1 Account Management ===
+
=== Account Management ===
 
==== Accounts ====
 
==== Accounts ====
 
The following resources are applicable:
 
The following resources are applicable:
Line 283: Line 285:
 
Table 4.1.1 (a)
 
Table 4.1.1 (a)
  
==== /AccountMgmt ====
+
* <big>/AccountMgmt</big>
 
<big>GET</big>
 
<big>GET</big>
  
Line 327: Line 329:
 
   }
 
   }
  
=== /AccountMgmt/acuntName/<name> ===
+
* <big>/AccountMgmt/acuntName/<name></big>
 
<big>GET</big>
 
<big>GET</big>
  
Line 367: Line 369:
 
   "result" : "true"
 
   "result" : "true"
 
   }
 
   }
 +
 +
=== System Management ===
 +
 +
=== Process Management ===
 +
 +
=== WSN Management ===

Revision as of 07:25, 24 February 2016

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.

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.

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. Restfulapi dhc.png

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)

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;
 }

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){}
 }

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) 
     {                    
     }
 });

Web Services

URL Specification

WISE3310 Web Services APIs are RESTful in nature. Every URL relates to a specific resource or list of resources.

URI: http://<ip address>/restapi/<resource path> All REST APIs use CRUD Conventions as follows:

Action Create Read Update Delete
HTTP VERB POST/PUT* GET PUT DELETE

Return Error Code

Catalog Error Code Description
Server Status 1001 Internal Sever Error
Input Argument and Data 1501 Input Invalid JSON
Input Argument and Data 1502 Input Argument Error
Output Data 1101 Output Invalid JSON
Service Access 1151 Invalid URL
Service Access 1152 Invalid Method
Service Access 1153 Read Only

Example:

 {
     "result": {
         "ErrorCode": "1051",
         "Description": "Input Invalid JSON"
     }
 }

REST Resource

Restfulapi resource.png

  • API Information

The following resources are applicable:

  • /APIInfoMgmt

/APIInfoMgmt GET

Retrieve all API resources, and API version.

Request :

Ex:

 curl -H "Content-Type: application/json" -X GET http://username:password@172.22.12.34/restapi/APIInfoMgmt

Response Body: (media type: application/json)

 { "result" : { "Mgmt" : { "item" : [ "AccountMgmt",
             "SystemMgmt",
             "ProcessMgmt",
             "WSNMgmt"
           ] },
     "totalsize" : 4,
     "version" : 1.0.0"
 } }

Account Management

Accounts

The following resources are applicable:

  • /AccountMgmt
  • /AccountMgmt/acuntName/<name>
Item Description
totalsize Number of items in the result.
username Account name.
password Account password, but will not show real password.
lastchange Account last change time.

Table 4.1.1 (a)

  • /AccountMgmt

GET

Retrieve all accounts information.

Request :

Ex:

 curl -H "Content-Type: application/json" -X GET http://username:password@172.22.12.34/restapi/AccountMgmt

Response Body: (media type: application/json)

 {
   "result" : {
     "item" : [
        {
           "password" : "$1$44809109$pK1LHNBwMNRL1T5OHTLl3.",
           "lastchange" : "1444809109",
           "username" : "admin"         }
     ],
     "totalsize" : 1
    }
 }


PUT

Change account password.

Required fields: username, password Request Body: (media type: application/json)

 {
     "username":"admin",
     "password":"1234"
 }

Ex:

 curl -H "Content-Type: application/json" -X PUT -d '{ "username":"admin", "password":"1234"}'
 http://username:password@172.22.12.34/restapi/AccountMgmt

Response Body: (media type: application/json)

 {
  "result" : "true"
 }
  • /AccountMgmt/acuntName/<name>

GET

Retrieve specific account information by account name.

Request :

Ex:

 curl -H "Content-Type: application/json" -X GET http://username:password@172.22.12.34/restapi/AccountMgmt/acuntName/admin

Response Body: (media type: application/json)

 {
  "result" : {
     "item" : {
        "username" : "admin",
        "password" : "$1$44613844$SHHhya9WJ72FSD17OG6SE/",
        "lastchange" : "1443662918"
     }
  }
 }

PUT

Change specific account password.

Required fields: password

Request Body: (media type: application/json)

 {
   "password":"1234"
 }

Ex:

 curl -H "Content-Type: application/json" -X PUT -d '{ "password":"1234"}' 
 http://username:password@172.22.12.34/restapi/AccountMgmt/acuntName/admin

Response Body: (media type: application/json)

 {
  "result" : "true"
 }

System Management

Process Management

WSN Management