Web Services SmartApps Tutorial
This example illustrates how a SmartApp can expose RESTful endpoints, and how a third party application can integrate with the SmartApp using OAuth.
There are two components to this example:
Web Services SmartApp
A Web Services SmartApp is simply a SmartApp that can be called through REST requests.
This example uses a simple Sinatra app to illustrate the process of obtaining an access token to make REST calls to the SmartApp.
TRY IT OUT
- In the SmartThings IDE, create a new SmartApp with the contents of web-services-smartapp-groovy. Make sure to enable OAuth from the App Settings, and note the Client ID and Client Secret.
- Publish the SmartApp.
Simulator and cURL
- Install the SmartApp in the simulator, and pick some switches.
- Copy the API token and API URL from the simulator.
- Open a terminal command prompt.
- Using curl, issue a GET request to the
/switchesendpoint, using the API URL and token:
curl -H "Authorization: Bearer <API-TOKEN>" -X GET "<API-ENDPOINT>/switches"
- Send the on or off command to the configured switches, using the
curl -H "Authorization: Bearer <API-TOKEN>" -X PUT "<API-ENDPOINT>/switches/on"
- When you are done experimenting, uninstall the SmartApp from the simulator.
- Make sure you have Ruby and Bundler installed. This example has been tested with Ruby 2.2.1 and Bundler 1.10.4.
- In a terminal, set the environment variables
ST_CLIENT_SECRETwith the ID and secret for the SmartApp. Alternatively, replace the
CLIENT_SECRETvariables in the application with your actual client ID and secret.
- Run bundler:
- Start the app:
- Open http://localhost:4567 in your web browser.
- Click on the "Authorize with SmartThings" link. Enter your SmartThings username and password if not already logged in.
- Select a Location from the dropdown, select one or more devices, and click Authorize.
- The app will simply redirect to a page showing the result of the web request to the SmartApp endpoint.
- When you publish a SmartApp for yourself, it is published only to the server that you are publishing from. It cannot be installed by users associated with a different server, without being published there as well.
- Additional servers will be added as needed (don't count on just two, or three, or any fixed number of servers).
- For SmartApps to be globally available, and replicated on additional servers as they are created (with the same Client ID and secret), they should be submitted to SmartThings for publication.
- Regardless of where the SmartApp is installed,
https://graph.api.smartthings.com/should be used to retrieve the access code, token, and endpoints for the SmartApp. The JSON returned from getting the SmartApp endpoints will contain the
base_url, which will be specific to the installation location of the SmartApp. Refer to
server.rbto see this in practice.
For more information, see the Web Services Docs.