Category: Data
Requests data from the internet and executes code when the request is complete.
Your apps are not limited to data they collect and generate. Many web sites make data available for your apps to access. startWebRequest() should be used with the URL of web services that are designed to be called in that way.
The callback function will be passed three parameters:
Example: Print the name and population of every country
startWebRequest("https://restcountries.eu/rest/v2/all?fields=name;population", function(status, type, content) { var jsonContent = JSON.parse(content); for(var i = 0; i< jsonContent.length; i++){ console.log(jsonContent[i]); } });
Example: This simple example lets users type in a number and returns a random fun fact about the number.
textInput("numberInput", ""); setProperty("numberInput","placeholder","Type a number"); textLabel("factOutput", ""); button("newInput", "Get fact!"); onEvent("numberInput", "change", function() { var number = getNumber("numberInput"); var url = "http://numbersapi.com/" + number; startWebRequest(url, function(status, type, content) { if(status == 200) { setText("factOutput", content); } }); });
startWebRequest(url, function(status, type, content) { Code to execute });
Name | Type | Required? | Description |
---|---|---|---|
url | string | Yes | The web address of a service that returns data. |
callback | function | Yes | A function that is asynchronously called when the call to startWebRequest() is finished. Three paramters are passed to this function. |
When startWebRequest() is finished executing, the callback function is automatically called.
For security reasons, only URLs with certain hostnames can be accessed using startWebRequest. Currently, the hostname must end in one of the following:
Want to use a URL that's not currently allowed? Let us know at support@code.org
Found a bug in the documentation? Let us know at documentation@code.org
Found a bug in the documentation? Let us know at documentation@code.org