REST API & SDK
Learn how to authenticate with the Arduino Cloud REST API to make requests using HTTP Client, JavaScript and Python®.
The Arduino Cloud REST API can be accessed through a set of endpoints to manage Devices, Things, Properties and more. It can be accessed via any HTTP client, and is supported by JavaScript, Python® and Golang clients.
In this article you will find some useful examples to get started with the Arduino Cloud API, and an understanding of what the API offers.
To see the full API, follow the link below:
To authenticate with the Arduino Cloud API, you will need to set up an Arduino Account. How to generate API credentials will be explained in this article.
Requirements
To connect with the Arduino Cloud API, we will need one of the following clients:
You can also use services such as Postman to create HTTP requests.
Usage
With the Arduino Cloud API, you are able to interface with the Arduino Cloud service through JavaScript, Python® and Golang.
You can for example write custom scripts that can:
- Fetch latest data from a specific selection of properties.
- Switch a large number of booleans at the same time.
- Automatically notify you if a Thing has stopped updating values.
Mainly, it can be used to integrate an existing software project with the Arduino Cloud service. You can for example display real time data from your Arduino on your website, or create automatic email triggers whenever a threshold value is met.
API Keys & Authentication
To authenticate, you will need to generate a
clientId
and clientSecret
. This is generated in the Arduino Cloud UI. Follow the steps below to generate your credentials:1. Log in to your Arduino account.
2. Navigate to the API Keys page.
3. Click "CREATE API KEY". Name it, and save it as a PDF. You will not be able to see
clientSecret
again.Obtaining IDs
All main components of the Arduino Cloud have an
id
associated. You can access your device, Thing & variable id
from the web interface.For example, your Thing ID is stored in the "Metadata" tab of your Thing.
You can also make a request that will return a list of the component and all information about it:
- lists all Things and associated properties/variables.https://api2.arduino.cc/iot/v2/things
- lists all devices.https://api2.arduino.cc/iot/v2/device
- lists all dashboard and associated widgets.https://api2.arduino.cc/iot/v2/dashboards
You can make more specific requests to obtain only the information on a specific Thing, or a specific variable.
Note that you will need to pass the authentication token in the body when making any request to the Arduino Cloud REST API. The examples in this guide includes the generation of such token. For testing the API, you can follow the Postman setup just below.
Postman
Postman is a service that allows you to construct and make HTTP requests. In the panel, you can create a workspace, and a new HTTP request.
Before we can make requests to the API, we will need to generate an access token. To do so, you will need to configure the "Authorization" tab, according to the images shown below:
Now, click on the "Advanced Options" tab, and add
https://api2.arduino.cc/iot
to the "Audience" field.Finally, click on the "Get New Access Token".
You now have an access token that has an expiry of
300
seconds, and we can make requests to the API.You can for example try
- GET |
https://api2.arduino.cc/iot/v2/dashboards
Which should look like this in the Postman UI:
Note that your access token expires after
seconds. After that, you will need to re-generate it by clicking the button again.300
JavaScript (node.js)
Requirements:
To install the
arduino-iot-client
, run the following command:1npm install @arduino/arduino-iot-client
After it is installed, you can create a
.js
file, e.g. main.js
that you can write your script in. First, we need to authenticate with the Arduino Cloud API:
1var IotApi = require('@arduino/arduino-iot-client');2var rp = require('request-promise');3
4async function getToken() {5 var options = {6 method: 'POST',7 url: 'https://api2.arduino.cc/iot/v1/clients/token',8 headers: { 'content-type': 'application/x-www-form-urlencoded' },9 json: true,10 form: {11 grant_type: 'client_credentials',12 client_id: 'YOUR_CLIENT_ID',13 client_secret: 'YOUR_CLIENT_SECRET',14 audience: 'https://api2.arduino.cc/iot'15 }16 };17
18 try {19 const response = await rp(options);20 return response['access_token'];21 }22 catch (error) {23 console.error("Failed getting an access token: " + error)24 }25}
Then, we make a call to the Arduino Cloud API. In the example below will just list out the Properties attached to a specific Thing.
1async function listProperties() {2 var client = IotApi.ApiClient.instance;3 // Configure OAuth2 access token for authorization: oauth24 var oauth2 = client.authentications['oauth2'];5 oauth2.accessToken = await getToken();6
7 var api = new IotApi.PropertiesV2Api(client)8 var id = "XXX"; // {String} The id of the thing9
10 var opts = {11 'showDeleted': true // {Boolean} If true, shows the soft deleted properties12 };13 api.propertiesV2List(id, opts).then(function(data) {14 console.log(data); 15 });16}17
18listProperties();
And to run the script, you can simply use:
1node main.js
In your terminal, you will now receive a response akin to:
1[2 ArduinoProperty {3 href: '/iot/v1/things/<thingid>/properties/<propertyid>',4 id: '<propertyid>',5 name: 'Prop_1',6 permission: 'READ_WRITE',7 thing_id: '<thingid>',8 type: 'INT',9 update_strategy: 'ON_CHANGE',10 created_at: 2022-09-07T12:42:22.593Z,11 last_value: 'N/A',12 persist: true,13 tag: 2,14 thing_name: 'Arduino_Thing',15 updated_at: 2022-09-07T12:42:22.593Z,16 variable_name: 'Prop_1'17 }18]
As this is a
json
object, we can access it by changing the following line from the example above to access the different values. We can for example retrieve the last_value
from the first property like this:1console.log(data[0].last_value);
This is one of many examples of how to interact with the API. Now that you are setup, you can go on to explore the rest of the Arduino Cloud API.
Python®
Requirements:
- Python® 3.7+
- arduino-iot-client (Python®)
To install, use the following command:
1pip install arduino-iot-client
To authenticate, you will need to have the
requests-oauthlib
installed:1pip install requests-oauthlib
To generate an access token use the following script:
1from oauthlib.oauth2 import BackendApplicationClient2from requests_oauthlib import OAuth2Session3
4from os import access5import iot_api_client as iot6from iot_api_client.rest import ApiException7from iot_api_client.configuration import Configuration8
9# Get your token 10
11oauth_client = BackendApplicationClient(client_id="YOUR_CLIENT_ID")12token_url = "https://api2.arduino.cc/iot/v1/clients/token"13
14oauth = OAuth2Session(client=oauth_client)15token = oauth.fetch_token(16 token_url=token_url,17 client_id="YOUR_CLIENT_ID",18 client_secret="YOUR_CLIENT_SECRET",19 include_client_id=True,20 audience="https://api2.arduino.cc/iot",21)22
23# store access token in access_token variable24access_token = token.get("access_token")
Then, to authenticate with the generated token, use:
1client_config = Configuration(host="https://api2.arduino.cc/iot")2client_config.access_token = access_token3client = iot.ApiClient(client_config)
And to for example, list out properties attached to a Thing:
1thing_id = "YOUR_THING_ID"2
3# as an example, interact with the properties API4api = iot.PropertiesV2Api(client)5
6try:7 resp = api.properties_v2_list(thing_id)8 print(resp)9except ApiException as e:10 print("Got an exception: {}".format(e))
As this is a
json
object, we can access it by changing the following line from the example above to access the different values. We can for example retrieve the last_value
from the first property like this:1print(resp[0].last_value)
The following script lists out Properties attached to your Thing. Simply replace
YOUR_CLIENT_ID
, YOUR_CLIENT_SECRET
and YOUR_THING_ID
with your credentials and this script will work out of the box. 1from oauthlib.oauth2 import BackendApplicationClient2from requests_oauthlib import OAuth2Session3
4from os import access5import iot_api_client as iot6from iot_api_client.rest import ApiException7from iot_api_client.configuration import Configuration8
9# Get your token 10
11oauth_client = BackendApplicationClient(client_id="YOUR_CLIENT_ID")12token_url = "https://api2.arduino.cc/iot/v1/clients/token"13
14oauth = OAuth2Session(client=oauth_client)15token = oauth.fetch_token(16 token_url=token_url,17 client_id="YOUR_CLIENT_ID",18 client_secret="YOUR_CLIENT_SECRET",19 include_client_id=True,20 audience="https://api2.arduino.cc/iot",21)22
23# store access token in access_token variable24access_token = token.get("access_token")25
26# configure and instance the API client with our access_token27
28client_config = Configuration(host="https://api2.arduino.cc/iot")29client_config.access_token = access_token30client = iot.ApiClient(client_config)31thing_id = "YOUR_THING_ID"32
33# as an example, interact with the properties API34api = iot.PropertiesV2Api(client)35
36try:37 resp = api.properties_v2_list(thing_id)38 print(resp)39except ApiException as e:40 print("Got an exception: {}".format(e))
Golang
To access the Arduino Cloud API via the Go client, you can refer to the arduino/iot-client-go client on GitHub.
Below is an example that will authenticate with the API and list out all your devices.
1package main2
3import (4 "context"5 "log"6 "net/url"7
8 iot "github.com/arduino/iot-client-go"9 cc "golang.org/x/oauth2/clientcredentials"10)11
12var (13 clientID = "your_client_id"14 clientSecret = "your_client_secret"15)16
17func main() {18 // We need to pass the additional "audience" var to request an access token19 additionalValues := url.Values{}20 additionalValues.Add("audience", "https://api2.arduino.cc/iot")21 // Set up OAuth2 configuration22 config := cc.Config{23 ClientID: clientID,24 ClientSecret: clientSecret,25 TokenURL: "https://api2.arduino.cc/iot/v1/clients/token",26 EndpointParams: additionalValues,27 }28 // Get the access token in exchange of client_id and client_secret29 tok, err := config.Token(context.Background())30 if err != nil {31 log.Fatalf("Error retrieving access token, %v", err)32 }33 // Confirm we got the token and print expiration time34 log.Printf("Got an access token, will expire on %s", tok.Expiry)35
36 // We use the token to create a context that will be passed to any API call37 ctx := context.WithValue(context.Background(), iot.ContextAccessToken, tok.AccessToken)38
39 // Create an instance of the iot-api Go client, we pass an empty config40 // because defaults are ok41 client := iot.NewAPIClient(iot.NewConfiguration())42
43 // Get the list of devices for the current user44 devices, _, err := client.DevicesV2Api.DevicesV2List(ctx, nil)45 if err != nil {46 log.Fatalf("Error getting devices, %v", err)47 }48
49 // Print a meaningful message if the api call succeeded50 if len(devices) == 0 {51 log.Printf("No device found")52 } else {53 for _, d := range devices {54 log.Printf("Device found: %s", d.Name)55 }56 }57}
See the full example on GitHub.
Summary
This document covers the overall usage of the Arduino Cloud API, and how to use it with different clients (JavaScript, Python®, Golang).
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.