Difference between revisions of "IoTGateway/RESTful APIv2"

From ESS-WIKI
Jump to: navigation, search
Line 233: Line 233:
 
       }
 
       }
 
   }
 
   }
 +
 +
== REST Resource ==
 +
[[File:Restfulapi resource.png]]

Revision as of 08:38, 28 June 2016

Introduction

The IoT Gateway exposes a comprehensive set of Web Service APIs for application integration purposes. The IoT Gateway 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 IoT Gateway.

The IoT Gateway 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.

IoT Gateway 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 IoT Gateway 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 IoT Gateway 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 IoT Gateway 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/AccountInfo'
 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/AccountConfig'
 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/AccountConfig',
     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

IoT Gateway 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 1051 Input Invalid JSON
Service Access 1151 Invalid URL
Service Access 1152 Invalid Method

Example:

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

REST Resource

Restfulapi resource.png