All of the information I used to communicate with the SmartThings REST API came from the documentation here. If you are having trouble following my steps, please take a look at that documentation, since maybe something has changed.(http://docs.smartthings.com/en/latest/smartapp-web-services-developers-guide/authorization.html)
According to the documentation, the process of communicating with the API is:
- Request an authorization code.
- Use the code to request an access token.
- Get the endpoint URI for the SmartApp.
- Make REST calls to the SmartApp using the endpoint URI.
Today I’ll be focusing on steps 1 and 2. I just want to get access to the API now, and I’ll start communicating later.
SmartThings uses OAuth to authenticate any external systems which contact it. Whenever we communicate with SmartThings, we need to provide a token which will be used to verify our authorization.
To obtain the authorization code, I opened a web page and navigated to https://graph.api.smartthings.com/oauth/authorize?response_type=code&client_id=YOUR-SMARTAPP-CLIENT-ID&scope=app&redirect_uri=YOUR-SERVER-URI
Before actually going to that link I needed to replace a couple things. The section YOUR-SMARTAPP-CLIENT-ID”\ with the client id is replaced with the client id of the app I created in the last blog. Also YOUR-SERVER-URI needed to be replaced with the redirect uri that was specified in the smart app we created.
With this url, I was taken to a SmartThings page where I needed to give authorization. After selecting my location, I clicked on the Authorize button. My browser was then redirected to my redirect URI, and the authorization code was included in the URL: http://localhost:4567/oauth/callback?code=NGJP1p. We’ll have to be quick with it though, it expires in 24 hours.
Next I took the authorization code and asked for a token. To do that I sent a POST call to https://graph.api.smartthings.com/oauth/token?grant_type=authorization_code&code=YOUR_CODE&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&redirect_uri=YOUR_REDIRECT_URI
Here we needed to replace YOUR_CODE with the authorization code we just received, YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with the values which were generated for your SmartApp, and the YOUR_REDIRECT_URI that you set in your SmartApp.
When I made the call, I got a response like this:
Here we have the token in the access_token field. The expires_in value is in seconds, which tells us that the access token will expire in 50 years.
Now with that token, I can start making rest calls to actually read the sensor data.