How to use tsNetGetSync to retrieve data from a web site
This lesson is designed to show how the tsNet external can be used to retrieve data from a website. The example code in this lesson retrieves a To Do list and displays the number of items and the list.
To achieve this goal, we use the tsNetGetSync function from the tsNet external library.
In this example we are using a test REST API available from https://jsonplaceholder.typicode.com
Lay out the Stack
Create a new stack then drag a button and a field onto it.
Set the name of the field to "Output".
Save this stack.
Create the Script
Edit the script of the button that you placed on the stack by right clicking on the button and selecting "edit script".
Add the following code.
on mouseUp pButtonNumber -- The following line is the call to tsNetGetSync put tsNetGetSync("https://jsonplaceholder.typicode.com/todos", tHeaders, tRecvHeaders, tResult, tBytes) into tData -- tResult will be 200 (the HTTP response code for a successful transfer) if -- tsNetGetSync was able to retrieve the data -- If this is not the case, we will inform the user if tResult is not 200 then answer "Could not retrieve data" else -- The retrieved data is in JSON format, convert to a normal LiveCode array put JSONtoArray(tData) into tArray -- Display the number of items and the list put "There are" && the number of elements in tArray && "items." & return & return into field "Output" repeat with x = 1 to the number of elements in tArray put "Item" && x & ":" && tArray[x]["title"] & tab & tArray[x]["completed"] & return after field "Output" end repeat end if end mouseUp
The code above shows a very simple example of how to use tsNetGetSync to retrieve data. There are additional parameters that can be used with the tsNetGetSync function that allow more specific configuration and provide more information on the response that is returned from the web server. However, as can be seen above, these additional parameters are often not necessary when retrieving data from a website.
In particular, the tHeaders variable can be used to control what HTTP headers are sent with the HTTP GET request. The tRecvHeaders variable contains the HTTP headers returned from the web server and the tBytes variable stores the number of bytes of data that has been returned.
More information about these additional parameters can be found in the LiveCode dictionary.
Switch to Run mode and click the button.