An address form
A checkout asks for a delivery address. You want suggestions while the person types, so they pick an address the data knows instead of inventing a spelling; and when they submit, you want to know whether what they ended up with is an address at all — and if not, which part to ask them about.
The browser cannot call the API itself. A key grants every product its plan includes, to whoever holds it, and the service sends no CORS headers, so a cross-origin request from a page is refused by the browser anyway. The form talks to your own server; your server talks to oslew. Seeauthentication.
The approach
- As the person types, the page waits for a pause, then asks your server for suggestions, which asks
/v1/autocomplete(seeautocomplete). Choosing a suggestion fills the city, postcode and country too. - On submit, the page sends the form to your server, which sends it to
POST /v1/validateand turns the verdict into what the form should do next (see validating an address). - The verdict decides.
confirmed: use it.corrected: show the corrected address and let the person accept it.partialorunconfirmed: point at the parts that disagree and ask again.
Two products: autocomplete is search, validation is address. Search is its own product because a finished address takes five to fifteen completion requests; seeproducts and plans.
curl -G "https://api.oslew.com/v1/autocomplete" \
-H "Authorization: Bearer $GEO_API_KEY" \
--data-urlencode 'q=Museo Sou' \
--data-urlencode 'near=19.4406,-99.2047' \
--data-urlencode 'limit=5'from oslew import Client
# The key is read from GEO_API_KEY.
client = Client(base_url="https://api.oslew.com")
answer = client.autocomplete("Museo Sou", near="19.4406,-99.2047", limit=5)import { Client } from "@oslew/client";
// The key is read from GEO_API_KEY.
const client = new Client({ baseUrl: "https://api.oslew.com" });
const answer = await client.autocomplete("Museo Sou", { near: "19.4406,-99.2047", limit: 5 });HTTP/1.1 200 OK
content-type: application/json
ratelimit-limit: 100
ratelimit-remaining: 299
ratelimit-reset: 1
{
"query": "Museo Sou",
"name": "Museo Sou",
"context": null,
"near": [
19.4406,
-99.2047
],
"results": [
{
"doc": 348329,
"name": "Museo Soumaya",
"lat": 19.44062110346353,
"lon": -99.20465953606559,
"precision": "poi",
"precision_m": 6.756173533775122,
"hierarchy": {
"locality": "Miguel Hidalgo",
"region": "CMX",
"country": "MX",
"category": "museum",
"postcode": null,
"street": null
},
"matched": 2,
"extra": 0,
"prominence": 5,
"provenance": {
"name": "overture-places",
"release": "2026-08-19.0",
"license": "CDLA-Permissive-2.0"
}
},
{
"doc": 348400,
"name": "Museo Jumex",
"lat": 19.440393312940376,
"lon": -99.20370756260536,
"precision": "poi",
"precision_m": 6.756173533775122,
"hierarchy": {
"locality": "Miguel Hidalgo",
"region": "CMX",
"country": "MX",
"category": "museum",
"postcode": null,
"street": null
},
"matched": 1,
"extra": 1,
"prominence": 2,
"provenance": {
"name": "overture-places",
"release": "2026-08-19.0",
"license": "CDLA-Permissive-2.0"
}
},
{
"doc": 365706,
"name": "Soundspeedmx",
"lat": 19.493992651778623,
"lon": -99.24491233766965,
"precision": "poi",
"precision_m": 6.756173533775122,
"hierarchy": {
"locality": "Naucalpan de Juárez",
"region": null,
"country": "MX",
"category": "storage_facility",
"postcode": null,
"street": null
},
"matched": 1,
"extra": 0,
"prominence": 0,
"provenance": {
"name": "overture-places",
"release": "2026-08-19.0",
"license": "CDLA-Permissive-2.0"
}
},
{
"doc": 1930310,
"name": "CALLE SOL",
"lat": 19.451611114473653,
"lon": -99.24551844723197,
"precision": "street",
"precision_m": 6.756173533775122,
"hierarchy": {
"locality": "México",
"region": null,
"country": "MX",
"category": null,
"postcode": "53570",
"street": "CALLE SOL"
},
"matched": 1,
"extra": 1,
"prominence": 0,
"provenance": {
"name": "overture-addresses",
"release": "2026-08-19.0",
"license": "permissive (per-source, see record)"
}
},
{
"doc": 1930317,
"name": "CALLE SOL",
"lat": 19.45169432510208,
"lon": -99.2456916222276,
"precision": "street",
"precision_m": 6.756173533775122,
"hierarchy": {
"locality": "México",
"region": null,
"country": "MX",
"category": null,
"postcode": "53570",
"street": "CALLE SOL"
},
"matched": 1,
"extra": 1,
"prominence": 0,
"provenance": {
"name": "overture-addresses",
"release": "2026-08-19.0",
"license": "permissive (per-source, see record)"
}
}
],
"mode": "all",
"examined": 316,
"postings": 42,
"segments": 2,
"took_us": 1399
}A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call.
The last word of q is a prefix — Sou finds Soumaya — unless the text ends in a space, which says the word is finished. near here narrows to about a city around the point; it filters rather than biases, so a form that does not know where its user is leaves it out. Completions carry no confidence: a prefix is not yet a question with a right answer.
The program
A server with no framework, in each language, that serves the page and its script and answers two routes:/api/suggest and /api/validate. The key is read from GEO_API_KEY on the server. Run the TypeScript with npx tsx address-form.ts; see clients.
"""The server behind an address form. The browser talks to this and only
this; this talks to oslew, with the key, which never leaves the server.
python address_form.py # then open http://127.0.0.1:8000/
index.html and form.js sit in ./static next to this file.
"""
import json
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlparse
from oslew import BadRequest, Client, GeoError, RateLimited
client = Client(base_url="https://api.oslew.com") # the key is read from GEO_API_KEY
STATIC = Path(__file__).parent / "static"
FILES = {"/": ("index.html", "text/html; charset=utf-8"), "/form.js": ("form.js", "text/javascript")}
ADDRESS_LIKE = {"rooftop", "interpolated", "address", "street"} # not a museum or a shop
FIELDS = ("text", "locality", "postcode", "country")
visitors = {}
def allowed(visitor, rate=5.0, burst=10.0):
"""A small token bucket per visitor, so one script cannot spend the key's
rate for every other visitor."""
now = time.monotonic()
tokens, then = visitors.get(visitor, (burst, now))
tokens = min(burst, tokens + (now - then) * rate)
visitors[visitor] = (tokens - 1 if tokens >= 1 else tokens, now)
return tokens >= 1
def suggest(q):
"""Completions for what has been typed so far."""
answer = client.autocomplete(q, limit=10)
out = []
for r in answer["results"]:
if r["precision"] in ADDRESS_LIKE:
h = r["hierarchy"]
out.append({"label": r["name"], "locality": h.get("locality"),
"postcode": h.get("postcode"), "country": h.get("country")})
return {"suggestions": out[:5]}
def check(form):
"""Validate what was submitted and say what the form should do next."""
body = {k: form[k].strip() for k in FIELDS if isinstance(form.get(k), str) and form[k].strip()}
if "text" not in body:
return {"verdict": "unconfirmed", "formatted": "", "fix": ["street"], "corrected": []}
v = client.post_validate(body)
good = v["verdict"] in ("confirmed", "corrected")
return {
"verdict": v["verdict"],
"formatted": v["formatted"],
"lat": v["lat"] if good else None,
"lon": v["lon"] if good else None,
"fix": [c["name"] for c in v["components"] if c["quality"] == "partial"],
"corrected": [c["name"] for c in v["components"] if c["quality"] == "fuzzy"],
}
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
url = urlparse(self.path)
if url.path in FILES:
name, kind = FILES[url.path]
return self.reply(200, (STATIC / name).read_bytes(), kind)
if url.path != "/api/suggest":
return self.send_json(404, {"error": "not found"})
# Not stripped: a trailing space says the last word is finished.
q = parse_qs(url.query).get("q", [""])[0][:200]
if len(q.strip()) < 3:
return self.send_json(200, {"suggestions": []})
self.answer(suggest, q)
def do_POST(self):
if urlparse(self.path).path != "/api/validate":
return self.send_json(404, {"error": "not found"})
size = int(self.headers.get("content-length") or 0)
if size > 4096:
return self.send_json(413, {"error": "too large"})
try:
form = json.loads(self.rfile.read(size) or b"{}")
except ValueError:
form = None
if not isinstance(form, dict):
return self.send_json(400, {"error": "send a JSON object"})
self.answer(check, form)
def answer(self, work, arg):
# Behind a load balancer, use the forwarded client address instead.
if not allowed(self.client_address[0]):
return self.send_json(429, {"error": "slow down"})
try:
self.send_json(200, work(arg))
except BadRequest as e:
self.send_json(400, {"error": e.message})
except RateLimited as e:
# Interactive: say so now rather than make a person wait.
self.send_json(503, {"error": "busy; try again", "retry_after": e.retry_after})
except GeoError as e:
self.log_error("oslew: %s", e)
self.send_json(502, {"error": "the address service did not answer"})
def send_json(self, status, body):
self.reply(status, json.dumps(body).encode("utf-8"), "application/json")
def reply(self, status, data, kind):
self.send_response(status)
self.send_header("content-type", kind)
self.send_header("content-length", str(len(data)))
self.end_headers()
self.wfile.write(data)
ThreadingHTTPServer(("127.0.0.1", 8000), Handler).serve_forever()// The server behind an address form. The browser talks to this and only
// this; this talks to oslew, with the key, which never leaves the server.
//
// npx tsx address-form.ts # then open http://127.0.0.1:8000/
//
// index.html and form.js sit in ./static next to this file.
import { createServer } from "node:http";
import type { IncomingMessage, ServerResponse } from "node:http";
import { readFile } from "node:fs/promises";
import { BadRequest, Client, RateLimited } from "@oslew/client";
import type { PostValidateBody } from "@oslew/client";
const client = new Client({ baseUrl: "https://api.oslew.com" }); // the key is read from GEO_API_KEY
const FILES: Record<string, [string, string]> = {
"/": ["index.html", "text/html; charset=utf-8"],
"/form.js": ["form.js", "text/javascript"],
};
const ADDRESS_LIKE = new Set(["rooftop", "interpolated", "address", "street"]); // not a museum or a shop
const FIELDS = ["text", "locality", "postcode", "country"] as const;
// A small token bucket per visitor, so one script cannot spend the key's
// rate for every other visitor.
const visitors = new Map<string, { tokens: number; at: number }>();
function allowed(visitor: string, rate = 5, burst = 10): boolean {
const now = Date.now() / 1000;
const seen = visitors.get(visitor) ?? { tokens: burst, at: now };
const tokens = Math.min(burst, seen.tokens + (now - seen.at) * rate);
visitors.set(visitor, { tokens: tokens >= 1 ? tokens - 1 : tokens, at: now });
return tokens >= 1;
}
async function suggest(q: string) {
const answer = await client.autocomplete(q, { limit: 10 });
const suggestions = answer.results
.filter((r) => ADDRESS_LIKE.has(r.precision))
.slice(0, 5)
.map((r) => ({
label: r.name,
locality: r.hierarchy.locality ?? null,
postcode: r.hierarchy.postcode ?? null,
country: r.hierarchy.country ?? null,
}));
return { suggestions };
}
async function check(form: Record<string, unknown>) {
const body: PostValidateBody = {};
for (const k of FIELDS) {
const value = form[k];
if (typeof value === "string" && value.trim()) body[k] = value.trim();
}
if (!body.text) return { verdict: "unconfirmed", formatted: "", fix: ["street"], corrected: [] };
const v = await client.post_validate(body);
const good = v.verdict === "confirmed" || v.verdict === "corrected";
return {
verdict: v.verdict,
formatted: v.formatted,
lat: good ? v.lat : null,
lon: good ? v.lon : null,
fix: v.components.filter((c) => c.quality === "partial").map((c) => c.name),
corrected: v.components.filter((c) => c.quality === "fuzzy").map((c) => c.name),
};
}
async function readBody(req: IncomingMessage, limit: number): Promise<string | null> {
const chunks: Buffer[] = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > limit) return null;
chunks.push(chunk);
}
return Buffer.concat(chunks).toString("utf8");
}
function sendJson(res: ServerResponse, status: number, body: unknown) {
res.writeHead(status, { "content-type": "application/json" });
res.end(JSON.stringify(body));
}
async function answer(req: IncomingMessage, res: ServerResponse, work: () => Promise<unknown>) {
// Behind a load balancer, use the forwarded client address instead.
if (!allowed(req.socket.remoteAddress ?? "")) return sendJson(res, 429, { error: "slow down" });
try {
sendJson(res, 200, await work());
} catch (e) {
if (e instanceof BadRequest) sendJson(res, 400, { error: e.message });
// Interactive: say so now rather than make a person wait.
else if (e instanceof RateLimited) sendJson(res, 503, { error: "busy; try again", retry_after: e.retryAfter });
else {
console.error("oslew:", e);
sendJson(res, 502, { error: "the address service did not answer" });
}
}
}
createServer(async (req, res) => {
const url = new URL(req.url ?? "/", "http://localhost");
if (req.method === "GET" && Object.hasOwn(FILES, url.pathname)) {
const [name, kind] = FILES[url.pathname];
res.writeHead(200, { "content-type": kind });
return res.end(await readFile(new URL(`./static/${name}`, import.meta.url)));
}
if (req.method === "GET" && url.pathname === "/api/suggest") {
// Not trimmed: a trailing space says the last word is finished.
const q = (url.searchParams.get("q") ?? "").slice(0, 200);
if (q.trim().length < 3) return sendJson(res, 200, { suggestions: [] });
return answer(req, res, () => suggest(q));
}
if (req.method === "POST" && url.pathname === "/api/validate") {
const raw = await readBody(req, 4096);
if (raw === null) return sendJson(res, 413, { error: "too large" });
let form: unknown;
try {
form = JSON.parse(raw || "{}");
} catch {
form = null;
}
if (!form || typeof form !== "object" || Array.isArray(form)) {
return sendJson(res, 400, { error: "send a JSON object" });
}
return answer(req, res, () => check(form as Record<string, unknown>));
}
sendJson(res, 404, { error: "not found" });
}).listen(8000, "127.0.0.1");The page and its script are the same for either server, and neither holds a key:
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Delivery address</title>
<form id="address" autocomplete="off">
<label>Street and number <input name="text" required></label>
<ul id="suggestions"></ul>
<label>City <input name="locality"></label>
<label>Postcode <input name="postcode"></label>
<label>Country <input name="country" value="MX" maxlength="2"></label>
<button>Use this address</button>
<p id="message" role="status"></p>
</form>
<script src="/form.js"></script>
</html>// In the browser. It talks to your server, never to the API: no key here.
const form = document.querySelector("#address");
const street = form.elements.text;
const list = document.querySelector("#suggestions");
const message = document.querySelector("#message");
let timer;
let pending;
let asked = 0;
street.addEventListener("input", () => {
clearTimeout(timer);
timer = setTimeout(suggest, 200); // a pause in typing, not every key
});
async function suggest() {
const q = street.value; // not trimmed: "Museo " and "Museo" ask different things
if (q.trim().length < 3) return list.replaceChildren();
pending?.abort(); // an answer to an older prefix is no use now
pending = new AbortController();
const mine = ++asked;
try {
const r = await fetch(`/api/suggest?q=${encodeURIComponent(q)}`, { signal: pending.signal });
if (!r.ok || mine !== asked) return;
const { suggestions } = await r.json();
list.replaceChildren(...suggestions.map(option));
} catch (e) {
if (e.name !== "AbortError") list.replaceChildren(); // no suggestions; the form still works
}
}
function option(s) {
const li = document.createElement("li");
li.textContent = [s.label, s.locality, s.postcode].filter(Boolean).join(", "); // text, never HTML
li.addEventListener("click", () => {
street.value = s.label;
form.elements.locality.value = s.locality ?? "";
form.elements.postcode.value = s.postcode ?? "";
if (s.country) form.elements.country.value = s.country;
list.replaceChildren();
});
return li;
}
// Which input to point at when the answer names a part.
const INPUT = { house_number: "text", street: "text", name: "text", locality: "locality", postcode: "postcode", country: "country" };
function say(text, parts = []) {
message.textContent = text;
for (const el of form.elements) el.removeAttribute("aria-invalid");
for (const p of parts) form.elements[INPUT[p]]?.setAttribute("aria-invalid", "true");
}
form.addEventListener("submit", async (event) => {
event.preventDefault();
const r = await fetch("/api/validate", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(Object.fromEntries(new FormData(form))),
});
const v = await r.json();
if (!r.ok) return say(v.error ?? "The address could not be checked. Try again.");
if (v.verdict === "confirmed") return use(v);
if (v.verdict === "corrected") {
// The person decides: two edits can turn one street into another.
if (confirm(`Did you mean ${v.formatted}?`)) return use(v);
return say("Check the highlighted parts.", v.corrected);
}
if (v.verdict === "partial") {
return say("Part of this address does not match what we know. Check the highlighted parts.", v.fix.length ? v.fix : ["street"]);
}
say("We could not find this address. Check the street and number.", ["street"]);
});
function use(v) {
// Hand the address on: to the next step of your checkout, say.
say(`Using ${v.formatted}.`);
}The decisions in it
Typing: wait, cancel, and never trim
- A 200 ms pause before asking, so a fast typist sends a request when they pause rather than one per key. Three characters at least; fewer match too much to help.
- An older answer is thrown away. Each request aborts the one before it, and an answer that arrives after a newer question was asked is ignored — otherwise a slow reply to
Avencan overwrite the list forAvenida Insu. - The text is sent as typed. A trailing space means the last word is finished, so trimming
MuseotoMuseoasks a different question: a prefix again. The server caps the length and checks for three real characters, and leaves the spaces alone. - Addresses only. The server asks for ten completions and keeps the first five with an address precision —
rooftop,interpolated,addressorstreet— because a delivery form does not want the museum. A form that should accept businesses keepspoi. - Names are text. The script sets
textContent, neverinnerHTML: a place name comes from open data, and is not yours to trust as markup.
Submitting: the verdict, and which part to point at
The server sends the street line as text — validation finds the house number at either end of it — and the city, postcode and country as their own fields. It answers the page with the verdict, the formatted address, and two lists of part names: fix, the parts whose quality is partial (the match contradicts them), and corrected, the parts it matched within two edits.
| Verdict | The form |
|---|---|
confirmed | Uses the address. Every part given was exact, and it is an address point. |
corrected | Asks: "Did you mean …?" with the corrected address. Two edits can be a different street, so the person decides. |
partial | Marks the parts in fix and asks the person to check them — a house number the street does not have, a postcode that belongs elsewhere. |
unconfirmed | Asks for the street and number again. Nothing matched, or the street contradicts what did. |
corrected: a misspelt street
HTTP/1.1 200 OK
content-type: application/json
ratelimit-limit: 100
ratelimit-remaining: 295
ratelimit-reset: 1
{
"verdict": "corrected",
"formatted": "1602 AVENIDA INSURGENTES SUR, Ciudad de México, 03940, MX",
"components": [
{
"name": "house_number",
"input": "1602",
"matched": "1602",
"quality": "exact"
},
{
"name": "street",
"input": "Avenida Insurjentes Sur",
"matched": "AVENIDA INSURGENTES SUR",
"quality": "fuzzy"
},
{
"name": "locality",
"input": null,
"matched": "Ciudad de México",
"quality": "missing"
},
{
"name": "region",
"input": null,
"matched": null,
"quality": "missing"
},
{
"name": "postcode",
"input": "03940",
"matched": "03940",
"quality": "exact"
},
{
"name": "country",
"input": null,
"matched": "MX",
"quality": "missing"
}
],
"lat": 19.364069672979937,
"lon": -99.18198831998704,
"precision": "rooftop",
"confidence": 0.5967742,
"candidates": 25,
"why": "matched AVENIDA INSURGENTES SUR 1602 (an address point) among 25 candidates; street corrected from \"Avenida Insurjentes Sur\" to \"AVENIDA INSURGENTES SUR\"; locality inferred as \"Ciudad de México\"; country inferred as \"MX\"",
"epoch": 30,
"release": "2026-08-19.0",
"took_us": 1734
}A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call.
partial: a number the street does not have
HTTP/1.1 200 OK
content-type: application/json
ratelimit-limit: 100
ratelimit-remaining: 294
ratelimit-reset: 1
{
"verdict": "partial",
"formatted": "AVENIDA INSURGENTES SUR, Ciudad de México, 04530, MX",
"components": [
{
"name": "house_number",
"input": "9999999",
"matched": null,
"quality": "partial"
},
{
"name": "street",
"input": "Avenida Insurgentes Sur",
"matched": "AVENIDA INSURGENTES SUR",
"quality": "exact"
},
{
"name": "locality",
"input": "Ciudad de México",
"matched": "Ciudad de México",
"quality": "exact"
},
{
"name": "region",
"input": null,
"matched": null,
"quality": "missing"
},
{
"name": "postcode",
"input": null,
"matched": "04530",
"quality": "missing"
},
{
"name": "country",
"input": null,
"matched": "MX",
"quality": "missing"
}
],
"lat": 19.306485580000658,
"lon": -99.18666049037793,
"precision": "street",
"confidence": 0.35,
"candidates": 25,
"why": "matched AVENIDA INSURGENTES SUR (an address point) among 25 candidates; house_number \"9999999\" contradicts the match; postcode inferred as \"04530\"; country inferred as \"MX\"",
"epoch": 30,
"release": "2026-08-19.0",
"took_us": 2252
}A real response, captured from the service at commit b8f4bde-dirty. Timing fields such as took_us differ on every call.
house_number is partial in the second answer, so the form marks the street-and-number input. postcode and country are missing — not given — andmatched says what the match would put there. An unconfirmed address may still be real: a building newer than the data, or an area the loaded data covers thinly. The form above only asks again; a production form should also let the person keep what they typed, and flag the order for a look rather than refusing it.
The server: a narrow proxy, not an open one
- Two routes and fixed parameters. The browser cannot choose the endpoint, the
limitor anything else, so the server is not a way to spend your key on arbitrary requests. - A bucket per visitor. Every visitor shares your key's rate. Without a limit of your own, one script typing in a loop slows autocomplete for everyone else. Five a second with a burst of ten is generous for a person.
- Fail fast on a 429. A person is waiting, so the server answers
503at once rather than sleeping outRetry-After; the form still works without suggestions. A backfill would wait — see rate limits. - Position only when it is trusted. The server returns
latandlononly forconfirmedandcorrected; a partial or unconfirmed answer's position is the position of something else.
What to watch out for
- Do not trust the verdict the browser sends back. Anything the page holds, a person can edit. When the order is placed, validate on the server again, or keep the server's own answer keyed to the session.
- Autocomplete does not resolve context. Text after a comma is passed through as a raw term — no division or ISO code matching, unlike geocoding — which is why the form suggests from the street line alone and lets validation weigh the city and postcode.
- Validation's
formattedleads with the number —1602 AVENIDA INSURGENTES SUR— whatever the country's convention. Show it as a suggestion; if you store a layout, build it fromcomponents. GET /v1/validatetakes the same fields as query parameters. It is the same check;its reference lists them. A misspelt name is ignored, not refused:?q=instead of?text=is a request with no address in it.- Behind a load balancer, the socket's address is the balancer's. Key the per-visitor bucket on the forwarded client address, and in production use the rate limiting your framework or gateway already has.
Endpoints
/v1/autocompletesearchComplete text being typed: the last token is a prefix, prominence ranks before name length, and no confidence is claimed.