Difference between revisions of "IoT Restful API"
(→Get image representation of spatial query results) |
(→Get image representation of spatial query results) |
||
Line 138: | Line 138: | ||
− | {{Note|Basic authentication is used. Do not forget to use '''user | + | {{Note|Basic authentication is used. Do not forget to use '''user'''/'''tenant''' as username where '''tenant''' is case sensitive}} |
==Asynchronous== | ==Asynchronous== |
Revision as of 10:46, 12 June 2017
Restful API
- Access control (See Access control and Actors)
- Restful API requires a username and password to authenticate at the client side.
- Result formats are json of a type that depends on the success of the request
- If an error occurred, the result has a jsonld of "@type":"/amtech/linkeddata/types/composite/outputMsg"
{
"message":"Resource /amtech/things/entities/gpsDevice/gpsDeviceParkingDemo already exists",
"targetResourceType":"/amtech/linkeddata/types/composite/entity/gpsDevice",
"errorType":"amtech.utils.model.ResourceAlreadyExistException",
"@type":"/amtech/linkeddata/types/composite/outputMsg",
"resource":"/amtech/things/entities/gpsDevice/gpsDeviceParkingDemo",
"success":false,
"messagedetail":""
}
- If the request is successful, the result is a jsonld representation of the resource, with details depending of the requested CRUD operation
CRUD operations on resources
API resources support all CRUD operations. Valid credentials must be supplied, meaning that the user must exist and have access (roles/actors) to perform the given CRUD operation on the resource. Sample CRUD operations on a thing instance :
- Create : via POST on the root endpoint /amtech, passing the json to of the resource to be created
curl -X POST -H "Authorization: Basic xxxxx" -H "Content-Type: application/json" -d '{
"@type": "/amtech/linkeddata/types/composite/entity/Truck",
"@id": "/amtech/things/entities/Truck/truck1",
"description" : "New truck",
"weight":100.0
}' "https://dap.amtech.mx/amtech"
- Read : via GET on the resource uri
curl -X GET -H "Authorization: Basic xxxxx" -H "https://dap.amtech.mx/amtech/things/entities/Truck/truck1"
- Update : via PUT on the root endpoint /amtech, passing the json to update in the body of the request. The json must include the @id and @type properties, along with all the properties that want to be updated
curl -X PUT -H "Authorization: Basic xxxxx" -H "Content-Type: application/json" -d '{
"@type": "/amtech/linkeddata/types/composite/entity/Truck",
"@id": "/amtech/things/entities/Truck/truck1",
"description" : "Updated description"
}' "https://dap.amtech.mx/amtech"
- Delete : via DELETE on the resource uri
curl -X DELETE -H "Content-Type: application/json" -u "userId:password" https://dap.amtech.mx/amtech/things/entities/Truck/truck1
Observation instances
- Getting observation types with property _blankinstancepublished return a blank jsonld ready to be filled and send
- /amtech/linkeddata/types/composite/observation
- Sending observations
- /amtech/things/events
- (See Observations and observation types)
rest.postJson(self.dapUrl + '/amtech/things/events', observation, options).on(
'complete', function(data, response) {
if (response && response.statusCode && response.statusCode !== 200) {
complete(self.buildError(response, "Sending observation"), data);
} else if (data instanceof Error) {
complete(data);
} else if (data['success'] === false) {
complete(self.buildDapError(data, 'At DapClient sendObservation'), data);
} else {
complete();
}
});
- Synchronous consumption of observation instances in topics
- /amtech/things/events?client=<client id>&topic=<topic uri>[&obstype=<obs type>]
- topic (See Topics)
- targetthings (See Target things)
- proximityarea (See Location)
- location (See Location)
- producer (See [[Sensor's network#Observations)
Thing instances
- CRUD operations
- /crud
- CRUD operation promises:
- /promise/amtech/things/entities
- (See Thing types)
Commands
Asynchronous consumption of commands using websocket’s pushing mechanisms (WIP) Same as asynchronous consumption of observations. The command received, which is also an observation instance, will have the target type and target URI into the targetthings property. (See targetthings)
- (See Send command)
Get observation production configuration
- Get observation configurations for a tenant/user tacking into account registered services and access control (See Actors)
- '/amtech/system/queries/observationconfigfromactivities'
- (See Observation production configuration)
Get instances by thing type
- Get things instances by type for a tenant/user taking into account registered services and access control (See Actors)
- '/amtech/things/entities/<thingType>'
rest.get(self.dapUrl + '/amtech/things/entities/gpsDevice', options).on(
'complete', function (data, response) {
if (response && response.statusCode && response.statusCode !== 200) {
complete(self.buildError(response, "Getting plugins instances"), data);
} else if (data instanceof Error) {
complete(data);
} else if ('success' in data && !data['success']) {
complete(self.buildDapError(data, 'At DapClient getPluginsInstances'), data);
} else {
complete(null, data.members);
}
});
Get resources with links (self contained)
The API supports URI parameters to retrieving resources resolving its link. There are 2 parameters : selfContained, and fullSelfContained
- selfContained parameter will resolve all embedded links (links whose URIs are direct children of the resource), including for example embedded collections and its members.
- fullSelfContained will resolve all links, embedded and external
In both cases, once a link is resolved, it will not be resolved again, so if it appears a second time in the resource, the link URI will be left unresolved
Get image representation of spatial query results
In order to export the query results as an image, use
https://dap.amtech.mx/offlinemaps
Arguments:
- url: amtech url of the observer, query or thing collection.
- ext: extension of the produced file. Supported extensions are .png (default) and .pdf
- observation: json of the observation required to run activity observers
- any query or observer argument
Examples:
- To create a .png image showing the endCustomers in the map use
https://dap.amtech.mx/offlinemaps?url=/amtech/things/entities/endCustomer
- Use the observer url to show its results. E.g:
https://dap.amtech.mx/offlinemaps?url=/amtech/observers/observerName
- For observers defined inside activity, the observation json must be included
https://dap.amtech.mx/offlinemaps?url=/amtech/activities/myActivity/observers/myObserver&observation={...}
Note: Basic authentication is used. Do not forget to use user/tenant as username where tenant is case sensitive
Asynchronous
- In order to authenticate the request from a web browser using window.WebSocket object you can put the authentication credentials in the URL as:
- wss://<user>:<pass>@<host>/amtech/push/things/events?client...
- (web sockets)
Observations
- Asynchronous consumption of observation instances in topics using websocket’s pushing mechanisms (WIP)
- wss://dap.amtech.mx/amtech/push/things/events?client=<client id>&topic=<topic uri>[&obstype=<obs type>]
- (See CRUD observations)
Commands
- Asynchronous consumption of commands using websocket’s pushing mechanisms (WIP)
- wss://dap.amtech.mx/amtech/push/things/commands?client=<client id>&thingtype=<thing type>&[&obstype=<obs type>]
Notifications
- Asynchronous consumption of notifications using websockets:
- wss://dap.amtech.mx/amtech/push/notifications[?clientid=<client id>]
- (See Notifications)
Things
- Consumption through websockets of promise execution results:
- /promise/amtech/results?client=<client_id>&thingtype=<thingtype>[&thinguri=<thinguri>]
Example
"use strict"; var websocket = require("websocket"); var wsclient = new websocket.client(); wsclient.on("connectFailed", function (error) { console.log("Connect error: " + error.toString()); }); wsclient.on("connect", function (connection) { console.log("WebSocket client connected"); connection.on("error", function (error) { console.log("Connection error: " + error.toString()); }); connection.on("close", function () { console.log("Connection closed"); }); connection.on("message", function (message) { if (message.type === "utf8") { console.log("Received: '" + message.utf8Data + "'"); } }); process.on('SIGINT', function () { console.log("Closing connection..."); connection.close(); setTimeout(function () { console.log("Closed"); }, 5000); }); }); var token = new Buffer("user/tenant:password").toString("Base64"); wsclient.connect("wss://dap.amtech.mx/amtech/push/notifications", null, null, { Authorization: "Basic " + token });
Clone
There are two endpoints for cloning resources :
- /amtech/clone/resourceandlinks<resourceToCloneUri>?newname=<nameForClone>
A GET on this endpoint will clone the specified resource without persisting it, generating clones for all the links referenced in the resource. Ex. If called with a resource LLRPReader1, that has 2 anntenas, it will generate a clone for the each of the antennas and the LLRPReader.
- /amtech/clone/resourceflat<resourceToCloneUri>?newname=<nameForClone>
A GET on this endpoint will clone the specified resource without persisting it and without cloning the links referenced in the resource.
A POST on either endpoint will clone the resource and persist it
There are entities' properties such as "proximity area" and "activity for observation production" whose values are always copied to the new resource as a reference, instead of cloning them.
Cloning is supported for :
- Entity type
- Observation type
- Supported properties
- Entity instances
- Observation instances
CRUD promises
CRUD promises are like any other CRUD operation on things except that they are asynchronously executed. When you execute a PUT, POST or DELETE on the promises endpoint, the corresponding thing will be asynchronously created, updated or deleted by an engine that executes operations sequentially over the same thing instance.