# AddrAPI Public API (v1)

Read-only Turkish address hierarchy: country → province → district → neighborhood → street, etc. Base path: `/v1`. All responses are JSON (`Accept: application/json` is recommended). Only `GET` is supported.

> **Base URL:** `https://api.addrapi.com`. The API is generally available; every `/v1` request needs a valid API key (a missing or invalid key is `401`). Keys are issued per organization by AddrAPI.

## Authentication

Send your API key as a Bearer token:

```
Authorization: Bearer <YOUR_API_KEY>
```

A key needs the `addresses:read` ability. Keys are shown once at creation; keep them secret and never put them in URLs.

## Location object

| Field | Meaning |
|---|---|
| `id` | Location id (**not** a plate/postal code) |
| `parent_id` | Parent location id, `null` for a country |
| `name` | Name (Turkish characters, upper-case for most records) |
| `type` | `1` country, `3` province, `4` district, `5` neighborhood, `6` street, `7` avenue, `8` boulevard, `9` village, `10` other |
| `status` | Always `1` (only active records are public) |

> `province_id=35` is the location **id** of İSTANBUL, not the plate code (plate 35 is İzmir, whose location id is 36). Look ids up with `/v1/locations/{id}/children` or `/v1/search`.

## Endpoints

### `GET /v1/countries`
Active countries. Query: `limit` (1–100, default 25), `cursor`.

```json
{"data":[{"id":1,"parent_id":null,"name":"Türkiye","type":1,"status":1}],"meta":{"per_page":25,"has_more":false,"next_cursor":null}}
```

### `GET /v1/locations/{id}`
One active location (`data` object). Unknown or inactive id → `404`; malformed id → `422`.

### `GET /v1/locations/{id}/children`
### `GET /v1/locations?parent_id={id}`
Direct active children of an active parent, ordered by `id`. Query: `type` (1–32767, optional filter), `limit` (1–100, default 25), `cursor`. Both forms return the same data.

`GET /v1/locations/388/children?limit=2`:

```json
{"data":[{"id":43629,"parent_id":388,"name":"RASİMPAŞA MAH.","type":5,"status":1},{"id":43630,"parent_id":388,"name":"KOŞUYOLU MAH.","type":5,"status":1}],"meta":{"per_page":2,"has_more":true,"next_cursor":"eyJpZCI6NDM2MzAsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0"}}
```

Pagination is cursor-based: pass `meta.next_cursor` as `cursor` for the next page; stop when `has_more` is `false`. There are no totals or page numbers. Cursors are opaque; a malformed one is a `422`.

### `GET /v1/search`
### `GET /v1/autocomplete`
Name search (Turkish-aware: `kadikoy` matches `KADIKÖY`). Same parameters; autocomplete returns shorter lists.

| Parameter | Required | Notes |
|---|---|---|
| `q` | yes | 2–120 characters, no control characters, at least 2 letters/digits |
| `country_id` | no | Location id of a country |
| `province_id` | no | Location id of a province (type 3) |
| `district_id` | no | Location id of a district (type 4) |
| `neighborhood_id` | no | Location id of a neighborhood (type 5) |
| `type` | no | One of `1,3,4,5,6,7,8,9,10` |
| `limit` | no | search: 1–50, default 20; autocomplete: 1–20, default 10 |

Filter ids must exist, be active and be of the type their parameter names; otherwise `422`. `country_id` must agree with the other given ids. There is no pagination: use more specific text or filters instead.

`GET /v1/search?q=kadikoy&province_id=35&type=4&limit=3`:

```json
{"data":[{"id":388,"parent_id":35,"name":"KADIKÖY","type":4,"status":1,"context":{"province":{"id":35,"name":"İSTANBUL"}}}],"meta":{"limit":3,"has_more":false,"partial":false}}
```

`context` holds the known ancestors (`province`, `district`, …); it is `{}` when there are none. Without the filter, the same query also returns `KADIKÖY MAH.` neighborhoods in other provinces (e.g. Bergama/İzmir).

### `meta.has_more`, `meta.partial` and the search cutoff
- `has_more: true` — more matches exist than `limit` returned.
- Searches have a server-side time limit. If the index stops at it, the answer is the best of what was found: `meta.partial` is `true`, `has_more` is `true` (completeness cannot be proven) and the response carries `X-Search-Partial: true`. Retrying with a longer or more specific `q`, or with filters, usually gives a complete answer.
- If the search index is unavailable the API returns `503` with `Retry-After: 5`.

## Rate limits

Per-minute limits apply to each API key and to the whole organization; both depend on your plan. Successful responses carry the headers of the more constrained limit:

```
X-RateLimit-Limit: 10
X-RateLimit-Remaining: 9
```

A refused request is `429` with `Retry-After` (seconds), `X-RateLimit-Limit` and `X-RateLimit-Remaining: 0`.

In addition, requests are limited per client IP address (120 per minute) before the key is checked; exceeding it is also a `429` with `Retry-After`.

## Monthly quota

Every **successful (2xx)** request counts as 1 unit against the organization's monthly quota. Errors (4xx/5xx) and rate-limited requests are not counted. The month is the UTC calendar month. Successful responses and quota `429`s include:

| Header | Meaning |
|---|---|
| `X-Quota-Limit` | Monthly limit |
| `X-Quota-Remaining` | Units left this month |
| `X-Quota-Reset` | Unix timestamp of the start of the next UTC month |

Used = `X-Quota-Limit − X-Quota-Remaining`. When the quota is used up, requests get `429` with code `quota_exceeded` and `Retry-After` counting down to the reset.

## Errors

All errors use one shape:

```json
{"error":{"code":"not_found","message":"Not Found"}}
```

| Status | `error.code` | When |
|---|---|---|
| 401 | `unauthorized` | Missing or invalid key (`WWW-Authenticate: Bearer`) |
| 403 | `forbidden` | Key lacks the required ability |
| 404 | `not_found` | Unknown URL or unknown/inactive location |
| 405 | `method_not_allowed` | Method other than `GET` on a real endpoint |
| 422 | `validation_failed` | Invalid parameters; field messages in `error.details` |
| 429 | `rate_limit_exceeded` / `quota_exceeded` | Per-minute limit / monthly quota |
| 503 | `service_unavailable` | Search index, rate limiter or usage recording unavailable; retry later |
| 500 | `internal_server_error` | Unexpected error (no details exposed) |

`400` is not used; malformed input is `422`.

```json
{"error":{"code":"validation_failed","message":"The given data was invalid.","details":{"q":["The q field is required."]}}}
```

## Examples

### cURL

```bash
curl -s -H "Authorization: Bearer $ADDRAPI_KEY" -H "Accept: application/json" \
  "https://api.addrapi.com/v1/search?q=kadikoy&province_id=35&type=4"
```

### PHP

```php
$ch = curl_init('https://api.addrapi.com/v1/search?'.http_build_query(['q' => 'kadikoy', 'province_id' => 35, 'type' => 4]));
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer '.getenv('ADDRAPI_KEY'), 'Accept: application/json'],
    CURLOPT_TIMEOUT => 10,
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);

if ($status === 200) {
    $result = json_decode($body, true, flags: JSON_THROW_ON_ERROR);
    foreach ($result['data'] as $location) {
        echo $location['id'], ' ', $location['name'], PHP_EOL;
    }
}
```
