JavaScript Weather API Practice Exercise
Use this guided practice page to rebuild a weather forecast request from memory. The browser calls this website's backend, while the private WeatherAPI key remains on the server.
Review the complete Weather API lesson when you want to compare your solution with the full explanation.
Learning objectives
- read named controls from a submitted form;
- trim and validate the city value;
- build query parameters with
URLSearchParams; - request a same-origin backend endpoint with
fetch(); - check
response.okand read JSON; - show loading, success and error states;
- render forecast values using DOM properties instead of inserting API text as HTML.
Request flow
Form submission
-> validate city and days
-> fetch("/api/weather?...")
-> backend validates the request
-> backend asks WeatherAPI.com with its private key
-> browser renders selected forecast data
Working practice form
Enter a city and request one to three forecast days. Watch the status message while the request is running, then inspect the result and the Network panel in browser DevTools.
Enter a city to begin.
Weather data by WeatherAPI.com.
Practice steps
- Select the form, status paragraph, result list and submit button.
- Listen for
submitand callevent.preventDefault(). - Read and trim
elements.city.value, then readelements.days.value. - Build
/api/weatherparameters without adding any API key. - Disable the button and show a loading message during the request.
- Check the HTTP response before reading its JSON body.
- Render the forecast or show the backend's safe error message.
- Restore the button in
finally().
Further challenges
- Press Enter in the city field instead of clicking the button.
- Test an unknown city and inspect the
404response. - Test one-day and three-day forecasts.
- Add a button that clears the forecast.
- Rewrite the promise chain using
asyncandawait.