-
Notifications
You must be signed in to change notification settings - Fork 0
6. REST API
Almost all interactions with the TSDSystem database can be carried out through the REST API.
The Swagger UI tool is used to design, test and generate API documentation.
The Swagger interface provides:
- a description of the service offered by the API;
- the API URLs and the list of any parameters or body payloads accepted in input, the semantic meaning and the structure that each parameter must have.
- the structure of the API response on both success and failure.
- the meaning of the different HTTP states of the API response.
Once an instance of the TSDSystem has been activated, it is possible to consult and test the REST API documentation at the address (e.g. in localhost): http://localhost/swagger/tsdsystem.
The TSDSystem web API was designed to follow the classic rules and guidelines used in the world of REST services.
Starting from /tsdws/ root URL, the following collections of resources have been defined and are accessible to users basing on the allowed permissions (for details on the assignment of rights, see the "Resource access policies" page):
timeserieschannelsstationsstations/configssensorssensortypessensortype_categoriesdigitizersdigitizertypesnetssitesownersusersrolespermissions
For resources, plural names have been used in the URLs: for example, to interact with sensors resources, the URL /sensors will be used. In this way we are dealing with the collection. Other URL examples: /nets, /channels, etc.
To interact with a specific instance of a resource the URL will be formatted as follows: /{collection}/{resource_id} (e.g. /nets/1).
URLs like getNodes/, getTimeseries/, etc. have been deliberately avoided. The type of operation (read, write, update, delete) is identified by the VERB of the HTTP method. The HTTP protocol, in fact, provides several methods to implement the CRUD (Create Read Update Delete) principle. Each functionality that allows interaction with the domain's resources has been mapped with the relevant HTTP method:
-
POSTto create -
GETto read -
PUT/PATCHto update (fully or partially, respectively, the resource information) -
DELETEto delete
A client sending a request to the server through the API will be able to interpret the feedback by means of the HTTP code provided in the response by the server.
The server uses standard codes with a specific meaning (for more details see also https://developer.mozilla.org/it/docs/Web/HTTP/Status), with regard to the operation outcome. Below is a summary of the most used HTTP codes:
-
2XX(SUCCESSFUL category): the codes starting with the number 2 are codes used to confirm that the request has been received and successfully processed by the server. Examples:-
200- Ok. The standard answer to represent the success of a GET, PUT or POST operation (except for resource creations). -
201- Created. This code communicates that the new instance has been successfully created. For example, in creating a new resource using the POST method. -
204- No Content. It means that the request was successfully processed, but did not return any content.
-
-
3XX(REDIRECTION category): for example, the304- Not Modified - indicates that the client already has the response cached and there is no need to resend it. -
4XX(CLIENT ERROR category): this category includes errors correctly handled by the server, caused by incorrect input:-
400- Bad Request: indicates that the request has not been processed because the server does not recognize the request as one of the expected ones: for example, incorrect url or incorrect parameter name. -
401- Unauthorized: indicates that the client does not have the privileges to access this resource (the requested API requires authentication or an authentication token). -
403- Forbidden: indicates that the request made is valid and the client is correctly authenticated, but does not have the privileges to use this specific API method. -
404- Not Found: indicates that the requested resource does not exist or is temporarily unavailable. -
410- Gone: indicates that the requested resource is not available and intentionally moved.
-
-
5XX(SERVER ERROR category): this category of errors represents not correctly handled situations, such as server-side exceptions or temporarily unavailable services.-
500- Internal Server Error: indicates that the request is valid, but the server has encountered an unhandled error (e.g. a not correctly caught exception). -
503- Service Unavailable: indicates that the server is offline and therefore cannot process requests.
-
The REST API Controller response, for any received request, has always the following structure (JSON):
{
"params": {},
"data": {},
"error": {},
"statusCode": 0,
"records": 0
}
where:
-
paramssection contains the request input, -
datasection contains the requested dataset (for read operations) or the details about the operation result (for write operations), -
errorsection contains any incoming error of the request, -
statusCodesection contains the HTTP response code (redundant info), -
recordsorrowssections are used respectivelly forGET(read) orPOST(write) requests, and represents the number of found records or affected rows, respectivelly.
Some examples of requests in cURL language on a local TSDSystem instance (localhost) are shown below.
curl -X 'POST' \
'http://localhost/tsdws/nets' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"name": "Infrasonic"
}'
The successfull response should contain the HTTP code 201 to confirm the creation, with the data section containing the status (boolean), the number of records affected by the modification (rows) and the id assigned to the created resource.
{
"params": {
"name": "Infrasonic"
},
"data": {
"status": true,
"rows": 1,
"id": 2
},
"error": null,
"statusCode": 201
}
NOTE: In some special case, and for some specific resources, a succssfull response could contain the HTTP code
207- No rows inserted. This code communicates that no new records were created. An example could be when the request for inserting timeseries values (usingIGNOREparameter - i.e. do not overwrite) contains existing timestamps. Then, new records are ignored, but no error occurred.
curl -X 'GET' \
'http://localhost/tsdws/nets?sort_by=name' \
-H 'accept: application/json'
In this example, the request want to see the entire nets collection (all records). An example of successfull response (200 HTTP code) is shown below:
{
"params": {
"sort_by": "name"
},
"data": [
{
"id": 2,
"name": "Infrasonic",
"owner_id": null,
"n_nodes": 0
},
{
"id": 1,
"name": "Seismic",
"owner_id": 1,
"n_nodes": 17
}
],
"error": null,
"statusCode": 200,
"records": 2
}
To see a specific resource of the collection, the id has to be specified into the URL, as in the following example:
curl -X 'GET' \
'http://localhost/tsdws/nets/1' \
-H 'accept: application/json'
Successfull response:
{
"params": {
"id": 1
},
"data": [
{
"id": 1,
"name": "Seismic",
"owner_id": 1,
"n_nodes": 17
}
],
"error": null,
"statusCode": 200,
"records": 1
}
The server allows you to perform queries using the API URLs. During the API design phase, the inclusion of some parameters in the URL querystring was foreseen. The following are managed:
-
for ordering: use
sort_byto sort the records in an ascending/descending order based on the value of a field. For example:sort_by=name(default will be in ascending order -sort_by=name_asc) orsort_by=name_desc(for descending order) to sort usingnamefield; -
to filter: to filter the dataset, the API requires the insertion of parameters in the querystring. For example, to obtain the time series having
namecontaining the string 'RMS', addname=RMSinto theGETURL querystring. Another example, if we want to get only those with an exact match, usename=RMS&exact_match=true. NOTE: To effectively filter the dataset the name of the parameter has to match the name of one of the resource attributes (field), otherwise it is ignored.
To update a resource, REST APIs usually provide the PUT method endpoints for a fully replace of a record relating to a resource by identifier (id), while the PATCH method is used for a partial update (some record fields). In the TSDSystem REST API all updates are treated as partials and then only PATCH method endpoints are available for both cases.
Below is an example of a PATCH request to update the name of the resource with id=1:
curl -X 'PATCH' \
'http://localhost/tsdws/nets/2' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"name": "Clinometric",
"owner_id": 1
}'
A successfull response will contain the 202 HTTP code (Accepted).
To delete a resource, the DELETE HTTP method is used.
Below is an example of a DELETE request of resource of the collection nets with id=2:
curl -X 'DELETE' \
'http://localhost/tsdws/nets/2' \
-H 'accept: application/json'
In reality, this operation does not permanently delete a record in the database, but updates the remove_time (see the Database Model page) field with the timestamp of the request for deletion operation. For this reason the response to a DELETE request contains the HTTP code 202 and will be completely similar to that of the PATCH request:
{
"params": {
"id": 2
},
"data": {
"status": true,
"rows": 1
},
"error": null,
"statusCode": 202
}