Skip to content

6. REST API

carmelocassisi edited this page Oct 6, 2023 · 3 revisions

Almost all interactions with the TSDSystem database can be carried out through the REST API.

Swagger UI

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.

API design

The TSDSystem web API was designed to follow the classic rules and guidelines used in the world of REST services.

Resources names

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):

  • timeseries
  • channels
  • stations
  • stations/configs
  • sensors
  • sensortypes
  • sensortype_categories
  • digitizers
  • digitizertypes
  • nets
  • sites
  • owners
  • users
  • roles
  • permissions

URL design

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:

  • POST to create
  • GET to read
  • PUT/PATCH to update (fully or partially, respectively, the resource information)
  • DELETE to delete

HTTP response codes

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, the 304 - 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.

Examples of requests through the web API

The REST API Controller response, for any received request, has always the following structure (JSON):

{
  "params": {},
  "data": {},
  "error": {},
  "statusCode": 0,
  "records": 0
}

where:

  • params section contains the request input,
  • data section contains the requested dataset (for read operations) or the details about the operation result (for write operations),
  • error section contains any incoming error of the request,
  • statusCode section contains the HTTP response code (redundant info),
  • records or rows sections are used respectivelly for GET (read) or POST (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.

Create a resource using HTTP POST

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 (using IGNORE parameter - i.e. do not overwrite) contains existing timestamps. Then, new records are ignored, but no error occurred.

Read a resource using HTTP GET

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
}

Searching and ordering parameters

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_by to 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) or sort_by=name_desc (for descending order) to sort using name field;
  • to filter: to filter the dataset, the API requires the insertion of parameters in the querystring. For example, to obtain the time series having name containing the string 'RMS', add name=RMS into the GET URL querystring. Another example, if we want to get only those with an exact match, use name=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.

Update a resource using HTTP PATCH

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).

Delete a resource using HTTP DELETE

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
}

Clone this wiki locally