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
End Function

Function Button1_onclick()
  Dim city = encodeURIComponent(TextBox1.value)
  loadScript("" & 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 = ""
  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 (“?”):

Paste this into a browser and you will get:

"description":"few clouds","icon":"02n"}],"base":"cmc stations",

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.