|
| 1 | +--- |
| 2 | +title: 'Arduino Cloud API & SDK' |
| 3 | +difficulty: advanced |
| 4 | +description: 'Learn how to authenticate with the Arduino IoT Cloud API to make requests using HTTP Client, JavaScript and Python.' |
| 5 | +tags: |
| 6 | + - IoT Cloud API |
| 7 | + - JavaScript |
| 8 | + - Python |
| 9 | + - node.js |
| 10 | + - Golang |
| 11 | +author: 'Karl Söderby' |
| 12 | +--- |
| 13 | + |
| 14 | +The [Arduino IoT Cloud 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 | +## Postman |
| 58 | + |
| 59 | +[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**. |
| 60 | + |
| 61 | +First, to authenticate, click on the **"Import > Raw Text"**, then add the following commands, replacing `YOUR_CLIENT_ID` and `YOUR_SECRET_ID` with your credentials. |
| 62 | + |
| 63 | +``` |
| 64 | +curl --request POST \ |
| 65 | + --url 'https://api2.arduino.cc/iot/v1/clients/token' \ |
| 66 | + --header 'content-type: application/x-www-form-urlencoded' \ |
| 67 | + --data 'grant_type=client_credentials' \ |
| 68 | + --data 'client_id=YOUR_CLIENT_ID' \ |
| 69 | + --data 'client_secret=YOUR_SECRET_ID' \ |
| 70 | + --data 'audience=https://api2.arduino.cc/iot' |
| 71 | +``` |
| 72 | + |
| 73 | +This will import all necessary configurations. Click on **"Send"** and you will receive an access token (note that it has an expiry time, 300 seconds). Copy it. |
| 74 | + |
| 75 | +We can now create a new request to e.g. list out properties by first importing the following command (note that you need to replace `{id}` with a Thing ID). |
| 76 | + |
| 77 | +``` |
| 78 | +curl -X GET "https://api2.arduino.cc/iot/v2/things/{id}/properties |
| 79 | +``` |
| 80 | + |
| 81 | +Then, in the **Authorization** tab, select **"Type > OAuth 2.0"** and paste the access token in the field. |
| 82 | + |
| 83 | + |
| 84 | + |
| 85 | +## JavaScript (node.js) |
| 86 | + |
| 87 | +**Requirements:** |
| 88 | + |
| 89 | +- [node.js](https://nodejs.org/en/) |
| 90 | +- [@arduino/arduino-iot-client](https://www.npmjs.com/package/@arduino/arduino-iot-client) |
| 91 | + |
| 92 | +To install the `arduino-iot-client`, run the following command: |
| 93 | + |
| 94 | +``` |
| 95 | +npm install @arduino/arduino-iot-client |
| 96 | +``` |
| 97 | + |
| 98 | +After it is installed, you can create a `.js` file, e.g. `main.js` that you can write your script in. |
| 99 | + |
| 100 | +First, we need to authenticate with the Arduino Cloud API: |
| 101 | + |
| 102 | +```js |
| 103 | +var IotApi = require('@arduino/arduino-iot-client'); |
| 104 | +var rp = require('request-promise'); |
| 105 | + |
| 106 | +async function getToken() { |
| 107 | + var options = { |
| 108 | + method: 'POST', |
| 109 | + url: 'https://api2.arduino.cc/iot/v1/clients/token', |
| 110 | + headers: { 'content-type': 'application/x-www-form-urlencoded' }, |
| 111 | + json: true, |
| 112 | + form: { |
| 113 | + grant_type: 'client_credentials', |
| 114 | + client_id: 'YOUR_CLIENT_ID', |
| 115 | + client_secret: 'YOUR_CLIENT_SECRET', |
| 116 | + audience: 'https://api2.arduino.cc/iot' |
| 117 | + } |
| 118 | + }; |
| 119 | + |
| 120 | + try { |
| 121 | + const response = await rp(options); |
| 122 | + return response['access_token']; |
| 123 | + } |
| 124 | + catch (error) { |
| 125 | + console.error("Failed getting an access token: " + error) |
| 126 | + } |
| 127 | +} |
| 128 | +``` |
| 129 | + |
| 130 | +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**. |
| 131 | + |
| 132 | +```js |
| 133 | +async function listProperties() { |
| 134 | + var client = IotApi.ApiClient.instance; |
| 135 | + // Configure OAuth2 access token for authorization: oauth2 |
| 136 | + var oauth2 = client.authentications['oauth2']; |
| 137 | + oauth2.accessToken = await getToken(); |
| 138 | + |
| 139 | + var api = new IotApi.PropertiesV2Api(client) |
| 140 | + var id = "XXX"; // {String} The id of the thing |
| 141 | + |
| 142 | + var opts = { |
| 143 | + 'showDeleted': true // {Boolean} If true, shows the soft deleted properties |
| 144 | + }; |
| 145 | + api.propertiesV2List(id, opts).then(function(data) { |
| 146 | + console.log(data); |
| 147 | + }); |
| 148 | +} |
| 149 | + |
| 150 | +listProperties(); |
| 151 | +``` |
| 152 | + |
| 153 | +And to run the script, you can simply use: |
| 154 | + |
| 155 | +``` |
| 156 | +node main.js |
| 157 | +``` |
| 158 | + |
| 159 | +In your terminal, you will now receive a response akin to: |
| 160 | + |
| 161 | +``` |
| 162 | +[ |
| 163 | + ArduinoProperty { |
| 164 | + href: '/iot/v1/things/<thingid>/properties/<propertyid>', |
| 165 | + id: '<propertyid>', |
| 166 | + name: 'Prop_1', |
| 167 | + permission: 'READ_WRITE', |
| 168 | + thing_id: '<thingid>', |
| 169 | + type: 'INT', |
| 170 | + update_strategy: 'ON_CHANGE', |
| 171 | + created_at: 2022-09-07T12:42:22.593Z, |
| 172 | + last_value: 'N/A', |
| 173 | + persist: true, |
| 174 | + tag: 2, |
| 175 | + thing_name: 'Arduino_Thing', |
| 176 | + updated_at: 2022-09-07T12:42:22.593Z, |
| 177 | + variable_name: 'Prop_1' |
| 178 | + } |
| 179 | +] |
| 180 | +``` |
| 181 | + |
| 182 | +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: |
| 183 | + |
| 184 | +```js |
| 185 | +console.log(data[0].last_value); |
| 186 | +``` |
| 187 | + |
| 188 | +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/). |
| 189 | + |
| 190 | +## Python |
| 191 | + |
| 192 | +**Requirements:** |
| 193 | + |
| 194 | +- [Python 3.7+](https://www.python.org/downloads/) |
| 195 | +- [arduino-iot-client](https://pypi.org/project/arduino-iot-client/) (python) |
| 196 | + |
| 197 | +To install, use the following command: |
| 198 | + |
| 199 | +``` |
| 200 | +pip install arduino-iot-client |
| 201 | +``` |
| 202 | + |
| 203 | +To authenticate, you will need to have the `requests-oauthlib` installed: |
| 204 | + |
| 205 | +``` |
| 206 | +pip install requests-oauthlib |
| 207 | +``` |
| 208 | + |
| 209 | +To generate an **access token** use the following script: |
| 210 | + |
| 211 | +```py |
| 212 | +from oauthlib.oauth2 import BackendApplicationClient |
| 213 | +from requests_oauthlib import OAuth2Session |
| 214 | + |
| 215 | +from os import access |
| 216 | +import iot_api_client as iot |
| 217 | +from iot_api_client.rest import ApiException |
| 218 | +from iot_api_client.configuration import Configuration |
| 219 | + |
| 220 | +# Get your token |
| 221 | + |
| 222 | +oauth_client = BackendApplicationClient(client_id="YOUR_CLIENT_ID") |
| 223 | +token_url = "https://api2.arduino.cc/iot/v1/clients/token" |
| 224 | + |
| 225 | +oauth = OAuth2Session(client=oauth_client) |
| 226 | +token = oauth.fetch_token( |
| 227 | + token_url=token_url, |
| 228 | + client_id="YOUR_CLIENT_ID", |
| 229 | + client_secret="YOUR_CLIENT_SECRET", |
| 230 | + include_client_id=True, |
| 231 | + audience="https://api2.arduino.cc/iot", |
| 232 | +) |
| 233 | + |
| 234 | +# store access token in access_token variable |
| 235 | +access_token = token.get("access_token") |
| 236 | +``` |
| 237 | + |
| 238 | +Then, to authenticate with the generated token, use: |
| 239 | + |
| 240 | +```py |
| 241 | +client_config = Configuration(host="https://api2.arduino.cc/iot") |
| 242 | +client_config.access_token = access_token |
| 243 | +client = iot.ApiClient(client_config) |
| 244 | +``` |
| 245 | + |
| 246 | +And to for example, list out properties attached to a Thing: |
| 247 | + |
| 248 | +```py |
| 249 | +thing_id = "YOUR_THING_ID" |
| 250 | + |
| 251 | +# as an example, interact with the properties API |
| 252 | +api = iot.PropertiesV2Api(client) |
| 253 | + |
| 254 | +try: |
| 255 | + resp = api.properties_v2_list(thing_id) |
| 256 | + print(resp) |
| 257 | +except ApiException as e: |
| 258 | + print("Got an exception: {}".format(e)) |
| 259 | +``` |
| 260 | + |
| 261 | +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: |
| 262 | + |
| 263 | +``` |
| 264 | +print(resp[0].last_value) |
| 265 | +``` |
| 266 | + |
| 267 | +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. |
| 268 | + |
| 269 | +```py |
| 270 | +from oauthlib.oauth2 import BackendApplicationClient |
| 271 | +from requests_oauthlib import OAuth2Session |
| 272 | + |
| 273 | +from os import access |
| 274 | +import iot_api_client as iot |
| 275 | +from iot_api_client.rest import ApiException |
| 276 | +from iot_api_client.configuration import Configuration |
| 277 | + |
| 278 | +# Get your token |
| 279 | + |
| 280 | +oauth_client = BackendApplicationClient(client_id="YOUR_CLIENT_ID") |
| 281 | +token_url = "https://api2.arduino.cc/iot/v1/clients/token" |
| 282 | + |
| 283 | +oauth = OAuth2Session(client=oauth_client) |
| 284 | +token = oauth.fetch_token( |
| 285 | + token_url=token_url, |
| 286 | + client_id="YOUR_CLIENT_ID", |
| 287 | + client_secret="YOUR_CLIENT_SECRET", |
| 288 | + include_client_id=True, |
| 289 | + audience="https://api2.arduino.cc/iot", |
| 290 | +) |
| 291 | + |
| 292 | +# store access token in access_token variable |
| 293 | +access_token = token.get("access_token") |
| 294 | + |
| 295 | +# configure and instance the API client with our access_token |
| 296 | + |
| 297 | +client_config = Configuration(host="https://api2.arduino.cc/iot") |
| 298 | +client_config.access_token = access_token |
| 299 | +client = iot.ApiClient(client_config) |
| 300 | +thing_id = "YOUR_THING_ID" |
| 301 | + |
| 302 | +# as an example, interact with the properties API |
| 303 | +api = iot.PropertiesV2Api(client) |
| 304 | + |
| 305 | +try: |
| 306 | + resp = api.properties_v2_list(thing_id) |
| 307 | + print(resp) |
| 308 | +except ApiException as e: |
| 309 | + print("Got an exception: {}".format(e)) |
| 310 | +``` |
| 311 | + |
| 312 | +## Golang |
| 313 | + |
| 314 | +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. |
| 315 | + |
| 316 | +Below is an example that will authenticate with the API and list out all your devices. |
| 317 | + |
| 318 | +```go |
| 319 | +package main |
| 320 | + |
| 321 | +import ( |
| 322 | + "context" |
| 323 | + "log" |
| 324 | + "net/url" |
| 325 | + |
| 326 | + iot "github.com/arduino/iot-client-go" |
| 327 | + cc "golang.org/x/oauth2/clientcredentials" |
| 328 | +) |
| 329 | + |
| 330 | +var ( |
| 331 | + clientID = "your_client_id" |
| 332 | + clientSecret = "your_client_secret" |
| 333 | +) |
| 334 | + |
| 335 | +func main() { |
| 336 | + // We need to pass the additional "audience" var to request an access token |
| 337 | + additionalValues := url.Values{} |
| 338 | + additionalValues.Add("audience", "https://api2.arduino.cc/iot") |
| 339 | + // Set up OAuth2 configuration |
| 340 | + config := cc.Config{ |
| 341 | + ClientID: clientID, |
| 342 | + ClientSecret: clientSecret, |
| 343 | + TokenURL: "https://api2.arduino.cc/iot/v1/clients/token", |
| 344 | + EndpointParams: additionalValues, |
| 345 | + } |
| 346 | + // Get the access token in exchange of client_id and client_secret |
| 347 | + tok, err := config.Token(context.Background()) |
| 348 | + if err != nil { |
| 349 | + log.Fatalf("Error retrieving access token, %v", err) |
| 350 | + } |
| 351 | + // Confirm we got the token and print expiration time |
| 352 | + log.Printf("Got an access token, will expire on %s", tok.Expiry) |
| 353 | + |
| 354 | + // We use the token to create a context that will be passed to any API call |
| 355 | + ctx := context.WithValue(context.Background(), iot.ContextAccessToken, tok.AccessToken) |
| 356 | + |
| 357 | + // Create an instance of the iot-api Go client, we pass an empty config |
| 358 | + // because defaults are ok |
| 359 | + client := iot.NewAPIClient(iot.NewConfiguration()) |
| 360 | + |
| 361 | + // Get the list of devices for the current user |
| 362 | + devices, _, err := client.DevicesV2Api.DevicesV2List(ctx, nil) |
| 363 | + if err != nil { |
| 364 | + log.Fatalf("Error getting devices, %v", err) |
| 365 | + } |
| 366 | + |
| 367 | + // Print a meaningful message if the api call succeeded |
| 368 | + if len(devices) == 0 { |
| 369 | + log.Printf("No device found") |
| 370 | + } else { |
| 371 | + for _, d := range devices { |
| 372 | + log.Printf("Device found: %s", d.Name) |
| 373 | + } |
| 374 | + } |
| 375 | +} |
| 376 | +``` |
| 377 | + |
| 378 | +See the full example on [GitHub](https://github.com/arduino/iot-client-go/tree/master/example). |
| 379 | + |
| 380 | +## Summary |
| 381 | + |
| 382 | +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). |
| 383 | + |
0 commit comments