|
| 1 | +--- |
| 2 | +title: 'Arduino Cloud REST API & SDK' |
| 3 | +difficulty: advanced |
| 4 | +description: 'Learn how to authenticate with the Arduino IoT Cloud REST API to make requests using HTTP Client, JavaScript and Python.' |
| 5 | +tags: |
| 6 | + - IoT Cloud REST API |
| 7 | + - JavaScript |
| 8 | + - Python |
| 9 | + - node.js |
| 10 | + - Golang |
| 11 | +author: 'Karl Söderby' |
| 12 | +--- |
| 13 | + |
| 14 | +The [Arduino IoT Cloud REST API](https://www.arduino.cc/reference/en/iot/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. |
| 15 | + |
| 16 | +In this article you will find some useful examples to get started with the Arduino IoT Cloud API, and an understanding of what the API offers. |
| 17 | + |
| 18 | +To see the full API, follow the link below: |
| 19 | +- [Arduino IoT Cloud API](https://www.arduino.cc/reference/en/iot/api/) |
| 20 | + |
| 21 | +***To authenticate with the Arduino IoT Cloud API, you will need to set up an [Arduino Account](https://cloud.arduino.cc/home/). How to generate API credentials will be explained in this article.*** |
| 22 | + |
| 23 | +## Requirements |
| 24 | + |
| 25 | +To connect with the Arduino Cloud API, we will need one of the following clients: |
| 26 | + |
| 27 | +- [Javascript NPM package](https://www.npmjs.com/package/@arduino/arduino-iot-client) |
| 28 | +- [Python PYPI Package](https://pypi.org/project/arduino-iot-client/) |
| 29 | +- [Golang Module](https://github.com/arduino/iot-client-go) |
| 30 | + |
| 31 | +***You can also use services such as [Postman](https://www.postman.com/) to create HTTP requests.*** |
| 32 | + |
| 33 | +## Usage |
| 34 | + |
| 35 | +With the Arduino Cloud API, you are able to interface with the Arduino Cloud service through JavaScript, Python and Golang. |
| 36 | + |
| 37 | +You can for example write custom scripts that can: |
| 38 | + |
| 39 | +- Fetch latest data from a specific selection of properties. |
| 40 | +- Switch a large number of booleans at the same time. |
| 41 | +- Automatically notify you if a Thing has stopped updating values. |
| 42 | + |
| 43 | +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. |
| 44 | + |
| 45 | +## API Keys & Authentication |
| 46 | + |
| 47 | +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: |
| 48 | + |
| 49 | +**1.** Log in to your [Arduino account](https://cloud.arduino.cc/home/). |
| 50 | + |
| 51 | +**2.** Navigate to the [Arduino Cloud home page](https://cloud.arduino.cc/home/). |
| 52 | + |
| 53 | +**3.** Click **"API keys"** at the bottom left corner, and then click **"CREATE API KEY"**. Name it, and save it as a PDF. You will **not** be able to see `clientSecret` again. |
| 54 | + |
| 55 | + |
| 56 | + |
| 57 | +## Obtaining IDs |
| 58 | + |
| 59 | +All main components of the Arduino IoT Cloud have an `id` associated. You can access your **device, Thing & variable** `id` from the web interface. |
| 60 | + |
| 61 | +For example, your Thing ID is stored in the **"Metadata"** tab of your Thing. |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | +You can also make a request that will return a list of the component and all information about it: |
| 66 | +- `https://api2.arduino.cc/iot/v2/things` - lists all Things and associated properties/variables. |
| 67 | +- `https://api2.arduino.cc/iot/v2/device` - lists all devices. |
| 68 | +- `https://api2.arduino.cc/iot/v2/dashboards` - lists all dashboard and associated widgets. |
| 69 | + |
| 70 | +You can make more specific requests to obtain only the information on a specific Thing, or a specific variable. |
| 71 | + |
| 72 | +***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.*** |
| 73 | + |
| 74 | +## Postman |
| 75 | + |
| 76 | +[Postman](https://www.postman.com/) 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**. |
| 77 | + |
| 78 | +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: |
| 79 | + |
| 80 | + |
| 81 | + |
| 82 | +Now, click on the **"Advanced Options"** tab, and add `https://api2.arduino.cc/iot` to the **"Audience"** field. |
| 83 | + |
| 84 | + |
| 85 | + |
| 86 | +Finally, click on the **"Get New Access Token"**. |
| 87 | + |
| 88 | + |
| 89 | + |
| 90 | +You now have an access token that has an expiry of `300` seconds, and we can make requests to the API. |
| 91 | + |
| 92 | +You can for example try |
| 93 | +- **GET** | `https://api2.arduino.cc/iot/v2/dashboards` |
| 94 | + |
| 95 | +Which should look like this in the Postman UI: |
| 96 | + |
| 97 | + |
| 98 | + |
| 99 | +***Note that your access token expires after `300` seconds. After that, you will need to re-generate it by clicking the button again.*** |
| 100 | + |
| 101 | +## JavaScript (node.js) |
| 102 | + |
| 103 | +**Requirements:** |
| 104 | + |
| 105 | +- [node.js](https://nodejs.org/en/) |
| 106 | +- [@arduino/arduino-iot-client](https://www.npmjs.com/package/@arduino/arduino-iot-client) |
| 107 | + |
| 108 | +To install the `arduino-iot-client`, run the following command: |
| 109 | + |
| 110 | +``` |
| 111 | +npm install @arduino/arduino-iot-client |
| 112 | +``` |
| 113 | + |
| 114 | +After it is installed, you can create a `.js` file, e.g. `main.js` that you can write your script in. |
| 115 | + |
| 116 | +First, we need to authenticate with the Arduino Cloud API: |
| 117 | + |
| 118 | +```js |
| 119 | +var IotApi = require('@arduino/arduino-iot-client'); |
| 120 | +var rp = require('request-promise'); |
| 121 | + |
| 122 | +async function getToken() { |
| 123 | + var options = { |
| 124 | + method: 'POST', |
| 125 | + url: 'https://api2.arduino.cc/iot/v1/clients/token', |
| 126 | + headers: { 'content-type': 'application/x-www-form-urlencoded' }, |
| 127 | + json: true, |
| 128 | + form: { |
| 129 | + grant_type: 'client_credentials', |
| 130 | + client_id: 'YOUR_CLIENT_ID', |
| 131 | + client_secret: 'YOUR_CLIENT_SECRET', |
| 132 | + audience: 'https://api2.arduino.cc/iot' |
| 133 | + } |
| 134 | + }; |
| 135 | + |
| 136 | + try { |
| 137 | + const response = await rp(options); |
| 138 | + return response['access_token']; |
| 139 | + } |
| 140 | + catch (error) { |
| 141 | + console.error("Failed getting an access token: " + error) |
| 142 | + } |
| 143 | +} |
| 144 | +``` |
| 145 | + |
| 146 | +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**. |
| 147 | + |
| 148 | +```js |
| 149 | +async function listProperties() { |
| 150 | + var client = IotApi.ApiClient.instance; |
| 151 | + // Configure OAuth2 access token for authorization: oauth2 |
| 152 | + var oauth2 = client.authentications['oauth2']; |
| 153 | + oauth2.accessToken = await getToken(); |
| 154 | + |
| 155 | + var api = new IotApi.PropertiesV2Api(client) |
| 156 | + var id = "XXX"; // {String} The id of the thing |
| 157 | + |
| 158 | + var opts = { |
| 159 | + 'showDeleted': true // {Boolean} If true, shows the soft deleted properties |
| 160 | + }; |
| 161 | + api.propertiesV2List(id, opts).then(function(data) { |
| 162 | + console.log(data); |
| 163 | + }); |
| 164 | +} |
| 165 | + |
| 166 | +listProperties(); |
| 167 | +``` |
| 168 | + |
| 169 | +And to run the script, you can simply use: |
| 170 | + |
| 171 | +``` |
| 172 | +node main.js |
| 173 | +``` |
| 174 | + |
| 175 | +In your terminal, you will now receive a response akin to: |
| 176 | + |
| 177 | +``` |
| 178 | +[ |
| 179 | + ArduinoProperty { |
| 180 | + href: '/iot/v1/things/<thingid>/properties/<propertyid>', |
| 181 | + id: '<propertyid>', |
| 182 | + name: 'Prop_1', |
| 183 | + permission: 'READ_WRITE', |
| 184 | + thing_id: '<thingid>', |
| 185 | + type: 'INT', |
| 186 | + update_strategy: 'ON_CHANGE', |
| 187 | + created_at: 2022-09-07T12:42:22.593Z, |
| 188 | + last_value: 'N/A', |
| 189 | + persist: true, |
| 190 | + tag: 2, |
| 191 | + thing_name: 'Arduino_Thing', |
| 192 | + updated_at: 2022-09-07T12:42:22.593Z, |
| 193 | + variable_name: 'Prop_1' |
| 194 | + } |
| 195 | +] |
| 196 | +``` |
| 197 | + |
| 198 | +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: |
| 199 | + |
| 200 | +```js |
| 201 | +console.log(data[0].last_value); |
| 202 | +``` |
| 203 | + |
| 204 | +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 IoT Cloud API](https://www.arduino.cc/reference/en/iot/api/). |
| 205 | + |
| 206 | +## Python |
| 207 | + |
| 208 | +**Requirements:** |
| 209 | + |
| 210 | +- [Python 3.7+](https://www.python.org/downloads/) |
| 211 | +- [arduino-iot-client](https://pypi.org/project/arduino-iot-client/) (python) |
| 212 | + |
| 213 | +To install, use the following command: |
| 214 | + |
| 215 | +``` |
| 216 | +pip install arduino-iot-client |
| 217 | +``` |
| 218 | + |
| 219 | +To authenticate, you will need to have the `requests-oauthlib` installed: |
| 220 | + |
| 221 | +``` |
| 222 | +pip install requests-oauthlib |
| 223 | +``` |
| 224 | + |
| 225 | +To generate an **access token** use the following script: |
| 226 | + |
| 227 | +```py |
| 228 | +from oauthlib.oauth2 import BackendApplicationClient |
| 229 | +from requests_oauthlib import OAuth2Session |
| 230 | + |
| 231 | +from os import access |
| 232 | +import iot_api_client as iot |
| 233 | +from iot_api_client.rest import ApiException |
| 234 | +from iot_api_client.configuration import Configuration |
| 235 | + |
| 236 | +# Get your token |
| 237 | + |
| 238 | +oauth_client = BackendApplicationClient(client_id="YOUR_CLIENT_ID") |
| 239 | +token_url = "https://api2.arduino.cc/iot/v1/clients/token" |
| 240 | + |
| 241 | +oauth = OAuth2Session(client=oauth_client) |
| 242 | +token = oauth.fetch_token( |
| 243 | + token_url=token_url, |
| 244 | + client_id="YOUR_CLIENT_ID", |
| 245 | + client_secret="YOUR_CLIENT_SECRET", |
| 246 | + include_client_id=True, |
| 247 | + audience="https://api2.arduino.cc/iot", |
| 248 | +) |
| 249 | + |
| 250 | +# store access token in access_token variable |
| 251 | +access_token = token.get("access_token") |
| 252 | +``` |
| 253 | + |
| 254 | +Then, to authenticate with the generated token, use: |
| 255 | + |
| 256 | +```py |
| 257 | +client_config = Configuration(host="https://api2.arduino.cc/iot") |
| 258 | +client_config.access_token = access_token |
| 259 | +client = iot.ApiClient(client_config) |
| 260 | +``` |
| 261 | + |
| 262 | +And to for example, list out properties attached to a Thing: |
| 263 | + |
| 264 | +```py |
| 265 | +thing_id = "YOUR_THING_ID" |
| 266 | + |
| 267 | +# as an example, interact with the properties API |
| 268 | +api = iot.PropertiesV2Api(client) |
| 269 | + |
| 270 | +try: |
| 271 | + resp = api.properties_v2_list(thing_id) |
| 272 | + print(resp) |
| 273 | +except ApiException as e: |
| 274 | + print("Got an exception: {}".format(e)) |
| 275 | +``` |
| 276 | + |
| 277 | +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: |
| 278 | + |
| 279 | +``` |
| 280 | +print(resp[0].last_value) |
| 281 | +``` |
| 282 | + |
| 283 | +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. |
| 284 | + |
| 285 | +```py |
| 286 | +from oauthlib.oauth2 import BackendApplicationClient |
| 287 | +from requests_oauthlib import OAuth2Session |
| 288 | + |
| 289 | +from os import access |
| 290 | +import iot_api_client as iot |
| 291 | +from iot_api_client.rest import ApiException |
| 292 | +from iot_api_client.configuration import Configuration |
| 293 | + |
| 294 | +# Get your token |
| 295 | + |
| 296 | +oauth_client = BackendApplicationClient(client_id="YOUR_CLIENT_ID") |
| 297 | +token_url = "https://api2.arduino.cc/iot/v1/clients/token" |
| 298 | + |
| 299 | +oauth = OAuth2Session(client=oauth_client) |
| 300 | +token = oauth.fetch_token( |
| 301 | + token_url=token_url, |
| 302 | + client_id="YOUR_CLIENT_ID", |
| 303 | + client_secret="YOUR_CLIENT_SECRET", |
| 304 | + include_client_id=True, |
| 305 | + audience="https://api2.arduino.cc/iot", |
| 306 | +) |
| 307 | + |
| 308 | +# store access token in access_token variable |
| 309 | +access_token = token.get("access_token") |
| 310 | + |
| 311 | +# configure and instance the API client with our access_token |
| 312 | + |
| 313 | +client_config = Configuration(host="https://api2.arduino.cc/iot") |
| 314 | +client_config.access_token = access_token |
| 315 | +client = iot.ApiClient(client_config) |
| 316 | +thing_id = "YOUR_THING_ID" |
| 317 | + |
| 318 | +# as an example, interact with the properties API |
| 319 | +api = iot.PropertiesV2Api(client) |
| 320 | + |
| 321 | +try: |
| 322 | + resp = api.properties_v2_list(thing_id) |
| 323 | + print(resp) |
| 324 | +except ApiException as e: |
| 325 | + print("Got an exception: {}".format(e)) |
| 326 | +``` |
| 327 | + |
| 328 | +## Golang |
| 329 | + |
| 330 | +To access the Arduino Cloud API via the Go client, you can refer to the [arduino/iot-client-go](https://github.com/arduino/iot-client-go) client on GitHub. |
| 331 | + |
| 332 | +Below is an example that will authenticate with the API and list out all your devices. |
| 333 | + |
| 334 | +```go |
| 335 | +package main |
| 336 | + |
| 337 | +import ( |
| 338 | + "context" |
| 339 | + "log" |
| 340 | + "net/url" |
| 341 | + |
| 342 | + iot "github.com/arduino/iot-client-go" |
| 343 | + cc "golang.org/x/oauth2/clientcredentials" |
| 344 | +) |
| 345 | + |
| 346 | +var ( |
| 347 | + clientID = "your_client_id" |
| 348 | + clientSecret = "your_client_secret" |
| 349 | +) |
| 350 | + |
| 351 | +func main() { |
| 352 | + // We need to pass the additional "audience" var to request an access token |
| 353 | + additionalValues := url.Values{} |
| 354 | + additionalValues.Add("audience", "https://api2.arduino.cc/iot") |
| 355 | + // Set up OAuth2 configuration |
| 356 | + config := cc.Config{ |
| 357 | + ClientID: clientID, |
| 358 | + ClientSecret: clientSecret, |
| 359 | + TokenURL: "https://api2.arduino.cc/iot/v1/clients/token", |
| 360 | + EndpointParams: additionalValues, |
| 361 | + } |
| 362 | + // Get the access token in exchange of client_id and client_secret |
| 363 | + tok, err := config.Token(context.Background()) |
| 364 | + if err != nil { |
| 365 | + log.Fatalf("Error retrieving access token, %v", err) |
| 366 | + } |
| 367 | + // Confirm we got the token and print expiration time |
| 368 | + log.Printf("Got an access token, will expire on %s", tok.Expiry) |
| 369 | + |
| 370 | + // We use the token to create a context that will be passed to any API call |
| 371 | + ctx := context.WithValue(context.Background(), iot.ContextAccessToken, tok.AccessToken) |
| 372 | + |
| 373 | + // Create an instance of the iot-api Go client, we pass an empty config |
| 374 | + // because defaults are ok |
| 375 | + client := iot.NewAPIClient(iot.NewConfiguration()) |
| 376 | + |
| 377 | + // Get the list of devices for the current user |
| 378 | + devices, _, err := client.DevicesV2Api.DevicesV2List(ctx, nil) |
| 379 | + if err != nil { |
| 380 | + log.Fatalf("Error getting devices, %v", err) |
| 381 | + } |
| 382 | + |
| 383 | + // Print a meaningful message if the api call succeeded |
| 384 | + if len(devices) == 0 { |
| 385 | + log.Printf("No device found") |
| 386 | + } else { |
| 387 | + for _, d := range devices { |
| 388 | + log.Printf("Device found: %s", d.Name) |
| 389 | + } |
| 390 | + } |
| 391 | +} |
| 392 | +``` |
| 393 | + |
| 394 | +See the full example on [GitHub](https://github.com/arduino/iot-client-go/tree/master/example). |
| 395 | + |
| 396 | +## Summary |
| 397 | + |
| 398 | +This document covers the overall usage of the [Arduino IoT Cloud API](https://www.arduino.cc/reference/en/iot/api/), and how to use it with different clients (JavaScript, Python, Golang). |
| 399 | + |
0 commit comments