# API keys

The key methods report whether a key can take requests, read or change its limits and export its usage. All of them except `keyAvailability()` need a [Management Key](/docs/sdks/php/setup.md#when-do-i-need-a-management-key), passed as the second argument to `IdealPostcodes::client()` or through `Factory::withManagementKey()`.

## Is my key working?

Call `keyAvailability()`. It needs only the API key and costs nothing, so it suits a health check.

availability.phpphp

```php
use IdealPostcodes\IdealPostcodes;

$client = IdealPostcodes::client('ak_test');
$key = $client->keyAvailability('ak_test')->result;

echo var_export($key->available, true), PHP_EOL;
foreach ($key->contexts as $country) {
    echo $country->iso3, PHP_EOL;
}
```

`available` is `false` when the key has no lookups left, has hit a daily limit or is called from a URL it does not allow. `contexts` lists the countries the key can search.

## How many lookups are left?

`keyDetails()` returns `lookupsRemaining`, the daily, monthly and per-IP limits, allowed URLs, notification settings and datasets.

details.phpphp

```php
use IdealPostcodes\IdealPostcodes;

$client = IdealPostcodes::client('ak_test', getenv('IDPC_MANAGEMENT_KEY'));
$details = $client->keyDetails('ak_test')->result;

echo $details->lookupsRemaining, ' lookups left, daily limit ', $details->dailyLimit->limit ?? 'none', PHP_EOL;
```

## How do I change a limit?

Call `updateKeyDetails()` with only the settings to change. The rest stay as they are.

update.phpphp

```php
use IdealPostcodes\IdealPostcodes;

$client = IdealPostcodes::client('ak_test', getenv('IDPC_MANAGEMENT_KEY'));
$client->updateKeyDetails('ak_test', [
    'daily_limit' => ['limit' => 1000],
    'allowed_urls' => ['https://www.example.com'],
]);
```

The body uses the API's own field names. `null` inside a nested setting becomes JSON `null`, so `['daily_limit' => ['limit' => null]]` removes the daily limit, `['allowed_urls' => []]` removes the URL restriction and `['notifications' => ['enabled' => false]]` stops notification emails. See [`updateDetails`](/docs/sdks/php/endpoints/update-key-details.md) for every field.

## How do I export usage?

`keyUsage()` returns totals and a daily breakdown. `keyLogs()` returns each billable lookup as a CSV string. Both take `start` and `end` as UNIX timestamps in milliseconds.

usage.phpphp

```php
use IdealPostcodes\IdealPostcodes;

$client = IdealPostcodes::client('ak_test', getenv('IDPC_MANAGEMENT_KEY'));
$range = ['start' => strtotime('-7 days') * 1000, 'end' => time() * 1000];

$usage = $client->keyUsage('ak_test', $range)->result;
foreach ($usage->dailyCount as $day) {
    echo $day->date, ': ', $day->count, PHP_EOL;
}

file_put_contents('lookups.csv', $client->keyLogs('ak_test', $range));
```

Pass `licensee` in the same array to report one [licensee's](/docs/sdks/php/licensees.md) usage.
