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 key_availability need a Management Key, passed to IdealPostcodes::Client.new as management_key:.
Key availability
Call key_availability. It needs only the API key and costs nothing, so it suits a health check.
require "ideal_postcodes"
client = IdealPostcodes::Client.new(api_key: "ak_test")
key = client.key_availability("ak_test").result
puts key.available
key.contexts.each { |country| puts country.iso_3 }
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.
Lookup balance
key_details returns lookups_remaining, the daily, monthly and per-IP limits, allowed URLs, notification settings and datasets.
require "ideal_postcodes"
client = IdealPostcodes::Client.new(api_key: "ak_test", management_key: ENV.fetch("IDPC_MANAGEMENT_KEY"))
details = client.key_details("ak_test").result
puts "#{details.lookups_remaining} lookups left, daily limit #{details.daily_limit.limit || 'none'}"
Update limits
Call update_key_details with only the settings to change. The rest stay as they are.
client.update_key_details(
"ak_test",
daily_limit: { "limit" => 1000 },
allowed_urls: ["https://www.example.com"]
)
Nested settings use the API's own field names. A keyword left out, or passed as nil, is not sent. Inside a nested setting nil becomes JSON null, so daily_limit: { "limit" => nil } removes the daily limit, allowed_urls: [] removes the URL restriction and notifications: { "enabled" => false } stops notification emails. See update_key_details for every field.
Usage export
key_usage returns totals and a daily breakdown. key_logs returns each billable lookup as a CSV string. Both take start: and end: as UNIX timestamps in milliseconds.
require "ideal_postcodes"
client = IdealPostcodes::Client.new(api_key: "ak_test", management_key: ENV.fetch("IDPC_MANAGEMENT_KEY"))
now = (Time.now.to_f * 1000).to_i
week_ago = now - (7 * 86_400_000)
usage = client.key_usage("ak_test", start: week_ago, end: now).result
usage.daily_count.each { |day| puts "#{day.date}: #{day.count}" }
File.write("lookups.csv", client.key_logs("ak_test", start: week_ago, end: now))
end: works as a keyword argument even though end is a Ruby keyword. Pass licensee: as well to report one licensee's usage.