# Address Verification API

Address verification, batch verification, and parsing for ShipWave users, as a standalone
API. All endpoints under `/api/v1/addresses/*` are billable. The first 100 new lookups per
account each calendar month are free.

## Verification Provider

`verify` and `verify-batch` use Google Address Validation. US and Puerto Rico
addresses are also checked against USPS data, so the response uses
USPS-standardized fields (uppercase, ZIP+4) and USPS delivery-point validation
(DPV).

- `deliverable` is `true` only when Google marks the address complete, confirms
  every component, and matches it to a building or unit (`PREMISE`/`SUB_PREMISE`),
  and, when USPS returns a DPV result (US/PR), that result is `Y`.
- `residential` is Google's residential flag when Google knows it, otherwise `null`.
- `street1` and `city` are always required. `state` and `zip` are required only
  for US and Puerto Rico addresses; leave `state` out for countries that don't use
  one (for example `{"street1":"10 Downing Street","city":"London","zip":"SW1A 2AA","country":"GB"}`).
- `country` is a two-letter country code and defaults to `US`.
- Supported countries are the countries/regions on Google's
  [coverage list](https://developers.google.com/maps/documentation/address-validation/coverage).
  Any other country returns `400 VALIDATION_ERROR`
  (for example `Address could not be verified: Unsupported region code: "AF".`).
- `name` and `company` are accepted but don't affect the result.
- An address that comes back `deliverable: false` is still a completed lookup. It
  returns `200` and counts toward your usage like any other lookup.
- Only send real addresses. The USPS data provider can cut off validation for
  accounts that send made-up US addresses, including for testing.

### `messages` codes

Each entry in `messages` is an object with `code` and `message`.

| Code | Meaning |
|------|---------|
| `ADDRESS.INCOMPLETE` | Google did not mark the address complete |
| `ADDRESS.GRANULARITY` | Matched only to a street, city, or broader level, not a building |
| `ADDRESS.MISSING_COMPONENT` | A required part is missing (e.g. apartment/suite/unit number) |
| `ADDRESS.UNCONFIRMED_COMPONENT` | A part was present but could not be confirmed |
| `ADDRESS.UNRESOLVED_INPUT` | Input text that could not be matched to any part of the address |
| `USPS.NOT_CONFIRMED` | USPS DPV `N`: delivery point not confirmed |
| `USPS.SECONDARY_MISSING` | USPS DPV `D`: building confirmed, unit number missing |
| `USPS.SECONDARY_UNCONFIRMED` | USPS DPV `S`: building confirmed, unit number not confirmed |

`correctedFields` lists which of `street1`, `street2`, `city`, `state`, and `zip`
differ from your input, ignoring case. A field you left blank is never listed.

## Authentication & Scope

Address verification endpoints require an API key with **Address verification**
access (scope `addresses:verify`). Create one in the dashboard under
**Settings → API Keys** and check **Address verification**. **Shipping API** access
(`read:*`/`write:*`) alone is **not** sufficient and returns `403 FORBIDDEN`. Address
verification is opt-in to prevent accidental metered usage. A key can have both kinds
of access.

```bash
curl -X POST https://shipwave.app/api/v1/addresses/verify \
  -H "Authorization: Bearer sw_live_abc..." \
  -H "Content-Type: application/json" \
  -d '{"address":{"street1":"1600 Pennsylvania Ave NW","city":"Washington","state":"DC","zip":"20500"}}'
```

## Pricing

| Operation | Rate (after free tier) |
|-----------|------------------------|
| `verify` (single) | **$0.02 / lookup** |
| `verify-batch` (per entry) | **$0.02 / lookup** |
| `parse` | **$0.005 / lookup** |

- **Free tier:** the first 100 new lookups per account per calendar month (UTC),
  across verify, verify-batch, and parse.
- **Past the free tier:** add a card in ShipWave under **Settings → API Keys**. Usage is
  billed monthly through Stripe. Without a card, new lookups return
  `402 PAYMENT_REQUIRED` (batch entries fail individually) until you add a card or the
  next month starts. If your address billing is past due, new lookups past the free tier
  also return `402` until you update your card.
- **What counts:** only new lookups that succeed. Cached repeats, requests rejected with
  `400`, `402`, or `502`, and batch entries that fail are not counted or billed.
- **Cache:** identical inputs within 24 hours return the earlier result and are
  **never billed** (`costCents: 0`, `cached: true`). See [Caching](#caching).
- **Usage:** every successful response reports `costCents` for that lookup. Non-cached
  responses also report `freeTierRemaining` (free lookups left this month); in
  verify-batch it is in `summary`.

## Rate Limits

- **60 requests per minute** per API key, shared with the key's other ShipWave API calls.
  A verify-batch call counts as one request.
- Responses that pass the key and scope checks include `X-RateLimit-Limit`,
  `X-RateLimit-Remaining`, and `X-RateLimit-Reset` headers.
  See [Rate Limiting](rate-limiting.md).

## Endpoints

### Verify a Single Address

```
POST /api/v1/addresses/verify
```

#### Request Body

```json
{
  "address": {
    "name": "Jane Smith",                  // optional
    "company": "Acme Co",                  // optional
    "street1": "1600 Pennsylvania Ave NW",
    "street2": "Suite 100",                // optional
    "city": "Washington",
    "state": "DC",                         // required for US/PR only
    "zip": "20500",                        // required for US/PR only
    "country": "US"                        // optional, defaults to "US"
  }
}
```

#### Response

```json
{
  "data": {
    "verified": {
      "street1": "1600 PENNSYLVANIA AVE NW",
      "street2": null,
      "city": "WASHINGTON",
      "state": "DC",
      "zip": "20500-0005",
      "country": "US",
      "deliverable": true,
      "residential": false,
      "correctedFields": ["zip"],
      "messages": []
    },
    "cached": false,
    "lookupId": "clxyz...",
    "costCents": 0,
    "freeTierRemaining": 87
  }
}
```

A cached response has `"cached": true`, `"costCents": 0`, the original `lookupId`, and
no `freeTierRemaining`.

#### Example

```bash
curl -X POST https://shipwave.app/api/v1/addresses/verify \
  -H "Authorization: Bearer sw_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "address": {
      "street1": "1600 Pennsylvania Ave NW",
      "city": "Washington",
      "state": "DC",
      "zip": "20500"
    }
  }'
```

---

### Batch Verify (up to 100)

```
POST /api/v1/addresses/verify-batch
```

Each address is verified independently and billed individually. The endpoint returns
200 even when some entries fail; check `results[i].ok` for each entry.

#### Request Body

Each entry is an address object with the same fields as `address` in
[Verify a Single Address](#verify-a-single-address).

```json
{
  "addresses": [
    { "street1": "...", "city": "...", "state": "CA", "zip": "94103" },
    { "street1": "...", "city": "...", "state": "NY", "zip": "10001" }
  ]
}
```

`addresses` must be a non-empty array of at most **100** addresses. An empty or missing
array, or a larger batch, returns `400 VALIDATION_ERROR` for the whole request.

#### Response

```json
{
  "data": {
    "results": [
      {
        "index": 0,
        "ok": true,
        "verified": { /* same shape as verify */ },
        "cached": false,
        "lookupId": "clxyz...",
        "costCents": 2
      },
      {
        "index": 1,
        "ok": false,
        "error": { "code": "VALIDATION_ERROR", "message": "Missing required address fields: state", "fields": ["state"] }
      }
    ],
    "summary": {
      "total": 2,
      "ok": 1,
      "errors": 1,
      "totalCostCents": 2,
      "freeTierRemaining": 0
    }
  }
}
```

`index` is the entry's position in your `addresses` array. `totalCostCents` is the sum of
`costCents` across the batch.

#### Per-entry error codes

| `error.code` | Cause |
|--------------|-------|
| `VALIDATION_ERROR` | Required fields are missing (`fields` lists them), or the provider rejected the address, for example an unsupported country (no `fields`) |
| `PAYMENT_REQUIRED` | The free tier is used up and no card is on file, or address billing is past due |
| `UPSTREAM_ERROR` | The verification provider was unavailable for this entry; retry it |

---

### Parse a Free-Text Address String (US only)

```
POST /api/v1/addresses/parse
```

Splits a US-formatted address string (`street, city, ST ZIP`) into fields. It doesn't
verify the address; pass the parsed fields to `/verify` for that. Non-US strings are not
supported: they get a low `confidence` and `country: "US"`.

#### Request Body

```json
{ "raw": "1600 Pennsylvania Ave NW, Washington, DC 20500" }
```

`raw` must be a non-empty string.

#### Response

```json
{
  "data": {
    "parsed": {
      "name": null,
      "company": null,
      "street1": "1600 Pennsylvania Ave NW",
      "street2": null,
      "city": "Washington",
      "state": "DC",
      "zip": "20500",
      "country": "US",
      "confidence": 1,
      "warnings": []
    },
    "cached": false,
    "lookupId": "clxyz...",
    "costCents": 0,
    "billedRate": "0.5¢/parse",
    "freeTierRemaining": 86
  }
}
```

- `costCents` is `0` within the free tier and `0.5` for a billed parse.
- `name` and `company` are always `null`, and `country` is always `"US"`.
- Text between the street and the city (`street, unit, city, ST ZIP`) goes into `street2`.
- `confidence` is 0.0–1.0. Values below 0.6 mean one or more fields couldn't be
  identified cleanly; review the result before calling `/verify`.
- `warnings` can contain `zip_not_found`, `state_not_found`, `city_not_found`, and
  `street_not_found`.
- A cached response has `"cached": true`, `"costCents": 0`, the original `lookupId`, and
  no `billedRate` or `freeTierRemaining`.

---

## Errors

All errors follow the standard envelope:

```json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Missing required address fields: zip",
    "details": { "fields": "zip" }
  }
}
```

For missing fields on `/verify`, `details.fields` is a comma-separated string, for
example `"street1,city"`.

| Code | HTTP | Meaning |
|------|------|---------|
| `UNAUTHORIZED` | 401 | Missing, invalid, revoked, or expired API key |
| `FORBIDDEN` | 403 | API key lacks the `addresses:verify` scope |
| `VALIDATION_ERROR` | 400 | Body isn't valid JSON, a required field is missing, the batch is empty or over 100, or the provider rejected the address (for example an unsupported country) |
| `PAYMENT_REQUIRED` | 402 | Free tier used and no card on file, or address billing is past due. `details.reason` is `free_tier_exhausted` or `billing_past_due`, and `details.billingUrl` links to Settings → API Keys. |
| `RATE_LIMITED` | 429 | More than 60 requests in a minute on this key |
| `INTERNAL_ERROR` | 502 | `/verify` only: the verification provider was unavailable; retry shortly |
| `INTERNAL_ERROR` | 500 | Unexpected server error |

`402` and `502` apply to `/verify` and `/parse` as whole-request errors. In
`/verify-batch` they appear per entry instead (see
[Per-entry error codes](#per-entry-error-codes)). `/parse` never returns `502`.

## Caching

- Two `verify` or `verify-batch` inputs are identical when `street1`, `street2`, `city`,
  `state`, `zip`, and `country` match after trimming whitespace and ignoring case.
  `name` and `company` are ignored. `verify` and `verify-batch` share one cache.
- `parse` inputs are identical when the `raw` strings match after trimming whitespace and
  ignoring case. Parse results are cached separately from verifications.
- TTL: **24 hours** from the original lookup. A cache hit returns that original result;
  it isn't re-verified.
- The cache is per account. One account's lookups are never served to another.
- Cache hits return `cached: true` and `costCents: 0`, reuse the original `lookupId`, and
  don't count toward the free tier.

## Programmatic Usage

```typescript
async function verifyAddress(input) {
  const res = await fetch("https://shipwave.app/api/v1/addresses/verify", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.SHIPWAVE_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ address: input }),
  });
  if (!res.ok) throw new Error(`${res.status}: ${(await res.json()).error?.message}`);
  return (await res.json()).data;
}
```
