Weight widget (part 3)

Good evening,

Back to the weight widget topic, and more specifically to the request that is made to the Fitbit API. I have struggled a couple of hours tonight with the method makeWebRequest, but finally I managed to get it running with the help from several web resources. I haven’t previously made any WEB requests by using the API so this is learning in progress for me.

Submitting an HTTP GET request from a ConnectIQ app by using makeWebRequest

The connections module of the Connect IQ SDK enables making requests to RESTful Web services. As I wasn’t ready with the OAuth2 yet, I simply wanted to make a couple of experiments with the API without making the whole more complicated with the authentication challenges.

I implemented a simple method submitting a HTTP GET request to a sample URL and check that the response contains an ordinary response code and data. The url points to a URL of the Fake Online REST API for Testing and Prototyping. The headers variable specifies the content type that in the case of the GET request is URL encoded and the file type to be accepted that is JSON.

The options object specifies that the request is sent as GET, the headers are included and the response type is also set.

Finally the actual request is made with the parameters with the callback method as the last one (“onReceive()”).

function makeRequest() {
   var url = "http://jsonplaceholder.typicode.com/posts/1";
   var headers = {
      "Content-Type" => Comm.REQUEST_CONTENT_TYPE_URL_ENCODED,
      "Accept" => "application/json"
   };

   var options = {
      :method => Comm.HTTP_REQUEST_METHOD_GET,
      :headers => headers,
      :responseType => Comm.HTTP_RESPONSE_CONTENT_TYPE_JSON
   };
   Comm.makeWebRequest(url, null, options, method(:onReceive));
}

As result, a response with the JSON is obtained (see the code excerpt below).

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

In the beginning I wasn’t able to obtain a valid response, when not providing the options (even though a valid parameter according to the documentation also could be null). Secondly I was a bit careless when sending requests: if the request is sent to an SSL web site, and the certificate is not OK, the request seems to fail; this is also the case with the example URL above.

Anyway, it was nice to get one additional, even though a minor piece of the app working.  In the next part I’ll proceed with the implementation, and hopefully finally with the OAuth2. 🙂

 

Leave a Reply

Your email address will not be published. Required fields are marked *