Getting Started with REST API

You can have programmatic access to your data in the Cloud database and to an on-premise server by using a simple and secure REST-based web services API.

Account and Organization owners, as well as Account and Organization administrators, can access the REST API commands. Your devices can be managed and monitored both in the UI and by using REST API commands. You can use the UI to verify that the commands that you sent by using the REST API were properly and successfully executed.

 

Table of Contents

Terminology

Overview

Authorization protocol

Prerequisites

Set up the REST API

1. Create an API client for the application

2. Get an Access Token for a REST API Call

3. Authenticate with REST API by using the Access Token

Use the API Commands

Date-time Format

Limited Results

HTTP Status Codes 

Testing your REST API Commands by Using Postman REST Client

Examples of Common API Calls

 

Terminology

Terminology

Definition

Authentication Server Entity that protects data and validates credentials before authorizing an API Client to take any action on behalf of an end user.
API Client Entity that represents your application and allows use of OAuth2 for authentication.
Client Credentials API key and secret for the API Client.
Access Token Token provided by the Authorization Server to the client application to authorize access to data.
grant_type This must be client_credentials.
client_id Your application's API Client Key.
client_secret Your application's API Client Secret.

 

Overview

Ayyeka uses OAuth 2.0 for authentication, which means that after you generate a REST API key and secret in the UI, you will submit those credentials to our authentication server to receive a temporary token.

The Access Token gives your application access to data that is stored on the Ayyeka Cloud or on your on-premise server for 60 minutes.

The API Client Key and API Client Secret are valid indefinitely.
You submit the temporary token in the header of your REST API calls for every submission. The token will allow you to retrieve the data you request.
When the temporary token expires, you need to generate a new temporary token, and then use the new token for all REST calls until it expires.
The Postman API platform facilitates interactive testing and learning of API methods, particularly the authentication process. You can use Postman to test your API calls before you implement them in your environment.

Authorization Protocol

When an API function is called by a user, the system checks the user’s permissions to learn which devices that user can manage, and whether the user has permission to perform the action.

The industry-standard OAuth 2.0 protocol allows you to authorize API client access to your data via the REST API. This protocol enables you to grant access to an API client without having to share your username and password. You can view and revoke the API client that you authorized in your account settings.

Only the client credentials grant type is supported. For more information about OAuth 2.0, see The OAuth 2.0 Authorization Framework.

 

Prerequisites

  • You need a basic familiarity with software development, REST web services, and the UI.
  • If you want to use Postman to test your REST APIs, download the application and install it.
  • You must have an Account/Organization Owner role or an Account/Organization Administrator role to generate the API Client Key and the API Client Secret. 
You must not generate the REST API keys when logged in as a user with the Partner role.
For an on-premises system, you must not generate the REST API keys when logged in as the (super) Admin user. The keys generated by the Admin user will not work.
  •  If you want to use Swagger to run your APIs, download the application and install it.
  • The API queries run in your Account. If you need to run API commands in several Accounts, you must generate a different API Client Key and API Client Secret for each Account.
  • If your data is stored on an on-premise server rather than on the Ayyeka Cloud, you must use different URLs for REST API Domain and for the Authentication Server. The following table gives the URLs to use when the data that the API needs to access is on the Cloud and on an on-premise server. Use these URLs in the procedures below. 

 

URL Type 

Data is on the Cloud 

Data is on an On-Premise Server 

Authentication 

Server (for Access Token generation) 

https://restapi.ayyeka.com/auth/token 

http://<on-premise server IP>:85 /auth /token 

 Note:

  • You must use "http" and not "https".
  • If the on-premise server is only accessible through the user’s network, then the router/NAT must be configured for port-forwarding. The external port must be mapped to port 85 on the on-premise server. 

REST API Domain 

(for REST API requests) 

https://restapi.ayyeka.com 

http://<on-premise server IP>:85/v2.0 (or /v1.0) 

Note:

  • You must use "http" and not "https".
  • If the on-premise server is only accessible through the user’s network, then the router/NAT must be configured for port-forwarding. The external port must be mapped to port 85 on the on-premise server.  

     

     

    Set up the REST API 

    1. Create an API Client for the application

      1. Get the API Client Key and Secret by doing the following steps in the UI:

    i.  In the left pane, click API, and then click the API Clients tab.

    ii.  In the API Clients window, click +Generate API Key.

    iii.  In the Generate API Key window, select REST, type in a comment, and then click Generate.

    Important: Record the API Client Key and the API Client Secret in a secure place because there is no way to access the API Client Secret in the future. You need them in step 4 below.

              b.   Click Close. The API Clients tab refreshes to display the new API Key in the table.

     

    2. Get an Access Token for REST API Calls

    To make a REST API call, you must include request headers, including the Authorization header, with an OAuth 2.0 Access Token.

    To get an Access Token, pass the [Api_Client_Key]:[Api_Secret] credentials to the Authorization Server (use the Authentication Server URL) in Base64 format in the Authorization header of a get Access Token request. 

    You must include request headers, including the Authorization header, with an OAuth 2.0 Access Token.

     
    The following figure illustrates the process:
        +---------+                                  +---------------+ 
    : : : :
    : :>-- A - Client Authentication --->: Authorization :
    : Client : : Server :
    : :<-- B ---- Access Token ---------<: :
    : : : :
    +---------+ +---------------+

      

     Example request: 

    APIClient Key

    APIClient Secret

    149F9AC689CB4F16853433AA0AE44E5F  

    ePs4G352BUD9FYCvPXEoz2RC5UYx/K8BoVs+mkrVfpg=

    POST /auth/token HTTP/1.1
    Host: https://restapi.ayyeka.com/auth/token
    Content-Type: application/x-www-form-urlencoded
    Authorization: Basic MTQ5RjlBQzY4OUNCNEYxNjg1MzQzM0FBMEFFNDRFNUY6ZVBzNEczNT
    JCVUQ5RllDdlBYRW96MlJDNVVZeC9LOEJvVnMrbWtyVmZwZz0=
    Cache-Control: no-cache 
    grant_type= client_credentials

     

    Example response:

    HTTP/1.1 200 OK
    Cache-Control: no-store
    Content-Type: application/json; charset=utf-8
    Date: Mon, 26 Jun 2017 14:36:08 GMT
    Pragma: no-cache
    Content-Length: 231
    Connection: keep-alive
    {"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp
    XVCJ9.eyJhdWQiOiIyIiwiZXhwIjoxNDk4NDkxMzY4LCJpYXQiOjE0OTg0ODc3NjgsImlzcy
    I6IkNsb3VkIiwic3ViIjoiMjc...",   
    "token_type":"JWT","expires_in":3600}

     

    Example using curl (How to complete the authentication process): 

    curl -X POST https://restapi.ayyeka.com/auth/token \
    -H 'Authorization: Basic MTQ5RjlBQzY4OUNCNEYxNjg1MzQzM0FBMEFFNDRFNUY6ZVBzNEczNT
    JCVUQ5RllDdlBYRW96MlJDNVVZeC9LOEJvVnMrbWtyVmZwZz0=' \
    -H 'Cache-Control: no-cache' \
    -H 'Content-Type: application/x-www-form-urlencoded' \
    -H 'Postman-Token: b0ee4f16-ac32-4429-b1e1-c39ee4793444' \
    -H 'cache-control: no-cache' \
    -d 'grant_type=client_credentials'

     

    3. Authenticate with the Access Token 

    Using the Access Token provided in the authorization response, the API client can now access the REST API on behalf of the authorizing user.

    Note the following items:

    • Use a header in the format Authorization: Bearer [token].
    • Your application should check for 403 errors. This error indicates that accessing the page or resource is forbidden. The cause might be that your application access was revoked, or that the token expired.

    The number of Authorization requests is limited to 15 requests per 15 minutes per key. If you exceed the limit, a warning message is displayed.

    Tip: To prevent hitting the limit, authorize only when the Access Token has expired rather than on every request. Excess token requests have a negative impact on server performance.

     

    Example request:

    GET /v1.0/site HTTP/1.1
    Host: <Authentication Server URL>
    Authorization:Bearer
    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiIyIiwi
    ZXhwIjoxNDk4NDkxMzY4LCJpYXQiOjE0OTg0ODc3NjgsImlzcyI6IkNsb3VkIiwic3ViIjoiMjc...
    Cache-Control: no-cache  
                                     

    Note that the Authorization:Bearer value is the "access_token" from the previous example response.

    Example response:

    HTTP/1.1 200 OK
    Content-Type: application/json;charset=UTF-8 
    [{"id":1,"creationDate":"2013-05-31T01:11:41Z","displayName":"Test
    Site","status":"Active","accountOrganizationId":2}]

     

    Example using curl:

    curl -X GET https://restapi.ayyeka.com/v2.0/site -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiIyIiwi ZXhwIjoxNDk4NDkxMzY4LCJpYXQiOjE0OTg0ODc3NjgsImlzcyI6IkNsb3VkIiwic3ViIjoiMjc' -H 'cache-control: no-cache'

     

    Use the REST API Commands

    In the UI, click API in the left pane , and then select API Documentation > API Reference (v2.0 or v1.0). A list of all REST APIs is documented.

    You can work with the APIs in Swagger. Swagger UI enables you to visualize and interact with the API’s resources without having any of the implementation logic in place.  In the UI, click the  Download a Swagger file link to download the Swagger yaml file to your local environment. Import the yaml file into Swagger.

    Note:
     - The limit for data requests is 1,000,000 requests within 15 minutes.
     - If you have the Partner role, some API calls might not return any results. 

     

    Date-time Format 

    The date-time format is yyyy:mm:ddThh:mm:ssZ.  For example, 2015-10-13T18:23:52Z.  

    The “T” separates the date from the time. The “Z” means "zero-hour offset", or also "Zulu time" (UTC). 

    Limited Results

    Some REST API calls limit the number of results that they will retrieve at a time.

    If the query name contains the string "Batch", then the first line of output will be “hasMore: true”. For example, you are testing the call sampleGetSamplesScalarBatchBySite in Postman, and you see the following output:

    To get subsequent results, run sampleGetSamplesScalarBatchBySite as many times as needed to get all of the results.

     

    Tip: If the query output is too large for a single call, then either narrow your search parameters or contact support@ayyeka.com.

     

    HTTP Status Codes 

    Status Code 

    Text 

    Description 

    200 

    OK 

    The API command was completed successfully. 

    304

    Not Modified 

    There was no new data to return. 

    400 

    Bad Request 

     

    The request was invalid or cannot be otherwise served. In 

    API v1.1, requests without authentication are not considered valid and give this response. 

    401

    Unauthorized 

    Authentication credentials were missing or incorrect. 

    403 

    Forbidden 

    The request was refused, or access was denied. 

    404 

    Not Found 

    The URI requested is not valid or the resource requested, for example, a user, does not exist. 

    406 

    Not Acceptable 

    Returned by the Search API when a format that is not valid is specified in the request. 

    429

    Too Many Requests

    The request cannot be served because the limit for the resources is exceeded. 

    500 

    Internal Server Error 

     

    The requested format is not supported by the requested method, or a runtime error has occurred. 

    The log files SystemOut.log, SystemError.log, and igc.log contain more information. 

    502

    Bad Gateway

    The server encountered a temporary error and could not complete the request. Usually, this is a temporary problem.

    503 

    Service Unavailable 

    The server is up, but it is overloaded with requests. Try again later. 

     

    Test your REST API Commands by Using Postman REST Client

    Use Postman to test your API calls before you implement them in your environment.

    Prerequisites

    For details about using Postman in your API development, see Postman-The Collaboration Platform for API Development.

    For details about using OAuth 2.0 with Postman, see OAuth 2.0 Authorization with Postman.

     

    To test your REST API commands:

    1. Generate an API Key in the UI. These keys will be used in the next step.
    2. Set up OAuth 2.0 token for authorization by doing the following steps (refer to  OAuth 2.0 Authorization with Postman):
      1. Open the Postman REST client application or web page.
      2. Go to the Authorization tab that is described in step 4 of OAuth 2.0 webpage.
      3. In the TYPE drop-down list, select OAuth 2.0 as described in step 5 of OAuth 2.0 webpage.
      4. Click Get New Access Token  as described in step 6 of OAuth 2.0 webpage.
      5. In the GET NEW ACCESS TOKEN window, fill in the following fields:
        • Token Name: Type in any text for the name.
        • Grant Type: Select Client Credentials
        • Access Token URL: Type in <Authentication Server URL>.
        • Client ID: Type in the APIClient Key.
        • Client Secret: Type in the APIClient Secret.
        • Scope: You may leave blank.
        • Client Authentication: Keep the default.
      6. Click Request Token. The Access Token will be displayed in a new window. Copy the Token.
      7. In the text box above the Authorization and Header tabs, you might need to type in the URL of the REST API Domain. This will create the Access Token (as shown in the screenshot below) that must be submitted in the header of all subsequent REST API calls for the lifetime of this token.

    Repeat the entire step 2 whenever this token expires (using the same Key/Secret pair) in order to execute future REST API calls.

     

      3.   Leverage the Authentication Token in REST API Calls in Postman by doing the following steps: 
      • If the “Use Token” button is enabled (in the above screen shot), click it to instantiate the Access Token in the header of subsequent REST API calls in this Postman instance.
      • If the “Use Token” button is not enabled, copy the Access Token from this panel, click to close the MANAGE ACCESS TOKENS window. Paste the Access Token into the Postman REST client header, by doing the following steps:
        1. Go to the Headers tab (located beside the Authorization tab).
        2. Click inside the vacant “Key” field, and then type Authorization. After you have typed the first few letters, click on the word that appears in the field.
        3. Click inside the vacant “Value” field next to the “Key” field, and then type "Bearer ”.
    Do not include the quotation marks and do make sure to include a space (“ “) following the word “Bearer ”.

             d. Paste the generated Access Token that was retrieved from the “Request Token” request from Step 2 above.

     4.  In the left pane of the UI, click API, and then click the API Documentation tab. Select API Reference v2.0 tab to view REST API calls to query the Ayyeka Cloud database for relevant Account, Site, Device, Channel, Stream, Samples and system data.

    Each call will retrieve a different set of data from the Ayyeka database, by formulating a URL that can be executed through the Postman REST Client. 

    5.   Copy the relevant URL from the API Documentation page, substitute any variables (such as device ID, serial number, account ID, and so forth), and then enter the URL in the text box in the Postman REST Client above the Auth and Headers tabs.

    Make sure you select the correct type of call (GET, POST, etc.), according to the API Documentation.

     6.   Click Send to submit the REST API query to the server. The Server’s response should appear on the right side of the screen on the “Body” tab.


     

    Examples of Common API Calls

    Q: How can I read the data sampling of a specific stream of a specific device for the last 4 hours?

    A: You can create an API command that returns sample aggregation from a specified stream and date range.  

    1. Go to API Documentation tab in the UI, and then look at the commands in the API METHODS – SAMPLE section. The API that you need is:  sampleGetSamplesScalarAggregationByStreamAnd DateRange 

    The API command would be: 

    https://<your API domain>/v2.0/stream/{streamId}/sample/agg?timeFrame=&fromDate=&toDate= 
      • To find the streamId of the stream whose data samples you need to aggregate, see the What's What - Unique Identification table. For this example, the streamID is 123456. 
      • The fromDate and toDate are in Epoch Unix format. For example, fromDate of 2021-09-27T06:00:00Z is 1630983600. A toDate of 2021-09-27T10:00:00Z is 1630998000.
      • The aggtimeFrame, the number of hours, is 4.

    Example:

    https://my_domain.com/v2.0/stream/123456/sample/agg?timeFrame=4&fromDate=1630983600&toDate=1630998000



    2.   Test the command in Postman. The output might be: 

    { 

    "stream_id": 123456, 

    "start_date": "2021-09-27T06:00:00Z", 

    "number_of_samples": 53, 

    "agg_values": { 

    "min": "0.384000", 

    "max": "0.385500", 

    "avg": "0.384321", 

    "sum": "20.369000" 



    }, 



    "stream_id": 123456, 

    "start_date": "2021-09-27T07:00:00Z", 

    "number_of_samples": 3, 

    "agg_values": { 

    "min": "0.384300", 

    "max": "0.384500", 

    "avg": "0.384400", 

    "sum": "1.153200" 



    }, 



    "stream_id": 123456, 

    "start_date": "2021-09-27T09:00:00Z", 

    "number_of_samples": 28, 

    "agg_values": { 

    "min": "0.384400", 

    "max": "0.981300", 

    "avg": "0.809361", 

    "sum": "22.662100" 



    }, 



    "stream_id": 123456, 

    "start_date": "2021-09-27T10:00:00Z", 

    "number_of_samples": 60, 

    "agg_values": { 

    "min": "0.978500", 

    "max": "0.980600", 

    "avg": "0.978837", 

    "sum": "58.730200" 



    }, 

     

    Q: How can I get information, such as the Site and the display name, about a specific stream?

    A: Use the getStreamById API command.  

    1. The API command would be:

    https://<your REST API domain>/v2.0/stream/{streamId} 

      2.   Test the command in Postman. The output might be: 



    "id": 123456, 

    "site_id": 11111, 

    "creation_date": "2020-12-25T08:10:082”, 

    "display_name": “Battery Life”, 

    “status_id”: 3, 

    “type_id”: 78, 

    “type_display_name”: “Battery Status”, 

    “units”: “%”, 

    ‘value_scale”: “0” 
    },