Skip to content

HTTP API ​

An opt-in JSON API over the package services, for front ends that don't run Filament: Inertia (React, Vue, Svelte), SPAs, mobile apps. It exposes the same country data and address flows the Filament form uses, so a custom form gets the same subdivision matching, verification and error codes.

The API is off by default. When it's off, no routes are registered.

Table of Contents ​


Enabling the API ​

bash
ADDRESS_API_ENABLED=true
ADDRESS_API_PREFIX=address-api     # optional, the default

Then run php artisan migrate. Since 1.1 the audit log has a source column that marks calls made through the API.

The routes are registered when the app boots. If you cache routes (php artisan route:cache), rebuild the cache after changing these settings.

All endpoints are under the prefix, e.g. POST /address-api/verify. Route names start with filament-address.api. (e.g. route('filament-address.api.verify')).

Access control ​

The routes use the middleware in addresses.api.middleware (publish the config to change it). The default is ['web']: session cookies and CSRF protection, for forms served by the same Laravel app.

Front endmiddleware
Inertia or Blade pages on the same domain, public forms['web'] (default)
Same domain, signed-in users only['web', 'auth']
SPA on another domain, or a mobile app (Sanctum tokens)['api', 'auth:sanctum']
Your own guard or policyAny middleware: ['web', 'auth', 'can:manage-addresses']

With web, POST requests need the CSRF token. Axios (used by Inertia) sends it automatically from the XSRF-TOKEN cookie. With fetch, send it yourself:

js
const token = document.querySelector('meta[name="csrf-token"]').content;

const response = await fetch('/address-api/verify', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': token },
    body: JSON.stringify({ address_line_1: '1600 Amphitheatre Pkwy', locality: 'Mountain View', administrative_area: 'CA', postal_code: '94043', country_code: 'US' }),
});

The API adds its own middleware ahead of yours. It makes every error a JSON response, including a CSRF failure (419) and an authentication failure (401), whatever Accept header the client sends.

Rate limits ​

The resolve and verify endpoints call paid APIs (Google, Smarty, USPS), so they have a stricter limit than the endpoints that read package data.

VariableDefaultApplies to
ADDRESS_API_RATE_LIMIT60,1Countries, subdivisions, postal codes, format (no paid calls)
ADDRESS_API_PAID_RATE_LIMIT10,1resolve/* and verify

The format is attempts,minutes: 10,1 allows 10 requests per minute. Each limit is counted per IP address and, separately, per signed-in user (or per session when there's no user). All paid endpoints share one count, and so do all free ones. Over the limit, the API answers 429 Too Many Requests with a Retry-After header.

The limiters are named filament-address-api and filament-address-api-paid. To use your own rules, redefine them with RateLimiter::for() in a service provider's boot(); yours replace the package's if your provider boots later.

Responses and errors ​

StatusWhenBody
200Data endpoints{ "data": ... }
200Resolve and verify, including a failed lookup or verificationA ResolvedAddress record: check success and error.code
404API disabled, or an unknown country in the URL{ "message": ... }
419CSRF token missing or expired (web middleware){ "message": ... }
422Invalid requestLaravel's validation format: { "message": ..., "errors": { "field": [...] } }
429Rate limit reached{ "message": ... }, Retry-After header

A failed lookup is an address outcome, not a broken request, so resolve and verify return 200 and say what happened:

json
{
    "success": false,
    "fields": {},
    "original": {},
    "changes": [],
    "requires_choice": false,
    "error": {
        "code": "zero_results",
        "message": "No geocoding results found",
        "severity": "warning",
        "details": {}
    },
    "verification_error": null,
    "formatted_address": null,
    "location_type": null,
    "review": { "needs_review": false, "reasons": [] }
}

error.code is one of the error codes: act on the code, not the message. severity says how prominently the Filament form would show it (silent, warning, danger). When the address was found but the verification provider rejected it, success is true, fields holds the address flagged needs_review, and verification_error has the code.

Endpoints ​

Requests and responses use Address field names: address_line_1, address_line_2, locality, locality_id, administrative_area, administrative_area_id, dependent_locality, dependent_locality_id, postal_code, country_code, lat, lon. Country codes are ISO 3166-1 alpha-2, in either case.

MethodPathPaidCalls
GETcountries—
GETcountries/{code}CountryService::getCountryAddressDefinition()
GETcountries/{code}/subdivisionsCountryService subdivision options
POSTpostal-codeCountryService::validatePostalCode(), resolveSubdivisionFromPostalCode()
POSTformatCountryService::formatAddress(), formatAddressLocal()
POSTresolve/input✓AddressResolver::resolveTyped()
POSTresolve/place✓AddressResolver::resolvePlace()
POSTresolve/coordinates✓AddressResolver::resolveCoordinates()
POSTresolve/locate✓AddressResolver::locate()
POSTverify✓AddressResolver::verify()

The static map proxy (GET /filament-address/map-image?lat=&lng=) is separate and always registered; see Configuration.

Countries ​

GET countries: every country, by name.

json
{ "data": [ { "country_code": "JP", "name": "Japan", "name_local": "日本" }, ... ] }

GET countries/{code}: the country and its address definition, which tells a form which fields to show, their labels, which are required and the postal code format.

json
{
    "data": {
        "country_code": "US",
        "name": "United States",
        "name_local": null,
        "address_definition": {
            "subdivision_fields": ["administrative_area", "locality"],
            "template_fields": ["administrative_area", "locality", "postal_code", "address_line_1", "address_line_2"],
            "required_fields": ["address_line_1", "locality", "administrative_area", "postal_code"],
            "uppercase_fields": ["administrative_area", "locality"],
            "field_labels": { "locality": "city", "postal_code": "zip", "administrative_area": "state" },
            "postal_code_regex": "(\\d{5})(?:[ \\-](\\d{4}))?",
            "use_administrative_area_code": true,
            "template_default": "%first_name %last_name\n%organization\n%address_line_1\n%address_line_2\n%locality, %administrative_area %postal_code",
            "template_local": null,
            "administrative_area_level": 1,
            "locality_level": null,
            "dependent_locality_level": null
        }
    }
}

address_definition is null for a country without one. The *_level keys say which subdivision levels the country has in the database: a field with a level gets a dropdown (options below), a field without one is free text.

GET countries/{code}/subdivisions?field=…&parent=…: dropdown options for one subdivision field, by name.

Query
fieldRequired: administrative_area, locality or dependent_locality
parentID of the level above: the administrative area for localities, the locality for dependent localities
json
{ "data": [ { "id": "01K7MTQHWBHDJ219DGYH7SVX1C", "name": "Sichuan", "code": "SC", "iso_code": "CN-SC", "local_code": null, "name_local": "四川省" }, ... ] }

Localities that sit under an administrative area are empty until you pass a parent, so a country's thousands of cities never load at once. Save the option's id as the _id field and its name as the text field.

Postal codes ​

POST postal-code with country_code and postal_code: whether the code matches the country's format, and, where the package knows it (DE, ES, FR, IT, NL), the administrative area it belongs to.

json
{
    "data": {
        "valid": true,
        "postal_code_regex": "\\d{5}",
        "subdivision": { "administrative_area_id": "01K7…", "administrative_area": "Berlin" }
    }
}

valid is true for any non-empty code when the country has no format. subdivision is null when the code is invalid or the area isn't known.

Format preview ​

POST format: the address as the country writes it, in the international template (country name added, in capitals) and the local one, like the form's live preview. Send country_code plus any address fields, and optionally first_name, last_name, organization, bldg, box, ico. Subdivision IDs are shown by name (or code, where the country uses codes).

json
{ "data": { "international": "1600 Amphitheatre Pkwy\nMOUNTAIN VIEW, CA 94043\nUNITED STATES", "local": "1600 Amphitheatre Pkwy\nMOUNTAIN VIEW, CA 94043" } }

Resolve and verify ​

Each endpoint returns one ResolvedAddress record (toArray()):

Key
successfalse when nothing was resolved; see error (fields and original are then {})
fieldsThe complete record: every address field (subdivision text and IDs, coordinates) plus is_verified, verification_provider, verified_at, verification_metadata, needs_review
original, changes, requires_choiceWhen verification standardized the address: the address as entered, the names of the fields that differ (ignoring case and a ZIP+4 suffix), and whether to let the user choose
error, verification_error{ code, message, severity, details } or null
formatted_address, location_typeFrom the geocoder
reviewWhy the address needs review (needs_review, reasons; see Review reasons). Each reason has code, label, message and detail (an object, {} when there's no detail)

Save fields to the address (or let the user choose between original and fields when requires_choice is true). See the AddressResolver reference for what each flow does.

POST resolve/input: an address typed or pasted into line 1, typically when the field loses focus. Required: address_line_1, country_code; send the other fields the user has filled. To decide when to call it (minimum length, paste detection), see BlurGeocodingPolicy.

POST resolve/place: a Google Places Autocomplete selection. Send what the browser has after fetchFields():

Field
place_idThe place ID; the server geocodes it for the stored coordinates
lat, lngRequired
name, street_address, postal_code, country_code, formatted_address, primary_typeFrom the place
currentOptional: { "country_code": "US" }, used when the place has no country

POST resolve/coordinates: lat and lon; reverse geocoding, then verification.

POST resolve/locate: new lat/lon for the current address after an edit (the Filament form calls it when the city changes). Geocode only, no verification; the other fields come back unchanged. Required: country_code and address_line_1, locality or postal_code.

POST verify: verify the address as entered, without geocoding it first (the form's Verify button). Required: address_line_1, country_code. Send lat/lon if you have them.

Costs, auditing and caching ​

  • Paid calls. Every resolve/* and verify request can call Google (Geocoding), Smarty or USPS. Manual entry needs none of them: a form that doesn't geocode or verify just doesn't call these endpoints. Keep the paid rate limit low on public pages.
  • Audit log. Each provider call is a row in address_api_audit_logs, as for the Filament form; rows from API requests have source = api (filter Source in the Audit Log admin page). A place selection also logs its Autocomplete session, as in the form.
  • No caching. Google's terms forbid storing Google Maps content, so nothing from Google is cached on the server, and the responses add no caching headers (web sends Cache-Control: no-cache, private). Don't cache the responses in your front end beyond the user's session either.

Released under a commercial license.