Build a local weather card

Build a weather card from a postal code using JavaScript, Node, or Python, with current conditions and observation time.

Last tested

Working example

HTML + JavaScript
JavaScript (browser)

Set up ParseAPI

Use a public API key restricted to your website. Keep secret keys on your server.

Get an API key ↗

Show the weather for a chosen place

Add a local weather card to a dashboard, account page, or travel view. Start with a postal code and country, use the returned coordinates for a Weather lookup, then render the current temperature, condition, and observation time.

The example uses 10001, US. A browser card can let someone change that place; a server-rendered card can use a location already saved in your application. Keep secret keys on the server when using Node or Python.

1. Locate the place

Keep the postal code and its country together. Postal gives you the coordinates for that area:

JavaScript
const url = new URL(`https://api.parseapi.com/postal/${encodeURIComponent(postal)}`);
url.searchParams.set('country', country);
url.searchParams.set('key', API_KEY);
const response = await fetch(url, { headers: { 'X-API-Version': '2.3.0' }, signal, redirect: 'error', cache: 'no-store' });
if (!response.ok) {
  throw Object.assign(new Error('request_failed'), { status: response.status });
}
const place = await response.json();

The same code can exist in several countries, so the country is explicit. Keep postal codes as text to preserve spaces and leading zeroes. In your application, take these two inputs from the person's place selection or saved location.

2. Request weather at those coordinates

JavaScript
const url = new URL('https://api.parseapi.com/weather');
url.searchParams.set('lat', String(latitude));
url.searchParams.set('lon', String(longitude));
url.searchParams.set('key', API_KEY);
const response = await fetch(url, { headers: { 'X-API-Version': '2.3.0' }, signal, redirect: 'error', cache: 'no-store' });
if (!response.ok) {
  throw Object.assign(new Error('request_failed'), { status: response.status });
}
const weather = await response.json();

Pass place.latitude and place.longitude to Weather; Python reads those keys from the returned dictionary. If either coordinate is missing, keep the place visible and ask for another location instead of requesting weather at a guessed point.

If your app already has coordinates from a city, address, or shared device location, start with the Weather call. Postal coordinates describe an approximate area, so the card is local weather rather than an observation at someone's building.

3. Render the observation

JavaScript
const observation = {
  temperature: weather.current.temperature ?? null,
  temperature_f: weather.current.temperature_f ?? null,
  condition_name: weather.current.condition_name ?? null,
  observed_at: weather.current.observed_at ?? null
};

Weather keeps these values in current. Read weather.current.temperature in Node or weather["current"]["temperature"] in Python. Put the temperature and its unit on the card, followed by the condition and observed_at time.

temperature is Celsius; temperature_f is Fahrenheit. The browser card leads with Fahrenheit for its US selection and Celsius elsewhere, with the other value beside it when available. Display zero as a temperature. Keep a missing value as null and show an unavailable label for an unknown condition.

If the Weather request fails after the place resolves, retain the place and show that its current observation is unavailable. An older observation keeps its actual time; it must not appear to be a fresh reading.

4. Connect it to your page

Use the two calls in the handler that supplies your card's data, then render the returned place and observation in your component. Reuse the selected place for subsequent page views; a weather card does not need to look up the visitor's IP.

When someone changes the place, clear the previous weather immediately and let only that new selection update the card. The browser example submits the new place, cancels pending work, and ignores late responses. It does not poll in the background.

These are ordinary lookups. Node and Python reuse one SDK client with its normal timeout and retry defaults; the browser bounds an update to ten seconds without automatic retries.

This feature shows current conditions. Add forecasts only when your application needs them, using the additional fields in the Weather reference. The Postal reference describes location coverage.

Complete example

Use the complete implementation as a reference when adding this feature to your app. It includes the validation and failure handling around the calls above.

View and copy the complete source
weather-card.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Local weather card</title>
  <style>
    :root { color-scheme: light dark; --bg: #fff; --ink: #152029; --muted: #5e6b75; --line: #d9e2e7; --field: #f6f9fa; --accent: #007c91; --button: #c5f6ff; --error: #b42335; }
    @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { --bg: #0b1015; --ink: #eff7fa; --muted: #94a6b2; --line: #2c3942; --field: #121b23; --accent: #67e8f9; --button: #67e8f9; --error: #fda4af; } }
    :root[data-theme="dark"] { color-scheme: dark; --bg: #0b1015; --ink: #eff7fa; --muted: #94a6b2; --line: #2c3942; --field: #121b23; --accent: #67e8f9; --button: #67e8f9; --error: #fda4af; }
    :root[data-theme="light"] { color-scheme: light; }
    * { box-sizing: border-box; }
    [hidden] { display: none !important; }
    body { margin: 0; padding: 28px; background: var(--bg); color: var(--ink); font: 15px/1.5 system-ui, sans-serif; }
    main { max-width: 520px; margin: 0 auto; }
    p, h1 { margin: 0; }
    .topline { display: flex; align-items: center; justify-content: space-between; gap: 16px; }
    .eyebrow { color: var(--accent); font-size: 11px; font-weight: 650; letter-spacing: .1em; }
    h1 { margin-top: 18px; font-size: clamp(26px, 6vw, 34px); line-height: 1.15; letter-spacing: -.035em; overflow-wrap: anywhere; }
    #area, #condition, #observed, #status { color: var(--muted); }
    #area { margin-top: 7px; font-size: 13px; }
    .reading { display: flex; align-items: baseline; flex-wrap: wrap; gap: 14px; margin-top: 22px; }
    #temperature { font-size: clamp(56px, 13vw, 86px); line-height: 1; font-weight: 400; letter-spacing: -.065em; font-variant-numeric: tabular-nums; }
    #temperature[data-empty="true"] { font-size: 32px; letter-spacing: -.035em; }
    #alternate { color: var(--muted); font-size: 18px; }
    #condition { margin-top: 15px; font-size: 17px; }
    #observed { margin-top: 25px; font-size: 12px; }
    #status { min-height: 20px; margin-top: 12px; font-size: 13px; }
    #status[data-error="true"] { color: var(--error); }
    #status[data-quiet="true"] { position: absolute; width: 1px; height: 1px; min-height: 0; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
    button, input, select { font: inherit; }
    button { min-height: 44px; padding: 10px 14px; border: 0; border-radius: 7px; background: var(--button); color: #07313c; cursor: pointer; font-size: 13px; font-weight: 650; }
    button:disabled { opacity: .55; cursor: wait; }
    #change { padding-inline: 0; color: var(--accent); background: transparent; font-weight: 500; white-space: nowrap; }
    #place-form { margin-top: 24px; padding-top: 22px; border-top: 1px solid var(--line); }
    .fields { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.25fr); gap: 12px; }
    label { display: block; min-width: 0; font-size: 12px; font-weight: 550; }
    input, select { display: block; width: 100%; min-width: 0; min-height: 46px; margin-top: 7px; padding: 11px 10px; border: 1px solid var(--line); border-radius: 7px; color: var(--ink); background: var(--field); }
    select:not([multiple]):where(:not([size]), [size="0"], [size="1"]) { -webkit-appearance: none; appearance: none; padding-right: 40px; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath d='m4 6 4 4 4-4' fill='none' stroke='%2371717a' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 12px center; background-size: 16px; }
    #show { margin-top: 16px; }
    :focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
    @media (max-width: 360px) { body { padding: 20px; } .fields { grid-template-columns: 1fr; } }
  </style>
</head>
<body>
  <main>
    <div class="topline"><p class="eyebrow">CURRENT WEATHER</p><button id="change" type="button" aria-expanded="false" aria-controls="place-form">Change place</button></div>
    <section id="weather-card" aria-labelledby="place-name" aria-busy="true">
      <h1 id="place-name">10001</h1>
      <p id="area">United States</p>
      <div class="reading"><p id="temperature" data-empty="true">Loading</p><p id="alternate"></p></div>
      <p id="condition">Finding the latest observation.</p>
      <p id="observed"></p>
    </section>
    <form id="place-form" hidden>
      <div class="fields">
        <label for="postal">Postal code<input id="postal" name="postal" type="text" autocomplete="postal-code" maxlength="32" value="10001" required></label>
        <label for="country">Country<select id="country" name="country" autocomplete="country" required><option value="US" selected>United States</option><option value="GB">United Kingdom</option><option value="CA">Canada</option><option value="FR">France</option><option value="DE">Germany</option><option value="JP">Japan</option></select></label>
      </div>
      <button id="show" type="submit">Show weather</button>
    </form>
    <p id="status" role="status" aria-live="polite" aria-atomic="true"></p>
  </main>
  <script>
    // Restrict this public key to the hostnames where you run the card.
    const API_KEY = 'YOUR_PUBLIC_API_KEY';
    const COUNTRIES = { US: 'United States', GB: 'United Kingdom', CA: 'Canada', FR: 'France', DE: 'Germany', JP: 'Japan' };
    const $ = (selector) => document.querySelector(selector);
    const form = $('#place-form'), postalInput = $('#postal'), countryInput = $('#country');
    const card = $('#weather-card'), change = $('#change'), show = $('#show'), status = $('#status');
    let revision = 0, controller;

    function setStatus(message, error = false, quiet = false) { status.textContent = message; status.dataset.error = String(error); status.dataset.quiet = String(quiet); }
    function setBusy(busy) { card.setAttribute('aria-busy', String(busy)); show.disabled = busy; }
    function clearObservation(label, detail) {
      $('#temperature').textContent = label; $('#temperature').dataset.empty = 'true';
      $('#alternate').textContent = ''; $('#condition').textContent = detail; $('#observed').textContent = '';
    }
    function showPlace(place) {
      $('#place-name').textContent = place.city || place.postal;
      $('#area').textContent = `${place.postal} · ${COUNTRIES[place.country]}`;
    }
    function showEditor(focus = false) { form.hidden = false; change.setAttribute('aria-expanded', 'true'); if (focus) postalInput.focus(); }

    async function cancelable(task, signal) {
      let onAbort;
      const aborted = new Promise((_, reject) => {
        onAbort = () => reject(new Error('request_aborted'));
        signal.addEventListener('abort', onAbort, { once: true });
        if (signal.aborted) onAbort();
      });
      try {
        return await Promise.race([aborted, (async () => {
          if (signal.aborted) throw new Error('request_aborted');
          return task();
        })()]);
      } finally { signal.removeEventListener('abort', onAbort); }
    }

    async function lookupPostal(postal, country, signal) {
      if (!API_KEY.startsWith('parse_public_')) throw new Error('Add your public API key to run this card.');
      // example:location
      const url = new URL(`https://api.parseapi.com/postal/${encodeURIComponent(postal)}`);
      url.searchParams.set('country', country);
      url.searchParams.set('key', API_KEY);
      const response = await fetch(url, { headers: { 'X-API-Version': '2.3.0' }, signal, redirect: 'error', cache: 'no-store' });
      if (!response.ok) {
        throw Object.assign(new Error('request_failed'), { status: response.status });
      }
      const place = await response.json();
      // /example:location
      return place;
    }

    async function lookupWeather(latitude, longitude, signal) {
      if (!API_KEY.startsWith('parse_public_')) throw new Error('Add your public API key to run this card.');
      // example:request
      const url = new URL('https://api.parseapi.com/weather');
      url.searchParams.set('lat', String(latitude));
      url.searchParams.set('lon', String(longitude));
      url.searchParams.set('key', API_KEY);
      const response = await fetch(url, { headers: { 'X-API-Version': '2.3.0' }, signal, redirect: 'error', cache: 'no-store' });
      if (!response.ok) {
        throw Object.assign(new Error('request_failed'), { status: response.status });
      }
      const weather = await response.json();
      // /example:request
      return weather;
    }

    function readPlace(data, postal, country) {
      const code = (value) => typeof value === 'string' ? value.replace(/\s/g, '').toUpperCase() : '';
      if (!data || !code(data.postal) || code(data.postal) !== code(postal) || data.country !== country ||
          (data.city != null && typeof data.city !== 'string')) throw new Error('unexpected_response');
      for (const [field, limit] of [['latitude', 90], ['longitude', 180]]) {
        if (data[field] != null && (!Number.isFinite(data[field]) || Math.abs(data[field]) > limit)) throw new Error('unexpected_response');
      }
      return data;
    }

    function currentWeather(weather) {
      const current = weather?.current;
      if (!current || typeof current !== 'object' || Array.isArray(current)) throw new Error('unexpected_response');
      for (const field of ['temperature', 'temperature_f']) {
        if (current[field] != null && !Number.isFinite(current[field])) throw new Error('unexpected_response');
      }
      for (const field of ['condition_name', 'observed_at']) {
        if (current[field] != null && typeof current[field] !== 'string') throw new Error('unexpected_response');
      }
      // example:result
      const observation = {
        temperature: weather.current.temperature ?? null,
        temperature_f: weather.current.temperature_f ?? null,
        condition_name: weather.current.condition_name ?? null,
        observed_at: weather.current.observed_at ?? null
      };
      // /example:result
      return observation;
    }

    function showObservation(current, country) {
      const fahrenheit = country === 'US' ? current.temperature_f != null : current.temperature == null && current.temperature_f != null;
      const primary = fahrenheit ? current.temperature_f : current.temperature;
      const other = fahrenheit ? current.temperature : current.temperature_f;
      $('#temperature').textContent = primary == null ? 'Unavailable' : `${Math.round(primary)}°${fahrenheit ? 'F' : 'C'}`;
      $('#temperature').dataset.empty = String(primary == null);
      $('#alternate').textContent = other == null ? '' : `${Math.round(other)}°${fahrenheit ? 'C' : 'F'}`;
      $('#condition').textContent = current.condition_name || 'Condition unavailable';
      const match = current.observed_at?.match(/^(\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d)(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/);
      const wall = match ? new Date(`${match[1]}Z`) : null;
      const instant = wall && Number.isFinite(wall.getTime()) && wall.toISOString().slice(0, 19) === match[1]
        ? new Date(current.observed_at) : null;
      $('#observed').textContent = instant && Number.isFinite(instant.getTime())
        ? `Observed ${new Intl.DateTimeFormat('en', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', timeZone: 'UTC' }).format(instant)} UTC`
        : 'Observation time unavailable';
      return primary != null || !!current.condition_name;
    }

    async function refreshWeather(collapseEditor = false) {
      const currentRevision = ++revision;
      controller?.abort();
      const request = new AbortController(); controller = request;
      const postal = postalInput.value.trim(), country = countryInput.value;
      let place, timedOut = false;
      clearObservation('Loading', 'Finding the latest observation.');
      $('#place-name').textContent = postal || 'Choose a place'; $('#area').textContent = COUNTRIES[country] || '';
      setStatus('Loading weather.'); setBusy(true);
      const timer = setTimeout(() => { timedOut = true; request.abort(); }, 10000);
      const active = () => currentRevision === revision && !request.signal.aborted;
      try {
        if (!postal || postal.length > 32 || !Object.hasOwn(COUNTRIES, country)) throw new Error('Enter a postal code and choose its country.');
        const data = await cancelable(() => lookupPostal(postal, country, request.signal), request.signal);
        place = readPlace(data, postal, country);
        if (!active()) return;
        showPlace(place);
        if (place.latitude == null || place.longitude == null) {
          clearObservation('Unavailable', 'Weather is unavailable for this postal area.');
          setStatus('Choose another place.'); showEditor(); return;
        }
        const weather = await cancelable(() => lookupWeather(place.latitude, place.longitude, request.signal), request.signal);
        const current = currentWeather(weather);
        if (!active()) return;
        const observed = showObservation(current, country);
        if (collapseEditor) { form.hidden = true; change.setAttribute('aria-expanded', 'false'); change.focus(); }
        setStatus(observed ? `Weather loaded for ${place.city || place.postal}.` : 'No current observation is available.', false, observed);
      } catch (error) {
        if (currentRevision !== revision) return;
        clearObservation('Unavailable', place ? 'Current weather is unavailable.' : 'We could not find weather for this place.');
        const message = timedOut ? 'The lookup timed out. Try again.'
          : error.status === 404 ? (place ? 'No current observation is available. Try another place.' : 'Postal code not found. Check the country and code.')
          : error.message === 'unexpected_response' ? 'The result could not be read. Try again.'
          : ['request_failed', 'request_aborted'].includes(error.message) || error instanceof TypeError || error instanceof SyntaxError
            ? 'Weather could not be loaded. Try again.' : error.message;
        setStatus(message, true); showEditor();
      } finally {
        clearTimeout(timer);
        if (currentRevision === revision) setBusy(false);
      }
    }

    change.addEventListener('click', () => showEditor(true));
    form.addEventListener('submit', event => { event.preventDefault(); return refreshWeather(true); });
    function changedPlace() {
      revision++; controller?.abort(); setBusy(false);
      $('#place-name').textContent = 'Choose a place'; $('#area').textContent = '';
      clearObservation('Ready', 'Show weather for your selected place.'); setStatus('');
    }
    form.addEventListener('input', changedPlace);
    form.addEventListener('change', changedPlace);
    // A named place, never an inferred visitor location. Later changes require Show weather.
    void refreshWeather();
  </script>
</body>
</html>
Try the complete example on your computer

Replace YOUR_PUBLIC_API_KEY in the HTML with your public key and add localhost to its allowed domains. Serve the download folder over HTTP:

Terminal · Python 3
python3 -m http.server 8000

Open localhost:8000/weather-card.html. Add your website's hostname to the key when using the feature there.

For every field and parameter, see Postal API reference and Weather API reference.

Build something else

All tutorials →