startWebRequest
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:
- The status of the request (completed or failed), using HTTP status codes.
- The type of data returned by the service (text, image etc.).
- The data itself in JSON format.
Allowed hostnames
For security reasons, only URLs with certain hostnames can be accessed using startWebRequest. Currently, the hostname must end in one of the following:
Entertainment
- api.themoviedb.org - Data on movies, tv shows, and actors
- swapi.dev - Star Wars data from the films
Finance
- api.coinlayer.com - Exchange rate data for more than 385 cryptocurrencies in real-time
- api.coinmarketcap.com - Market cap rankings, charts, and more
- api.exchangeratesapi.io - Currency exchange rates for 168 world currencies and precious metals
- cryptonator.com - Volume of cryptocurrency exchange rates data covering 300+ cryptocurrencies across 16 exchanges
- moneyconvert.net - Exchange rate data
- quandl.com - Financial, economic and alternative datasets for investing insights
Fun and Games
- api.blizzard.com - Blizzard gaming data
- api.football-data.org - Provides football data and statistics including scores, fixtures, schedules, league tables, etc.
- api.nookipedia.com - Animal Crossing data from the Nookipedia wiki
- api.mojang.com - Minecraft game data
- api.scryfall.com - Magic: The Gathering card data
- api.sportsdata.io - SportsDataIO sports data feeds
- deckofcardsapi.com - Deck of cards API
- openlibrary.org - Open Library APIs
- opentdb.com - Trivia question database
- pokeapi.co - Pokémon data including moves, abilities, types and more
- roblox.com - Roblox game data
- runescape.com - RuneScape game data
- sessionserver.mojang.com - Minecraft session data
- stats.minecraftservers.org - Minecraft server data
- textures.minecraft.net - Minecraft textures data
- thecatapi.com - Cat photos
- thedogapi.com - Dog photos
Local Government
- api.energidataservice.dk - Data about the Danish energy system such as CO2 emissions, consumption and production data
- data.austintexas.gov - Austin, Texas city government data on transportation, health, and more
- data.cityofchicago.org - Chicago, Illinois city government data on administration, education, and more
- data.gv.at - Austrian government data
- rejseplanen.dk - Denmark public transport and traffic data
- theunitedstates.io - United States government data
- Transitchicago.com - Chicago transit train tracking, customer alerts, and more
Math
- numbersapi.com - Interesting facts about numbers and dates
- qrng.anu.edu.au - Random numbers in many formats
- random.org - Random number generation
Places
- api.foursquare.com - Points of interest data
- api.opencagedata.com - Convert coordinates to and from places
- api.openrouteservice.org - Directions, points of interest, and more
- api.zippopotam.us - Postal codes and zip codes for over 60 countries
- distanza.org - Distance, airport, and other geo-related content
- restcountries.com - Country information including language, currency and more
- worldclockapi.com - Time zones around the world
Space
- api.nasa.gov - NASA content including earth satellite imagery, Mars weather and more
- api.open-notify.org - Provides the current ISS location and number of people in space
- api.spacexdata.com - Launch, landpad, crew and other SpaceX data
- data.nasa.gov - Open data sets provided by NASA
- hubblesite.org - Hubble telescope news and more
- images-api.nasa.gov - Images from NASA
Tools and Integrations
- api.duckduckgo.com - Instant Answer API gives you free access to many of our search query answers
- api.github.com - GitHub data
- io.adafruit.com - Adafruit IO data
- maker.ifttt.com - Integrations for DIY projects
- googleapis.com - Allow communication with Google Services
- api.rebrandly.com - Manage short URLs on Rebrandly
Weather and Climate
- api.weather.gov - Weather forecast and alerts from the US National Weather Service
- api.weatherapi.com - Weather and geo data
- api.openweathermap.org - Current weather, historical weather, and forecast data
- api.pegelalarm.at - Current, historical, and forecasted water level data that can be used for flood alerting
- api.waqi.info - Air quality data
- dataservice.accuweather.com - Weather API endpoints
- noaa.gov - Weather and climate data
Words and Texts
- api.datamuse.com - Word-finding query engine
- api.scripture.api.bible - Bible verses and passages
Other
- api.arasaac.org - Symbol set and resources for Augmentive and Alternative Communicación (AAC)
- api.randomuser.me - Provides randomly generated users with details such as name, address, and more
- api.si.edu - Smithsonian Institute Open Access Media
- api.thingspeak.com - Analyze live data streams
- covidtracking.com - Coronavirus statistics
- myschoolapp.com - School specific data
- perenual.com - Botanical data for plants
- pixabay.com - Retrieve photos and videos
- wikipedia.org - Wikipedia content and data
- vpic.nhtsa.dot.gov - Vehicle manufacturer data, VIN decoding, and more
Want to use a URL that's not currently allowed? Let us know at support@code.org
[bug]
Found a bug in the documentation? Let us know at documentation@code.org
[/bug]
Examples
Example: Print the name and population of every country
startWebRequest("https://restcountries.com/v3.1/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].name.common + " - " + jsonContent[i].population);
}
});
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);
}
});
});
Syntax
startWebRequest(url, function(status, type, content) { // Code to execute });
Parameters
Name | Type | Required? | Description |
---|---|---|---|
url | string | The web address of a service that returns data. | |
callback | function | A function that is asynchronously called when the call to startWebRequest() is finished. Three paramters are passed to this function. |
Returns
Tips
- startWebRequest() has a callback because it is accessing an external web service and therefore will not finish immediately.
- The callback function can be inline, or separately defined in your app and called from startWebRequest().
- Do not put functions inside a loop that contain asynchronous code, like startWebRequest(). The loop will not wait for the callback function to complete.
- In order to write code that reads the content of the response returned by the service, we need to know the format of the response. This will often be documented online by the service, in the above case Yahoo Weather.
- You will also need to use the JSON.parse function, which can be used to transform the string of JSON into an object that we can use in our code.
Found a bug in the documentation? Let us know at support@code.org.