Skip to content
Docs navigation

Get an API key and call the API

Create a key, make one request, and read the forecast it returns. REST needs nothing installed.

Smarter Weather covers the 50 US states and DC only. Coverage details

Working through a coding agent? Step 5 is written for it, and llms.txt covers the whole platform.

1. Get an API key

Create a key in the dashboard. You need a free account; no card.

  1. Create a free account.
  2. Verify your email if the dashboard asks. Until you do, creating a key returns 403 email_not_verified.
  3. Open API keys in the dashboard and click Create key. Name the key, then click Create.
  4. Copy the key; the dashboard shows it once. Add it to .env as SMARTERWEATHER_API_KEY=sw_live_... and add .env to .gitignore.

Result: .env holds your live key.

From a terminal

Run npx -y @smarterweather/mcp-onboarding@latest login. You need Node.js 22 or later. It shows a link and a code to approve in the browser, then writes the key to .env (mode 0600, gitignored). It prints only a key prefix, never the key (key handling).

No account yet

Run npx -y @smarterweather/mcp-onboarding@latest trial for a trial key with no account and no browser step. It writes .env the same way.

Agent and CLI trial key, no account

  • 300 requests over 72 hours, 10 a minute (burst 5).
  • Routes under /v1/weather, /v1/geocode, and /v1/alerts. /v1/catalog requests don't count toward the request budget.
  • Claim it within 7 days to keep the same key on the Free plan: 60 requests a minute, 1,000 a day, no card.
  • The portal playground's sandbox key: 100 requests over 24 hours, 20 a minute (burst 10), same routes and claim window.
How trial keys work

2. Call the weather endpoint

Run this from the folder that holds .env. The first line reads SMARTERWEATHER_API_KEY from .env without running the file, and keeps a key you already exported.

[ -n "$SMARTERWEATHER_API_KEY" ] || export SMARTERWEATHER_API_KEY="$(sed -n 's/^\(export \)\{0,1\}SMARTERWEATHER_API_KEY=//p' .env | tail -n 1 | tr -d "\r\"' ")"
curl -sS 'https://api.smarterweather.com/v1/weather?lat=42.3601&lon=-71.0589' \
  -H "Authorization: Bearer ${SMARTERWEATHER_API_KEY:?set SMARTERWEATHER_API_KEY first, see developers.smarterweather.com/quickstart}"
location
{
  "lat": 42.3601,
  "lon": -71.0589,
  "name": "Boston",
  "region": "MA",
  "timezone": "America/New_York",
  "county": "Suffolk"
}
current
{
  "time": "2026-04-20T14:45:00Z",
  "temperature": 58.4,
  "feels_like": 58.4,
  "humidity": 62,
  "dew_point": 45.2,
  "pressure": 30.05,
  "wind_speed": 11.3,
  "wind_gust": 17.8,
  "wind_direction": 240,
  "visibility": 10,
  "cloud_cover": 35,
  "uv_index": 5,
  "precip_rate": 0,
  "precip_type": "none",
  "conditions": "Partly Cloudy",
  "icon": "partly-cloudy-day",
  "severe": false
}
hourly
[
  {
    "time": "2026-04-20T14:00:00Z",
    "temperature": 58.4,
    "feels_like": 58.4,
    "humidity": 62,
    "wind_speed": 11.3,
    "wind_direction": 240,
    "precip_probability": 5,
    "precip_amount": 0,
    "conditions": "Partly Cloudy",
    "icon": "partly-cloudy-day"
  },
  {
    "time": "2026-04-20T15:00:00Z",
    "temperature": 59.1,
    "feels_like": 59.1,
    "humidity": 60,
    "wind_speed": 12.1,
    "wind_direction": 245,
    "precip_probability": 5,
    "precip_amount": 0,
    "conditions": "Partly Cloudy",
    "icon": "partly-cloudy-day"
  },
  {
    "time": "2026-04-20T16:00:00Z",
    "temperature": 59.6,
    "feels_like": 59.6,
    "humidity": 58,
    "wind_speed": 12.4,
    "wind_direction": 245,
    "precip_probability": 5,
    "precip_amount": 0,
    "conditions": "Partly Cloudy",
    "icon": "partly-cloudy-day"
  }
]
daily
[
  {
    "date": "2026-04-20",
    "high": 61,
    "low": 44.5,
    "humidity_avg": 55,
    "wind_speed_max": 14.2,
    "wind_direction": 240,
    "precip_probability": 10,
    "precip_total": 0,
    "snow_total": 0,
    "conditions": "Partly Cloudy",
    "icon": "partly-cloudy-day",
    "day": {
      "temperature": 61,
      "wind_speed": 14.2,
      "wind_direction": 240,
      "precip_probability": 10,
      "precip_total": 0,
      "conditions": "Partly Cloudy",
      "icon": "partly-cloudy-day",
      "narrative": "Partly cloudy with a high near 61. West winds 10 to 15 mph."
    },
    "night": {
      "temperature": 44.5,
      "wind_speed": 6.8,
      "wind_direction": 260,
      "precip_probability": 5,
      "precip_total": 0,
      "conditions": "Mostly Clear",
      "icon": "mostly-clear-night",
      "narrative": "Mostly clear with a low around 45. Winds becoming light."
    }
  }
]
alerts
[]
outlooks
[]
astro
{
  "civil_dawn": "2026-04-20T09:37:00Z",
  "sunrise": "2026-04-20T10:05:00Z",
  "solar_noon": "2026-04-20T16:47:00Z",
  "sunset": "2026-04-20T23:29:00Z",
  "civil_dusk": "2026-04-20T23:57:00Z",
  "day_length": 48240,
  "daylight_length": 51600,
  "moonrise": "2026-04-20T11:42:00Z",
  "moonset": "2026-04-21T01:18:00Z",
  "moon_phase": 0.15,
  "moon_phase_name": "Waxing Crescent",
  "moon_illumination": 0.22,
  "polar": null
}
gis
{
  "lat": 42.3601,
  "lon": -71.0589,
  "city": "Boston",
  "state": "MA",
  "county": "Suffolk",
  "population": null,
  "timezone": "America/New_York",
  "nearest_radar": {
    "id": "BOX",
    "name": "Boston",
    "lat": 41.9558,
    "lon": -71.1369,
    "distance_km": 45.4
  },
  "nearest_station": {
    "id": "KBOS",
    "name": "Boston Logan International Airport",
    "state": "MA",
    "lat": 42.3656,
    "lon": -71.0096,
    "distance_km": 4.1,
    "elevation_m": 6
  }
}
units
{
  "temperature": "F",
  "wind_speed": "mph",
  "pressure": "inHg",
  "visibility": "mi",
  "precip_amount": "in"
}
attribution
{
  "sources": [
    "NOAA/NWS",
    "NBM",
    "GFS",
    "HRRR",
    "RTMA",
    "MRMS"
  ],
  "notice": "Data sourced from NOAA/NWS public products. Derived products produced by Smarter Weather."
}
meta
{
  "schema_version": "1.0.0",
  "generated_at": "2026-04-20T15:00:04Z",
  "freshness": [
    {
      "source": "rtma",
      "product_id": "rtma_conus_2p5km",
      "reference_time": "2026-04-20T14:45:00Z",
      "latest_valid": "2026-04-20T14:45:00Z",
      "age_seconds": 904
    },
    {
      "source": "hrrr",
      "product_id": "hrrr_conus_3km",
      "reference_time": "2026-04-20T14:00:00Z",
      "latest_valid": "2026-04-20T15:00:00Z",
      "age_seconds": 3604
    }
  ],
  "warnings": []
}

Result: HTTP 200 with the forecast for Boston, as shown. Any other status returns a problem document whose next_steps says what to do.

3. Call it from your code

The same request in JavaScript, Python, or Go. Each reads SMARTERWEATHER_API_KEY from the environment. To look a place up by name, pass location=City, ST instead of lat and lon. The response then adds country, zip, and gis.population, at the geocoder's centroid for the place. A lat/lon call adds the nearest radar and station.

curl "https://api.smarterweather.com/v1/weather?lat=42.3601&lon=-71.0589" \
  -H "Authorization: Bearer ${SMARTERWEATHER_API_KEY:?set SMARTERWEATHER_API_KEY first, see developers.smarterweather.com/quickstart}"
// save as sample.mjs; run: node --env-file=.env sample.mjs (Node 20.6+, ESM top-level await)
const res = await fetch(
  "https://api.smarterweather.com/v1/weather?lat=42.3601&lon=-71.0589",
  { headers: { Authorization: `Bearer ${process.env.SMARTERWEATHER_API_KEY}` } },
);
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
const data = await res.json();
console.log(JSON.stringify(data, null, 2));
# pip install requests python-dotenv
import os, sys, requests
from dotenv import load_dotenv

load_dotenv(".env")  # ./.env in the current directory; variables already set are kept

r = requests.get(
    "https://api.smarterweather.com/v1/weather",
    params={"lat":"42.3601","lon":"-71.0589"},
    headers={"Authorization": f"Bearer {os.environ['SMARTERWEATHER_API_KEY']}"},
)
if not r.ok:
    sys.exit(f"{r.status_code} {r.text}")
data = r.json()
print(data)
package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

func main() {
	req, err := http.NewRequest("GET", "https://api.smarterweather.com/v1/weather?lat=42.3601&lon=-71.0589", nil)
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("SMARTERWEATHER_API_KEY"))
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()
	body, err := io.ReadAll(res.Body)
	if err != nil {
		log.Fatal(err)
	}
	if res.StatusCode < 200 || res.StatusCode > 299 {
		log.Fatalf("%s %s", res.Status, body)
	}
	fmt.Println(string(body))
}

Result: the same JSON as step 2.

4. Give your agent weather tools

If your agent runs in an MCP client, paste this prompt. It installs the onboarding skill, signs you up, creates an API key, and sets up the Weather MCP in your client. You approve once in the browser.

Agents with a wallet can pay per call on the Weather MCP with x402 instead. The REST API always needs a key.

Install the Smarter Weather onboarding skill. The skills CLI needs Node.js 22.20 or later. Run `npx skills@1.7.4 add https://developers.smarterweather.com --skill smarterweather-onboarding` and select your agent. You can read the skill directly at https://developers.smarterweather.com/.well-known/skills/smarterweather-onboarding/SKILL.md (raw: https://raw.githubusercontent.com/smarterweather/developer/main/plugins/smarterweather-onboarding/skills/smarterweather-onboarding/SKILL.md). Then use the onboarding skill to sign up, create an API key, and set up the Weather MCP.

Result: the Weather MCP tools show up in your client.

5. Let an agent get the key

An agent can start with no key: the API answers with a 401 that says what to do next.

curl -sS -D - 'https://api.smarterweather.com/v1/weather?lat=42.3601&lon=-71.0589'
type
"https://smarterweather.com/errors/unauthorized"
title
"Unauthorized"
status
401
detail
"Missing Authorization header. Pass your API key as 'Authorization: Bearer sw_live_*'."
instance
"/v1/weather"
next_steps
{
  "if_no_human_present": "trial",
  "recommended": "device_flow",
  "device_flow": {
    "href": "https://developers.smarterweather.com/agents?utm_campaign=401&utm_medium=problem-json&utm_source=api#device-flow",
    "description": "Human present: run the `command` below. It shows the human a verification URL and code, writes SMARTERWEATHER_API_KEY to ./.env (0600, gitignored), and prints only a key prefix. Without Node: device grant at the endpoints below, then POST api_keys_endpoint and write only the response's key field to .env as a SMARTERWEATHER_API_KEY= line (e.g. pipe through jq -r .key). Never print the key or access token.",
    "command": "npx -y @smarterweather/mcp-onboarding@latest login",
    "client_id": "k2h05BUoTP393zcD",
    "device_authorization_endpoint": "https://clerk.smarterweather.com/oauth/device_authorization",
    "token_endpoint": "https://clerk.smarterweather.com/oauth/token",
    "api_keys_endpoint": "https://api.smarterweather.com/developer/keys"
  },
  "trial": {
    "href": "https://developers.smarterweather.com/agents?utm_campaign=401&utm_medium=problem-json&utm_source=api#trial",
    "description": "No human present: run the `command` below. It mints a trial key, writes SMARTERWEATHER_API_KEY to ./.env (0600, gitignored), prints only a key prefix and claim link. Without Node: GET challenge_endpoint, solve the SHA-256 proof-of-work, then POST mint_endpoint with the JSON body {\"challenge_token\": \"<from the challenge>\", \"solution\": \"<decimal string>\", \"accept_terms\": <true only once the terms are accepted>, \"client\": {\"name\": \"<your app name>\"}}. Set accept_terms to true only after reading the terms at https://developers.smarterweather.com/legal/terms (newer challenge responses carry them as terms_url, plus a request_example whose accept_terms stays false until you change it). Its api_key field is the bearer; write only that field to .env as a SMARTERWEATHER_API_KEY= line and never print it. Claim into a free account before claim_expires_at.",
    "command": "npx -y @smarterweather/mcp-onboarding@latest trial",
    "challenge_endpoint": "https://api.smarterweather.com/developer/keys/trial/challenge",
    "mint_endpoint": "https://api.smarterweather.com/developer/keys/trial"
  },
  "agents": {
    "href": "https://developers.smarterweather.com/llms.txt?utm_campaign=401&utm_medium=problem-json&utm_source=api"
  },
  "errors": {
    "href": "https://developers.smarterweather.com/errors?utm_campaign=401&utm_medium=problem-json&utm_source=api"
  },
  "get_key": {
    "href": "https://developers.smarterweather.com/dashboard/api-keys?utm_campaign=401&utm_medium=problem-json&utm_source=api"
  },
  "key_handling": {
    "href": "https://developers.smarterweather.com/agents?utm_campaign=401&utm_medium=problem-json&utm_source=api#key-handling"
  },
  "keyless_x402": {
    "href": "https://developers.smarterweather.com/agents?utm_campaign=401&utm_medium=problem-json&utm_source=api#x402"
  },
  "onboarding_mcp": {
    "href": "https://developers.smarterweather.com/agents?utm_campaign=401&utm_medium=problem-json&utm_source=api"
  },
  "quickstart": {
    "href": "https://developers.smarterweather.com/quickstart?utm_campaign=401&utm_medium=problem-json&utm_source=api"
  }
}

The 401 carries a WWW-Authenticate challenge and an RFC 9457 problem with a next_steps map. recommended names the link to take when a person is present; if_no_human_present names the trial link to take when no one is. Links other than those two are shortened to their href above.

A person is present

Run npx -y @smarterweather/mcp-onboarding@latest login in the background or with a long shell timeout, and relay the link and code it prints. It blocks until the person approves, then writes SMARTERWEATHER_API_KEY to ./.env (mode 0600, gitignored) and prints only a key prefix. The 401's next_steps.device_flow.command names this command. You need Node.js 22 or later.

Without Node.js, use the device grant directly. Write only the key field of the POST api_keys_endpoint response to .env as SMARTERWEATHER_API_KEY=, and never print the key or the access token.

  1. POST device_authorization_endpoint with the advertised client_id and scope=openid email. Read device_code, user_code, verification_uri, and interval.
  2. Show the person verification_uri and user_code. Poll token_endpoint with grant_type=urn:ietf:params:oauth:grant-type:device_code every interval seconds. Handle authorization_pending, slow_down, and expired_token.
  3. POST api_keys_endpoint with the access token, the body { "name": "cli <project>", "origin": { "channel": "device_flow" } }, and a new Idempotency-Key UUID. On 403 email_not_verified, ask the person to verify their email, then retry. Write only the response's key field to .env.
  4. Discard the access token. Never print the key.
npx -y @smarterweather/mcp-onboarding@latest login
# Preferred: the one command above. Shows the human a URL, writes ./.env
# (0600, gitignored), prints only a key prefix.

# Raw recipe (no Node): reference only, not a runnable script; step 2 needs
# your own poll loop. Stop if .env already has SMARTERWEATHER_API_KEY.
# 1. Ask Clerk for a device code (client_id is public; it is in the 401 body).
curl -sS -X POST 'https://clerk.smarterweather.com/oauth/device_authorization' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  --data-urlencode 'client_id=k2h05BUoTP393zcD' \
  --data-urlencode 'scope=openid email'

# 2. Show the human verification_uri + user_code. Poll until they approve.
#    grant_type=urn:ietf:params:oauth:grant-type:device_code
#    handle authorization_pending / slow_down / expired_token.

# 3. Create a key and write ONLY its key field to .env. Nothing reaches the terminal.
# (umask 077; curl -sS -X POST 'https://api.smarterweather.com/developer/keys' \
#   -H "Authorization: Bearer $ACCESS_TOKEN" \
#   -H "Idempotency-Key: $(uuidgen)" \
#   -H 'Content-Type: application/json' \
#   -d '{"name":"cli my-project","origin":{"channel":"device_flow"}}' \
#   | jq -er '"SMARTERWEATHER_API_KEY=" + .key' >> .env)
# grep -qx '.env' .gitignore 2>/dev/null || echo .env >> .gitignore

# 4. Discard the access token (unset ACCESS_TOKEN).

No one is present

Run npx -y @smarterweather/mcp-onboarding@latest trial, named by next_steps.trial.command. A trial key allows 300 requests over 72 hours, 10 a minute (burst 5); /v1/catalog requests don't count toward the 300. A person can claim the key later from the printed claim link.

Result: .env holds a key and the terminal shows only its prefix.

Three recipes

Schedule check

Move outdoor work when daily precipitation probability crosses a threshold.

// save as schedule.mjs; run: node --env-file=.env schedule.mjs (Node 20.6+)
const res = await fetch(
  "https://api.smarterweather.com/v1/weather?location=Boston,%20MA&include=daily",
  { headers: { Authorization: `Bearer ${process.env.SMARTERWEATHER_API_KEY}` } },
);
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
const weather = await res.json();
const today = weather.daily.find((d) => d.relative_day === 0);
if ((today?.precip_probability ?? 0) >= 40) {
  console.log("Move outdoor work inside");
}

Alert routing

Forward the alerts array to a webhook.

// save as alerts.mjs; run: node --env-file=.env alerts.mjs (Node 20.6+, WEBHOOK_URL set)
const res = await fetch(
  "https://api.smarterweather.com/v1/weather?location=Boston,%20MA&include=alerts",
  { headers: { Authorization: `Bearer ${process.env.SMARTERWEATHER_API_KEY}` } },
);
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
const weather = await res.json();
for (const alert of weather.alerts ?? []) {
  await fetch(process.env.WEBHOOK_URL, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(alert),
  });
}

Map overlay

Draw active NWS alert polygons in MapLibre. Your server holds the key (the API is not called from browsers). It draws the 4 most severe alerts in view and reports returned (capped at 50) and truncated. A new view costs up to 5 requests: 1 search, then up to 4 alert lookups at once, skipping alerts fetched in the last minute. Trial keys allow 10 requests a minute (burst 5); a lookup refused with a 429 is left off the map until the next view. Set PAGE_ORIGIN to your page's origin.

// proxy.mjs holds the key; the browser calls it. Run: node --env-file=.env proxy.mjs
// Set PAGE_ORIGIN to your page's origin (default http://localhost:3000).
import { createServer } from "node:http";

const PAGE_ORIGIN = process.env.PAGE_ORIGIN ?? "http://localhost:3000";
const TTL_MS = 60_000; // matches the API's Cache-Control: max-age=60
const cache = new Map(); // key -> { at, promise }; failures are not kept

function cached(key, load) {
  const hit = cache.get(key);
  if (hit && Date.now() - hit.at < TTL_MS) return hit.promise;
  if (cache.size > 500) cache.clear();
  const promise = load();
  cache.set(key, { at: Date.now(), promise });
  promise.catch(() => cache.get(key)?.promise === promise && cache.delete(key));
  return promise;
}

async function api(path) {
  const res = await fetch("https://api.smarterweather.com" + path, { headers: { Authorization: `Bearer ${process.env.SMARTERWEATHER_API_KEY}` } });
  if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
  return res.json();
}

createServer(async (req, res) => {
  const q = new URL(req.url, "http://localhost").searchParams;
  // Snap the box outward to 0.5° so nearby views share a cache entry.
  const snap = (k, round) => round(Number(q.get(k)) * 2) / 2;
  const box = new URLSearchParams({
    min_lon: snap("min_lon", Math.floor),
    min_lat: snap("min_lat", Math.floor),
    max_lon: snap("max_lon", Math.ceil),
    max_lat: snap("max_lat", Math.ceil),
  }).toString();
  try {
    // Search, then geometry (only on /v1/alerts/{id}) for the 4 most severe
    // alerts. Details are cached per id, so re-pans reuse them.
    const { alerts, truncated } = await cached(box, () => api(`/v1/alerts?${box}`));
    const details = await Promise.allSettled(
      alerts.slice(0, 4).map((a) =>
        cached(a.id, () => api(`/v1/alerts/${encodeURIComponent(a.id)}`)),
      ),
    );
    const features = details
      .filter((d) => d.status === "fulfilled" && d.value.geometry)
      .map(({ value: d }) => ({
        type: "Feature",
        geometry: d.geometry,
        properties: { event: d.event, severity: d.severity },
      }));
    res.writeHead(200, {
      "Content-Type": "application/geo+json",
      "Access-Control-Allow-Origin": PAGE_ORIGIN,
    });
    // returned: alerts the search returned (capped at 50; truncated = more exist).
    res.end(JSON.stringify({ type: "FeatureCollection", features, returned: alerts.length, truncated }));
  } catch (err) {
    res.writeHead(502, { "Access-Control-Allow-Origin": PAGE_ORIGIN });
    res.end(String(err));
  }
}).listen(8787, "127.0.0.1");
// In the page (maplibre-gl loaded, <div id="map">), with proxy.mjs on :8787
// and its PAGE_ORIGIN set to this page's origin.
const map = new maplibregl.Map({
  container: "map",
  style: "https://demotiles.maplibre.org/style.json",
  center: [-87.63, 41.88],
  zoom: 5,
});

function alertsUrl() {
  // Undo world-copy wrapping, then clamp: the API rejects lon outside ±180.
  const b = map.getBounds();
  const shift = Math.round(b.getCenter().lng / 360) * 360;
  const clamp = (v, max) => Math.min(max, Math.max(-max, v));
  const box = new URLSearchParams({
    min_lon: clamp(b.getWest() - shift, 180),
    min_lat: clamp(b.getSouth(), 90),
    max_lon: clamp(b.getEast() - shift, 180),
    max_lat: clamp(b.getNorth(), 90),
  });
  return "http://127.0.0.1:8787/?" + box;
}

map.on("load", () => {
  map.addSource("alerts", { type: "geojson", data: alertsUrl() });
  map.addLayer({
    id: "alerts",
    type: "fill",
    source: "alerts",
    paint: { "fill-color": "#e5484d", "fill-opacity": 0.35 },
  });
  let timer;
  map.on("moveend", () => {
    clearTimeout(timer);
    timer = setTimeout(() => map.getSource("alerts").setData(alertsUrl()), 3000);
  });
});

Next steps