Skip to content

Script Examples

API Request

Download ezUI File

In this example, we will make a API request to an external server, and populate our UI with the data we received. For this example we will use Open Weather Map to retrieve real-time weather data for a city.

API Request}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const appid = 'fe72...8f37' // Get your app ID from Open Weather Map: https://home.openweathermap.org/api_keys

search.onChange = triggerUpdate;

let timeout;

// We create a debounce function so that API is only requested when the user has finished typing the city name
function triggerUpdate() {
  if (timeout)
    clearTimeout(timeout);

  timeout = setTimeout(getWeatherData, 500);
}

async function getWeatherData() {
  timeout = 0;

  try {
    // We will use the asynchrons request.get function to make the request to the API
    const { body } = await request.get(`https://api.openweathermap.org/data/2.5/weather?q=${search.value}&appid=${appid}&units=Metric`);
    const temp = body.main.temp;
    let wind = body.wind.speed;

    // Here we update the values of the UI components, with the values we received from the API request
    txt_city.value = body.name;
    txt_temp.value = `${Math.round(temp)}°`;
    txt_wind.value = `${Math.round(wind)} Kmh`;

    // We use the Javascript Date() function to get the current day.
    const currentDate = new Date();
    txt_day.value = currentDate.toLocaleString('en-US', { weekday: 'long' });

  } catch {
    // If we did not manage to make the API request, we can handle the error here.
    console.error("CANNOT CONNECT TO API");
  }
}