AppStudio 4: GetJSON() makes Web Services Easy!

AppStudio 4 has a number of features to make your life easier. We looked for ways to make code easier to write and understand.

First up is GetJSON. This function is used to get information from a web service. There are many web services available: making use of these is a great way to connect your app to the outside world. The Programmable Web lists over 10,000 web API’s you can use. APIs exist for almost everything: sports, games, the stock market, weather, inventory checks at retailers, Yahoo, Twitter, FaceBook and Google.

The typical call has the URL of the web service, the parameter string to send to it, and the function in your program to call when the results come back. Here is how it looked before AppStudio 4:

'Obsolete code - before AppStudio 4
Function loadScript(URL)
  Dim head, script
  head=document.getElementsByTagName("head")[0]
  script=document.createElement("script")
  script.src=URL
  script.async=True
  head.appendChild(script)
End Function

Function Button1_onclick()
  Dim city = encodeURIComponent(TextBox1.value)
  loadScript("http://api.openweathermap.org/data/2.5/weather?q=" & city & "&callback=weatherData")
End Function

Sub weatherData(data)
  MsgBox "Temperature is " & data.main.temp - 273.15
End Sub

The GetJSON function is much shorter and easier to understand:

'How to do it in AppStudio 4
Function btnLoad_onclick()
  Dim city = "q=" & encodeURIComponent(txtCity.value)
  Dim URL = "http://api.openweathermap.org/data/2.5/weather"
  GetJSON(URL, city, weatherData)
End Function

Sub weatherData(data)
  MsgBox "Temperature is " & data.main.temp - 273.15
End Sub

Testing an API Function

Here’s a trick you can use to test many of these API calls. Combine the URL and the parameters into a single string separated by a question mark (“?”):

http://api.openweathermap.org/data/2.5/weather?q=Toronto

Paste this into a browser and you will get:

{"coord":{"lon":-79.39,"lat":43.65},"sys":
{"message":0.0454,"country":"Canada","sunrise":1396263570,
"sunset":1396309411},"weather":[{"id":801,"main":"Clouds",
"description":"few clouds","icon":"02n"}],"base":"cmc stations",
"main":"temp":273.2,"humidity":54,"pressure":1019,
"temp_min":271.48,"temp_max":275.15},"wind":{"speed":2.3,
"deg":320.501},"rain":{"3h":0},"snow":{"3h":0},"clouds":{"all":12},
"dt":1396259691,"id":6167865,"name":"Toronto","cod":200}

Encoding the Parameters

Certain characters, such as the space key, are not allowed in URL strings. The above example would fail on the city “New York” if it was not encoded. The encodeURIComponent() function converts your parameters into a string which will work perfectly as a URL.