Skip to main content

Avnet IoTConnect Rest API

Project description

This document is reformatted to better viewing as a standalone document. We recommend visiting this GitHub v3.0.0 link for best experience.

iotc-python-rest-api

This project is the Python interface for /IOTCONNECT REST API.

The project provides a limited set of essential Python interfaces for the /IOTCONNECT REST API. with the primary focus on to providing architecture that can be easily expanded by future feature additions. Additional REST API interfaces can be easily implemented by your custom applications when using the provided facilities.

The project provides a reference CLI implementation as well, with reduced functionality when compared to the native python API support.

At this stage, the Python interface covers the following set of features with partial implementations covering most common use cases:

  • Obtaining details about devices, templates, entities, /IOTCONNECT users and OTA Firmware upgrades.
  • Creating and Deleting templates based on template JSON and x509 authentication based devices.
  • Managing OTA firmware and firmware upgrades, uploading files, scheduling and publishing OTA to devices.
  • Sending commands to devices.
  • Uploading and managing files /IOTCONNECT File Storage.
  • Creating and Deleting x509 authentication based devices.
  • Generating an ECC x509 self-signed certificate and a matching private key
  • Generating iotcDeviceConfig.json which can be used along with certificates to provide streamlined configuration for our Python SDK MQTT clients, like the Python Lite SDK.

At the architecture level, the project infrastructure provides:

  • A uniform way to configure REST API endpoints based on your account settings.
  • Authenticate, refresh and store the credentials into the OS user's home directories.
  • Streamlined REST API calls and error reporting.

[!NOTE]
Devices created with REST API cannot be simply deleted in the /IOTCONNECT the UI. The delete icon will be grayed out. Either use this library to delete the device or check the checkbox next to your device in the device list and click Delete (Bulk Delete) at the rop of the device list page.

Rest API Credentials

This REST API implementation requires the user to authenticate with their /IOTCONNECT credentials, which in turn will store the session token into your home directory of your operating system.

This token will be valid for 24 hours, unless it is extended automatically for another 24 hours when you use the API (see the section below).

Automatic Token Refresh

By default, the API will attempt to refresh your session token, which is stored in your home directory, whenever you use any API calls. This refresh will trigger as long as the last refresh occurred at least one hour (default) since the last time it was refreshed.

Installing

Install this package by running this command:

python3 -m pip install iotconnect-rest-api

Getting Started

This package will install the iotconnect-cli utility, which can be invoked from command line.

This utility may be installed into different places depending on whether you install this package for all users, your user, or whether the package is installed from a Python virtual environment. Therefore, ensure that the iotconnect-cli location is in the PATH environment variable.

To get familiar with supported commands, first run the iotconnect-cli script with --help parameter:

iotconnect-cli --help

Values can be specified explicitly on the command line, or as environment variables described in the environment variables section:

iotconnect-cli configure --help
usage: iotconnect-cli configure [-h] [-u USERNAME] [-p PASSWORD] [-s SKEY] [--pf {aws,az}] [-e {poc,prod,avnet}]

Configure /IOTCONNECT credentials. Credentials from the environment will be used if arguments are not supplied. This action will store these settings configuration file and allow you
to run this tool without authenticating for 24 hours since last authentication token (automatic) refresh. All arguments are required, but environment variables can be used instead.

options:
  -h, --help            show this help message and exit
  -u USERNAME, --username USERNAME
                        Your account username (email). IOTC_USER environment variable can be used instead.
  -p PASSWORD, --password PASSWORD
                        Your account password. IOTC_PASS environment variable can be used instead.
  -s SKEY, --skey SKEY  Your solution key. IOTC_SKEY environment variable can be used instead.
  --pf {aws,az}, --platform {aws,az}
                        account platform ("aws" for AWS, or "az" for Azure). IOTC_PF environment variable can be used instead.
  -e {poc,prod,avnet}, --env {poc,prod,avnet}
                        account environment - From settings -> Key Vault in the Web UI. IOTC_ENV environment variable can be used instead

/IOTCONNECT Solution Key is required to use the API. You will need to request the solution key for your account via the /IOTCONNECT support ticket system available in the main menu of the /IOTCONNECT web page.

Use your credentials to configure the API:

# On Linux and similar, for security reasons, ensure this variable is set accordingly.
# We don't want our password to be stored in history, so this is the safest way to avoid having the password stored in plain text.
# Alternatively, though this is still not a very secure approach, you can also export IOTC_PASS in 
# your .profile or windows environment variables panel for convenience.
export HISTCONTROL=ignoreboth
 
# ... then add space in front of the line below:
 iotconnect-cli configure -u my@email.com -p "MyPassword" --pf az --env avnet --skey=MYSOLUTIONKEY  

Examples

Once the CLI is configured, API can be invoked to create a device in your account for example.

# ensure that sample-device-template.json from example is in the current directory
# clone this repo or copy the file locally
cd examples
# create the template and use a different template code and name than the one in the template json:
iotconnect-cli create-template ./sample-device-template.json --code=apidemo --name=apidemo
# prepare a new automatically generated certificate for our device that we will create
# this step creates device-cert.pem and device-pkey.pem
iotconnect-cli generate-cert apidemo-device01
# create a new device apidemo-device01 with the generated cert (default cert from previous step picked up)
iotconnect-cli create-device apidemo apidemo-device01

Now that our device is fully configured, we can install run the python SDK:

# ensure that sample-device-template.json from example is in the current directory
# clone this repo or copy the file locally
cd examples
python3 -m pip install iotconnect-sdk-lite
python3 lite-sdk-example.py

When done testing or evaluating, the device should be deleted, as it will not be possible to use the /IOTCONNECT Web UI to delete it:

iotconnect-cli delete-device apidemo-device01
iotconnect-cli delete-template apidemo-device01

API Usage with Python

To learn how to use the API, is suggested to start with the examples/basic-api-example.py, and then get familiar with the unit tests.

Programmatic Querying, Filtering and Pagination

List endpoints follow one consistent pattern: each module exposes a query() function that takes a typed, per-endpoint query object and returns a Page of results. Filtering, sorting and pagination all happen server-side — only the fields you set are sent.

from avnet.iotconnect.restapi.lib import device
from avnet.iotconnect.restapi.lib.device import DeviceQuery, DeviceStatus 
from avnet.iotconnect.restapi.lib.query import Sort, Order

# Each field is a documented, typed filter. Enums constrain values that the API fixes.
page = device.query(DeviceQuery(
    status=DeviceStatus.ACTIVE,
    template="mytmpl01",                 # template code OR GUID - resolved for you
    sort_by=Sort(device.SORT_DUID, Order.ASC), # or even as plain string f"{device.SORT_DUID} {Order.ASC}"
    page_size=50,
))

print("total matching devices:", page.total_count)   # server-reported total
for d in page:                                        # iterate the current page
    print(d.uniqueId, d.isActive)

for d in page.all():                                  # ...or walk every page transparently
    print(d.uniqueId)

Fields that reference another object (a template, an entity, a firmware) accept either a GUID or a friendly identifier (template code, entity name, firmware name) and resolve it to the GUID automatically — so you rarely need to look up GUIDs yourself. The same *Query objects exist for templates, firmware, firmware upgrades and users (TemplateQuery, FirmwareQuery, UpgradeQuery, UserQuery).

entity.query() is the exception: the /Entity endpoint exposes no filter or pagination parameters in the API, so it takes no query object and returns a plain list of all entities (filter it in Python).

Time-bound queries accept native Python types. Telemetry history, for example, takes a datetime, an ISO-8601 string, or a timedelta (a duration back from to_time):

from datetime import timedelta
from avnet.iotconnect.restapi.lib import telemetry
from avnet.iotconnect.restapi.lib.telemetry import TelemetryQuery

records = telemetry.get_history(TelemetryQuery("my-device-01", from_time=timedelta(minutes=5)))

Configuration Environment Variables

These variables can be used to store your credentials permanently:

Name Description
IOTC_PF Platform of your /IOTCONNECT account "aws" for AWS and "az" for Azure
IOTC_ENV Environment /IOTCONNECT account. It can be found at Settings -> Key Vault in the /IOTCONNECT Web UI
IOTC_SKEY Your Solution Key
IOTC_USER Your /IOTCONNECT username (email)
IOTC_PASS Your /IOTCONNECT password

Special Environment Variables

Name Description
IOTC_API_TRACE Setting this to any value will add add extra information to REST calls and some debug information.
IOTC_API_NO_TOKEN_REFRESH Setting this to any value will disable the automatic token refresh.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

iotconnect_rest_api-3.0.0.tar.gz (44.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

iotconnect_rest_api-3.0.0-py3-none-any.whl (52.9 kB view details)

Uploaded Python 3

File details

Details for the file iotconnect_rest_api-3.0.0.tar.gz.

File metadata

  • Download URL: iotconnect_rest_api-3.0.0.tar.gz
  • Upload date:
  • Size: 44.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for iotconnect_rest_api-3.0.0.tar.gz
Algorithm Hash digest
SHA256 1a9b9deede39ffe769b92ffd1cee1b2f7cd3d12ee8f94213dea6b4552f183ff3
MD5 1eecf5b9694c62ab008a8bcf837eb3ec
BLAKE2b-256 a0bdbd92b5d3a17f0715c82c91b5b579ba275373ee7041df4979a6466421a4c7

See more details on using hashes here.

File details

Details for the file iotconnect_rest_api-3.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for iotconnect_rest_api-3.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 94548182a7aa3998d1ed28dc606247f5c5c2a76284000e18799d1101a3f45057
MD5 27b8a54a69a5036f070e1b5ba851c050
BLAKE2b-256 bc7c8cd6b707835c059b480f10daf7e5901e23efd674b8a32857a024961b0dbd

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page