NOTICE

Examples in code-styled blocks can contain a different URL. You have to change it according to yours reseller URL (e.g. cloud.camstreamer.com).

Creating and using API tokens

Copy link

Authorization

Copy link

All communication with the API server has to be authorized via an access token. The valid token has to be inserted to the header of each API call. Token can be created by a user with full account access in the portal.

  1. Make sure your account has the full account access rights.
    • If your account is limited you will not be able to see API menu item.
    • In this case ask your administrator to provide you with full account access rights.
  2. Press the icon of the user in the right up corner and select option API.
  3. Press the Create an API token button to add a new access token and access rights to it.
  4. Use the token in the header of each API call.

Authorization header

"Authorization : Bearer TOKEN”

Example of authorization

curl -X POST -H 'Authorization: Bearer TOKEN' -H "Content-Type: application/json" --data-binary '{"query":"{cameraList{name}}"}' https://system2.netrex.cz/api/graphql.php

Introduction to GraphQL API

Copy link

The portal uses GraphQL to access the API, which is an alternative for a more widespread REST model. The server interprets the query string and returns a response with the data in the required format. It provides a comprehensive and clear description of the data in the API, giving client applications the ability to request exactly the data they need.

GraphQL uses two types of operations. Query operations are used to read data. Mutations are used to change data. Individual query and mutation operations are sent in the POST endpoint request. Add “api/graphql.php” after your portal address.

The endpoint remains constant regardless of the operation being performed.

HINT

More about GraphQL in this article. More about transition from REST to GraphQL in this article.

Using the API

Copy link

Detailed documentation of all available types, queries and mutations in the GraphQL API is available in the API Explorer. To open it, just add “api/explorer/index.html” after your portal address. The most important information for a quick start is described in the chapter Most common scenarios for API integration.

NOTICE

The public API does not support all actions that are supported in the user interface. If you are interested in an unsupported action, contact our Support.

API Explorer

Copy link

To test querying, we recommend using the API Explorer, which allows you to authorize a user account and test queries interactively. API Explorer allows the user to suggest, validate, and perform specific queries and mutations over the data of a connected account. You can also use Explorer to view and browse the structured documentation of all cloud API queries, mutations, and data types. The documentation is opened by clicking on Docs in the upper right corner.

Once opened, you need to log in to your cloud account. Press the Login button in the upper right corner. Press the Explorer button to display a tree list of all queries and mutations, which simplifies query creation.

WARNING

By using the Explorer API you query and edit the data in your account. Be careful not to delete or modify important data.

Creating API token

Copy link

The API token is used to authorize client access to the system application interface and to the application interface of the camera that is connected to the portal.

  1. In the top right corner, press the button with the username you are logged in with.
  2. Open the API tab.
  3. Press the Create API Token button.
  4. Fill in any token name.
  5. Select the desired token expiration.
  6. Confirm with the Save button.

NOTICE

For the token to be usable for camera API authorization, it must have the Configuration permission enabled.

OAuth2 API authorization

Copy link

There are two ways to obtain an authorization token. The first option is to create a token in the user interface. This option is the simplest and is recommended for most API applications. The Oauth2 protocol can also be used to obtain a token. The steps described below describe the procedure for obtaining an authorization token using OAuth2.

HINT

We recommend using one of the available libraries to implement OAuth2. More information and an introduction to OAuth2.

Creating a client application

Copy link

First, we will create a new OAuth2 application. The OAuth2 application allows authorization to the API using any owner or guest account. The client application management interface is available after logging in to your account.

  1. Press the user icon in the upper right corner and select an API.
  2. Open the OAuth2 Application.

The OAuth2 application defines the requester for access to the application interface. The application can be used to authorize any system account.

NOTICE

Only full access accounts can create the application.

When creating an application, you need to enter the following information:

  • Name – enter any name, e.g. “My application”.
  • Description – enter any description.
  • List of redirect URLs – enter the URL to which the user is redirected after authorization.

TIP

We recommend creating a new client application for each integration.

After OAuth2 application is created, the app generates:

  • client_id – unique application identifier,
  • client_secret – application key,

which OAuth2 uses to obtain the authorization code “AUTHORIZATION_CODE”.

Obtaining an authorization code

Copy link

NOTICE

Examples in code-styled blocks can contain a different URL. If you have an account under another reseller, you have to change it according to yours reseller URL (e.g. cloud.camstreamer.com).

To obtain an authorization code, which can be further exchanged for an access token, the endpoint https://system2.netrex.cz/oauth2/auth is used.

POST:
https://system2.netrex.cz/oauth2/auth/?response_type=code&client_id=CLIENT_ID&redirect_uri=CALLBACK_URL&scope=read,write

Request parameters

ParameterDescription
client_idIdentifies the client application.
scopeComma-separated list of required rights. Possible rights are:
• read,
• write,
• liveview,
• audiotransmit,
• liveview_ptz,
• liveview_light,
• liveview_audioclip,
• recordings,
• recordings_delete,
• events.
redirect_urlURL to which the authorization code should be sent. It must be the same as URL allowed in the client application definition.
stateOptional security parameter that is passed back to redirect_url without change along with the authorization code.

First, you are redirected to the portal login screen. After logging in to your account, a dialog is displayed asking you to grant access to the client application. After confirming/rejecting the dialog, the redirect_url is redirected and the “code” parameter with the authorization code or the “error” parameter with the reason for the error is added to the GET parameters (“access_denied” if the user has rejected the access request). If the “state” parameter was specified in the request, it will be added to the redirection as well.

Obtaining an access token

Copy link

The endpoint https://system2.netrex.cz/oauth2/token and possibly also the refresh token is used to obtain the access token.

POST:
https://system2.netrex.cz/oauth2/token?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&grant_type=authorization_code&code=AUTHORIZATION_CODE&redirect_uri=CALLBACK_URL
ParameterDescription
client_idIdentifies the client application.
client_secretThe secret key of the client application, with the use of which it is possible to obtain permanent access to the API (access and refresh tokens). Without this parameter, only temporary access is granted (i.e. only access token). Note the client_secret parameter cannot be used where there is a risk of it leaking out. For example, it is not possible to use it in JavaScript applications.
redirect_urlOne of the redirect URLs listed in the client application definition. In this step, it only serves as an additional security feature and no further redirection occurs.
grant_typeParameter specifying the authorization method. The following options are available:
auth_code. This is the exchange of the authorization code from the previous step for an access token.
refresh_token. This is a renewal or exchange for a new access token for the next period.

Possible answers in JSON format:

{"access_token":"ACCESS_TOKEN","expires_in":3600,"refresh_token":"1234"} – Unlimited time access to the API. When the access token expires, a new one can be obtained by refreshing the token. For this type of access, you must use client_secret in the query.
{"access_token":"ACCESS_TOKEN","expires_in":3600} – One-time access to the API, canceled when the access token expires.
{"error":"Error message"} – Invalid request or system error.

The obtained ACCESS_TOKEN can be inserted into the header of each Graph API call (“Authorization: Bearer TOKEN”).

Canceling access token

Copy link

The access token can be canceled at any time in the user interface or using the API. The endpoint https://system2.netrex.cz/oauth2/revoke is used to cancel the access.

POST:
https://system2.netrex.cz/oauth2/revoke?access_token=ACCESS_TOKEN
ParameterDescription
access_tokenExisting token to delete.

Answer in JSON format:

{"success":true,”message”:”Info message”} – The given access token (even with its refresh token) is canceled.

User permissions for OAuth2

Copy link

The system distinguishes between full access and partial access users whose view may be restricted. If you use Oauth2 authorization, the data obtained through the API corresponds to the access rights of the user. If you want to ensure full visibility, use an account with full access rights when authorizing OAuth2 or generate a static API token.

Common scenarios for API integration

Copy link

NOTICE

Examples in code-styled blocks can contain a different URL. If you have an account under another reseller, you have to change it according to yours reseller URL (e.g. cloud.camstreamer.com).

You can use API Explorer to easily test the following examples. Click here to get the API authorization information.

Organization of objects

Copy link

The objects user, camera, electrical input, dashboard, folder and more are nodes in the tree structure. This structure allows:

  • Getting aggregated metrics from multiple objects.
  • Managing user permissions for a group of objects.
  • Organizing objects into groups for better clarity in the user interface.

The folder object allows for endless immersion. Some objects, such as electrical input, are always immersed under the camera object.

Example

List of all items that the user has the right to see. Keep in mind that with OAuth2 authorization, a token may be issued to a guest user who does not see all the items.

query {
 nodeList {
  parent_node_id
  node_id
  type
  name
 }
}

Answer

{
 "data": {
  "nodeList": [
   {
    "parent_node_id": null,
    "node_id": 138170,
    "type": "folder",
    "name": "rootfolder"
   },
   {
    "parent_node_id": 138170,
    "node_id": 138170,
    "type": "folder",
    "name": "San Diego"
   },
…
  ]
 }
}

If we want to get only objects “camera”, we use the optional parameter type. You can find all available types in the generated documentation in API Explorer.

query {
 nodeList(type:camera) {
  parent_node_id
  type
  name
  node_id
 }
}

Answer

{
 "data": {
  "nodeList": [
   {
    "parent_node_id": 138170,
    "type": "camera",
    "name": "ACCC8EE8A9CA",
    "node_id": 140094
   }
  ]
 }
}

Obtaining camera parameters

Copy link

The camera type is the most comprehensive type that we use when downloading recordings and getting a live stream. A query for the camera type returns many parameters about the camera.

Example

By querying the camera type, we obtain information about the serial number (serial_number), connection status (is_connected) and camera ip address (source_ip). The mandatory parameter node_id can be found using the previous query on cameraList or nodeList.

query {
 camera(node_id:140094){
  name
  serial_number
  is_connected
  connection{
   source_ip
  }
 }
}

Answer

{
 "data": {
  "camera": {
   "name": "ACCC8EE8A9CA",
   "serial_number": "ACCC8EE8A9CA",
   "is_connected": true,
   "connection": {
    "source_ip": "211.21.111.111"
   }
  }
 }
}

Accessing KPI metrics

Copy link

There are several types you can use to get KPI metrics:

statisticData

Returns a single value for one object (camera). Use this to get a single number from a single camera. For example: Number of visitors from people counting camera1.

Available metrics:

  • peopleCount – number of visitors.
  • peopleCountIn – number of visitors (entries only).
  • peopleCountOut – number of visitors (outputs only).
  • transactionValueIn – value of positive payment transactions (multiplied x 100).
  • transactionCountIn – number of positive payment transactions.
  • transactionValueOut – value of negative payment transactions (multiplied x 100).
  • transactionCountOut – number of negative payment transactions.
statisticDataMetric

Returns a single value for one object or multiple objects in a folder. Queries to the folder object return agregated value for all objects in the folder. Use this to get a single value agregated from multiple cameras. For example: Number of visitors from one store where all store cameras are in folder “San Diego”.

Available metrics:

  • peopleCountAverage – number of visitors.
  • peopleCountIn – number of visitors (only incoming).
  • peopleCountOut – number of visitors (only outgoing).
  • peopleCountPassBy – number of visitors passing by the store.
  • transactionCountPositive – number of positive transactions.
  • transactionCountNegative – number of negative transactions.
  • transactionAmountPositive – value of positive transactions.
  • transactionAmountNegative – value of negative transactions.
  • conversionCount – conversion count; (number of positive transactions / number of visitors) * 100.
  • conversionAmount – spend per visitor; (value of positive transactions / number of visitors).
  • transactionAmountAverage – average transaction value (only positive transactions).
statisticDataMetricByGranularity

Returns multiple values (data series) in a single query. Available metrics and aggregation is identical to above mentioned statisticDataMetric. Use this to fetch multiple values in one query. The parameter of this query is granularity. Granularity defines number of returned data points.

Granularity:

  • HQ – 15 minutes
  • H – hour
  • H4 – 4 hours
  • H8 – 8 hours
  • H12 – 12 hours
  • D – day
  • W – week
  • M – month

All metrics in the system are stored with 15 minutes resolution. If the query does not align to a 15 minutes interval, API will calculate the result using nearby intervals. Parameters “from” and “to” are in Unix Timestamp format. For testing purposes you can use Unix Timestamp Converter.

Example 1 – Fetching single value

Query to a folder returns aggregated peopleCountAverage for all cameras in the folder.

query {
 statisticDataMetric(from:1589186000, to:1589186780, type:peopleCountAverage,node_id:140094)
}​

Answer

{
 "data": {
  "statisticDataMetric": 57
 }
}

Example 2 – Fetching multiple values (time series)

Query to a folder returns an aggregated peopleCountAverage in 15 minutes granularity.

{
 statisticDataMetricByGranularity(from: 1589186000, to: 1589186780, type: peopleCountAverage, node_id: 63575, granularity: HQ) {
  from
  to
  value
 }
}

Answer

{
 "data": {
  "statisticDataMetricByGranularity": [
   {
    "from": 1589185800,
    "to": 1589186700,
    "value": 20
   },
   {
    "from": 1589186700,
    "to": 1589187600,
    "value": 12
   }
   …
  ]
 }
}

View live stream from the camera

Copy link

Query the camera type to find out the URL for accessing the live stream. The portal supports several protocols for video streaming. Protocols vary depending on camera access:

  • Access within the local network:
    • rtsp – Plain unencrypted RTSP.
  • Access via the public internet:
    • rtsp – Plain unencrypted RTSP.
    • rtsph – Unencrypted RTSP over HTTP.
    • rtsphs – Encrypted RTSP over HTTPS.
    • rtspws – Unencrypted RTSP over WebSocket.
    • rtspwss – RTSP over WebSocket Secure.

Security of access to live stream

An API query for a streaming URL generates an RTSP link that is valid for 30 seconds. After 30 seconds or disconnecting the player, it will not be possible to connect the player and the application must request a new RTSP link.

Player

To playback live video from the system we recommend using our web player available in GitLab repository. The player uses a combination of WebSocket Secure and RTSP protocol and is suitable for playing videos anywhere on the internet.

Example

This example shows how to get a video stream for a remote player. Most cameras allow streaming of different profiles (resolution and capture). Query the streamProfile type to find out the available profiles.

query {
 camera(node_id:140094){
  stream_profiles{
   stream_profile_id
   width
   height
  }
 }
}

Answer

{
 "data": {
  "camera": {
   "stream_profiles": [
    {
     "stream_profile_id": 120846,
     "width": 800,
     "height": 450
    },
    {
     "stream_profile_id": 120850,
     "width": 1920,
     "height": 1080
    }
   ]
  }
 }
}

The next query gets the RTSP and URL for the currently generated RTSP stream.

query {
 camera(node_id:140094){
  live_view(stream_profile_id:120850){
   remote{
    rtsp{
     url
    }
   }
  }
 }
}

Answer

{
 "data": {
  "camera": {
   "live_view": {
    "remote": {
     "rtsp": {
      "url": "rtsp://nvhs10.survilla.net:2554/nvhs10~1600421245~9469bb1a2b831031456ef9c4abc182573d7a86a9f305f54df18621a9484d6134"
     }
    }
   }
  }
 }
}

Some cameras support multiple video channels. For example, cameras with multiple optics or virtual views of 180 ° cameras. The channel can be selected by the optional parameter video_channel_node_id in the type live_view (stream_profile_id: 120850, video_channel_node_id: 1000). A list of video channels of each camera is available in camera type.

View and download of the recording

Copy link

The process of viewing / downloading a recording is divided into three steps:

  1. Check recording availability and obtain recording_id.
  2. Preparation of the recording in the required resolution.
  3. Get the URL to download the recording.

Following example shows the whole process.

Example

Recording_id is a unique record identifier. It is created when you check availability using the following query. We also ask about the available recording sizes that we will use in the next step. The highest available size corresponds to the default recording resolution and is the fastest to prepare. The “from” and “to” parameters define the required recording time period.

query{
 camera(node_id:62303){
  recordings(from:1589190089, to:1589190689){
   recording_id
   duration
   download_url
   outputs{
    height
   }
  }
 }
}

Answer

{
 "data": {
  "camera": {
   "recordings": [
    {
     "recording_id": "xRMElmAkh3",
     "duration": 598,
     "download_url": null,
     "outputs": [
      {
       "height": 480
      },
      {
       "height": 720
      },
      {
       "height": 800
      }
     ]
    }
   ]
  }
 }
}

If the answer contains an empty field, check in the user interface whether the given camera is recording or was recording in the selected interval. We will now call a mutation to prepare a recording, whose parameters are recording_id and height from the previous step.

mutation{
 recordingPrepare(recording_id:"xRMElmAkh3", height:720)
}

Answer

{
 "data": {
  "recordingPrepare": true
 }
}

A true value indicates that the recording preparation has started successfully. The state of preparation is obtained by querying the type of recording whose parameter is recording_id.

query{
 recording(recording_id:"6RjiHGzqCE"){
  progress
  download_url
 }
}

Answer

{
 "data": {
  "recording": {
   "progress": 100,
   "download_url": "https://cloud.camstreamer.com/api/download.php?auth_key=2YwmG01NAeNYz4m1bZfwIKLOaoHeCfxH"
  }
 }
}

In the answer we see “progress: 100”. The upload is ready and download_url contains the download URL. If the recording is still being prepared, download_url contains the value “null” and progress expresses the processing status in percent.
An unused recording ID expires in one hour. The URL to download the recording expires in 24 hours. If the recording is downloaded, the download URL expires after 6 hours.

Pairing elements using an External ID

Copy link

When querying the NodeList type, the external ID that was entered in the user interface can be displayed for all items in the tree structure. The external ID is used to uniquely identify the item for integration into third-party services. An external ID can be created in the API section.

Example

The following query returns a list of nodes, including the corresponding external IDs.

query{
 nodeList {
  name
  external_id
 }
}

Answer

{
 "data": {
  "nodeList": [
   {
    "name": "Folder",
    "external_id": "001"
   },
   {
    "name": "ACCC8EE8A9CA",
    "external_id": "camera1"
   }
  ]
 }
}

Camera access and VAPIX camera interface

Copy link

A camera connected to the cloud receives an unique URL that allows remote access to the camera. The ULR always consists of the camera’s serial number and the first- and second-order domains device-connect.net.
https://SerialNumber.device-connect.net/
Such access is particularly suitable for programmatic control of the camera via the VAPIX interface. VAPIX is an application interface that allows you to control the camera and change its parameters.
To authorize access to the camera and its VAPIX API, an API token with the Configuration permission (DEVICE_ACCESS_TOKEN) must be generated. The exact procedure for generating the token can be found in this article.

Example of a request to the camera API

From the URL and DEVICE_ACCESS_TOKEN you can make a request for the VAPIX interface of the camera:

https://serialnumber.device-connect.net/axis-cgi/param.cgi?action=update&ImageSource.I0.Sensor.Brightness=89&root.ImageSource.I0.Sensor.ColorLevel=91&DEVICE_ACCESS_TOKEN=NvA7fxxxxxtYVQ

where:

  • serialnumber is the serial number of the camera,
  • /axis-cgi/param.cgi is the standard URL on the VAPIX interface,
  • ?action=update&ImageSource.I0.Sensor.Brightness=89&root.ImageSource.I0.Sensor.ColorLevel=91 is a VAPIX request. In this case, we change the brightness and saturation of the image,
  • &DEVICE_ACCESS_TOKEN=NvA7fxxxxxtYVQ is a one-time access token listed as the last parameter of the query.

Example of calls to API of CamStreamer App

The query for the list of available streams on the camera:

https://accc8ed8cbf0.device-connect.net/local/camstreamer/stream/list.cgi?DEVICE_ACCESS_TOKEN=D8PxS7HyQZepEwM4

The query for starting the particular stream on the camera:

https://accc8ed8cbf6.device-connect.net/local/camstreamer/stream/set.cgi?stream_id=36559&enabled=1&DEVICE_ACCESS_TOKEN=D8PxS7HyQZepEwM4

Error answers and limits

Copy link

API Limit

Limit for API queries for one account:

  • 1 query/second,
  • 10 000 queries/day.

When querying for metrics (such as number of visitors), the expected query size is as follows:

  • 1 year maximum range,
  • 5 metrics (for example, branches, cameras, or different metrics).

For queries larger than the size specified above, the maximum number of queries per second needs to be evaluated individually.

Error responses

{
 "errors": [
  {
   "message": "Invalid or empty access token.",
   "category": "authError"
  }
 ]
}

Missing access token: Make sure the authorization token has been inserted in the header in the correct format.

{
 "errors": [
  {
   "message": "Access token expired.",
   "category": "expired"
  }
 ]
}

Expired access token: In the API section in the system, make sure that the token is valid. For an OAuth2 token, request a token refresh.

{
 "errors":[
  {
   "message":"Request to an unknown or unavailable platform.",
   "category":"client"
  }
 ]
}

Invalid access token: Make sure the authorization token has been inserted in the header in the correct format. The token is inserted in the header but is not valid.

External ID Settings

Copy link

The external ID is used to uniquely identify an element for integration into third-party services. The external ID is used as a unique identifier for each element when queried through the API after it is entered into the system. The external ID is also used to set shortcuts for controlling the monitoring station.

Adding an External ID

Copy link
  1. In the top right corner, press the button with your username.
  2. Open the API tab.
  3. Select the External ID application interface.
  4. Press the Add identifier button.
  5. Click in the Item text box to open the item tree window.
    • Select the folder or item to which you want to assign an external ID.
  6. Fill in the External Identifier.
  7. Confirm with the Save button.

Editing an External ID

Copy link
  1. Press the button next to the corresponding external ID.
  2. Edit the necessary parameters.
  3. Confirm with the Save button

Deleting an External ID

Copy link
  1. Press the button next to the external ID you want to delete.

Requesting an External ID in the API

Copy link

For information and examples about polling, see the article Common API Integration Scenarios.