Link Search Menu Expand Document

Weather

Get the latest weather from OpenWeather.

To use this example, sign up for a free API key from the OpenWeather website, and insert it in the script where it says {YourApiKey}.

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  const result = await fetch('https://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid={YourApiKey}')
  const resultJson = await result.json()

  let html_content = "<h1>Weather</h1>"

  html_content += `<p>The current weather conditions for ${resultJson.name} are:</p>`
  html_content += `<p>Condition: ${resultJson.weather[0].main}.</p>`
  html_content += `<p>The temperature is: ${resultJson.main.temp} °C.</p>`
  html_content += `<p>The pressure is: ${resultJson.main.pressure} hPa.</p>`
  html_content += `<p>The wind speed is: ${resultJson.wind.speed} meter/sec.</p>`

  let html = `
  <!DOCTYPE html>
  <head>
    <title>Weather example</title>
  </head>
  <body>
    <style>body{padding:6em; font-family: sans-serif;} h1{color:#3a579a}</style>
    <div id="container">
    ${html_content}
    </div>
  </body>`
  
  return new Response(html, {
    headers: {
      "content-type": "text/html;charset=UTF-8",
    }
  });
}

© 2021 Bip.sh, Ltd.