API Documentation - Endpoints & Examples

Address Autocomplete

From an empty input to a validated, stored address

This guide builds the address step of a checkout: the user types, picks a city, and the country, province and postcode fields fill themselves in and get validated. Around 60 lines of JavaScript.

Three endpoints do the work:

  1. /v1/places/autocomplete — suggestions while typing
  2. /v1/places/details — the full record of what was picked
  3. /v1/places/validate — final check before you store it

The session token, first

A typeahead sends a request per keystroke. To keep the cost predictable, generate a sessiontoken when the field gains focus and reuse it for every request of that field, including the final details call. The whole field costs 1 token, however much the user types.

let session = crypto.randomUUID();

input.addEventListener('focus', () => {
  session = crypto.randomUUID(); // one session per address the user enters
});

Sessions last 3 minutes. If you omit the token, every request costs 1 token instead.

Vanilla JavaScript

<input id="city" placeholder="Start typing your city..." autocomplete="off" />
<ul id="suggestions"></ul>

<input id="country" readonly />
<input id="state" readonly />
<input id="zip" placeholder="Postal code" />
<p id="zip-error"></p>
const API_KEY = 'your-api-key';
const BASE = 'https://api.countrydataapi.com/v1/places';

const input = document.getElementById('city');
const list = document.getElementById('suggestions');

let session = crypto.randomUUID();
let timer;
let postal = null;

input.addEventListener('focus', () => { session = crypto.randomUUID(); });

// Debounce: one request per pause, not per key.
input.addEventListener('input', () => {
  clearTimeout(timer);
  const q = input.value.trim();
  if (q.length < 2) { list.innerHTML = ''; return; }

  timer = setTimeout(() => search(q), 150);
});

async function search(q) {
  const params = new URLSearchParams({
    apikey: API_KEY,
    q,
    types: 'city',
    limit: '5',
    sessiontoken: session,
  });

  const response = await fetch(`${BASE}/autocomplete?${params}`);
  const { suggestions } = await response.json();

  list.innerHTML = '';
  suggestions.forEach((suggestion) => {
    const item = document.createElement('li');
    item.textContent = suggestion.description; // "Madrid, Comunidad de Madrid, Spain"
    item.onclick = () => choose(suggestion);
    list.appendChild(item);
  });
}

async function choose(suggestion) {
  list.innerHTML = '';
  input.value = suggestion.name;

  const params = new URLSearchParams({
    apikey: API_KEY,
    id: suggestion.id,
    type: suggestion.type,
    sessiontoken: session, // closes the session: this call is free
  });

  const response = await fetch(`${BASE}/details?${params}`);
  const { place } = await response.json();

  document.getElementById('country').value = place.components.country?.name ?? '';
  document.getElementById('state').value = place.components.state?.name ?? '';

  // The country's postcode rules, to validate the next field in the browser.
  postal = place.postal;
  document.getElementById('zip').placeholder = postal.example ?? 'Postal code';
}

document.getElementById('zip').addEventListener('blur', (event) => {
  const error = document.getElementById('zip-error');
  if (!postal?.regex) { error.textContent = ''; return; }

  const ok = new RegExp(postal.regex).test(event.target.value.trim());
  error.textContent = ok ? '' : `Expected format: ${postal.example ?? postal.format}`;
});

That is the whole interaction. The description field is already formatted for a dropdown, so there is no string assembly to do.

React

import { useEffect, useRef, useState } from 'react';

const API_KEY = 'your-api-key';
const BASE = 'https://api.countrydataapi.com/v1/places';

export function useAddressAutocomplete() {
  const [query, setQuery] = useState('');
  const [suggestions, setSuggestions] = useState([]);
  const [address, setAddress] = useState(null);
  const session = useRef(crypto.randomUUID());

  useEffect(() => {
    if (query.trim().length < 2) {
      setSuggestions([]);
      return;
    }

    // Abort in-flight requests so a slow response cannot overwrite a newer one.
    const controller = new AbortController();
    const timer = setTimeout(async () => {
      const params = new URLSearchParams({
        apikey: API_KEY,
        q: query.trim(),
        types: 'city',
        limit: '5',
        sessiontoken: session.current,
      });

      try {
        const response = await fetch(`${BASE}/autocomplete?${params}`, {
          signal: controller.signal,
        });
        const data = await response.json();
        setSuggestions(data.suggestions ?? []);
      } catch (error) {
        if (error.name !== 'AbortError') throw error;
      }
    }, 150);

    return () => {
      clearTimeout(timer);
      controller.abort();
    };
  }, [query]);

  async function select(suggestion) {
    const params = new URLSearchParams({
      apikey: API_KEY,
      id: suggestion.id,
      type: suggestion.type,
      sessiontoken: session.current,
    });

    const response = await fetch(`${BASE}/details?${params}`);
    const { place } = await response.json();

    setAddress(place);
    setSuggestions([]);
    setQuery(place.name);
    session.current = crypto.randomUUID(); // next address, next session
  }

  return { query, setQuery, suggestions, address, select };
}
function AddressField() {
  const { query, setQuery, suggestions, address, select } = useAddressAutocomplete();

  return (
    <div>
      <input
        value={query}
        onChange={(event) => setQuery(event.target.value)}
        placeholder="Start typing your city..."
        autoComplete="off"
      />

      {suggestions.length > 0 && (
        <ul>
          {suggestions.map((suggestion) => (
            <li key={suggestion.id} onClick={() => select(suggestion)}>
              {suggestion.description}
            </li>
          ))}
        </ul>
      )}

      {address && (
        <>
          <input readOnly value={address.components.country?.name ?? ''} />
          <input readOnly value={address.components.state?.name ?? ''} />
          <input placeholder={address.postal.example ?? 'Postal code'} />
        </>
      )}
    </div>
  );
}

Final validation on the server

Client-side validation is for the user's benefit. Before you store or ship anything, confirm the whole combination server-side:

const params = new URLSearchParams({
  apikey: process.env.COUNTRY_DATA_API_KEY,
  country: form.country,
  state: form.state,
  city: form.city,
  zipcode: form.zip,
});

const response = await fetch(
  `https://api.countrydataapi.com/v1/places/validate?${params}`
);
const { result } = await response.json();

if (!result.valid && result.has_corrections) {
  // Offer the correction instead of rejecting the form outright.
  return { needsConfirmation: result.corrections };
}

// Store the canonical form, not what the user typed.
await orders.save({
  country: result.normalized.country?.name,
  state: result.normalized.state?.name,
  city: result.normalized.city?.name,
  zipcode: result.normalized.zipcode,
});

Storing result.normalized rather than the raw input is what makes your address data queryable later: no Cataluna next to Cataluña, no MADRID next to Madrid.

Asking for less

If your form only has a postal code and a city, you do not need the province field at all — the postcode resolves it:

const { result } = await api.places.validate({ country: 'ES', zipcode: '28001' });
result.normalized.state?.name; // "Comunidad de Madrid"

One field fewer is measurably better conversion on a checkout.

What this costs

Action Tokens
A full address field (any number of keystrokes + details) 1
Server-side validation of the submitted form 1
Postcode formats for every country (cache it) 1, once

So a completed checkout address costs 2 tokens, and it does not matter how fast the user types.

What this does not do

The dataset is administrative: countries, states, cities and postal codes. There is no street-level data, no coordinates below country level, and no points of interest — no businesses, opening hours, ratings or photos. If you need to geocode a full street address or search for a restaurant, this is not the right tool.

Related