Current section
Files
Jump to
Current section
Files
lib/codat/client.ex
defmodule Codat.Client do
@moduledoc """
The Codat API client.
A `%Codat.Client{}` holds configuration for authenticating and communicating
with the Codat API. Pass a client to any API function to use custom settings,
or omit it to use the global application config.
## Creating a Client
# From application config (reads :codat app config + CODAT_API_KEY env var)
client = Codat.Client.new()
# Explicit API key
client = Codat.Client.new(api_key: "your-api-key")
# Full custom configuration
client = Codat.Client.new(
api_key: "your-api-key",
base_url: "https://api.codat.io",
http_timeout: 60_000,
max_retries: 5
)
## Using a Client
# All API functions accept an optional client as the first argument
{:ok, companies} = Codat.Platform.Companies.list(client)
# Without a client, uses global application config
{:ok, companies} = Codat.Platform.Companies.list()
## Multi-Tenant Usage
Create one client per tenant to isolate API keys and configurations:
clients = Map.new(tenants, fn {id, key} ->
{id, Codat.Client.new(api_key: key)}
end)
{:ok, companies} = Codat.Platform.Companies.list(clients[tenant_id])
"""
alias Codat.Config
@type t :: %__MODULE__{config: Config.t()}
@enforce_keys [:config]
defstruct [:config]
@doc """
Creates a new `%Codat.Client{}` with the given options merged over application config.
Options are validated via `NimbleOptions`. See `Codat.Config.options_schema/0` for
the full list of supported keys.
## Examples
iex> Codat.Client.new(api_key: "abc123")
%Codat.Client{config: %Codat.Config{api_key: "abc123", ...}}
"""
@spec new(keyword()) :: t()
def new(opts \\ []) do
config = Config.new(opts)
%__MODULE__{config: config}
end
@doc """
Returns the underlying `%Codat.Config{}` for this client.
"""
@spec config(t()) :: Config.t()
def config(%__MODULE__{config: config}), do: config
@doc """
Returns the resolved API key for this client.
Raises if no API key is configured.
"""
@spec api_key!(t()) :: String.t()
def api_key!(%__MODULE__{config: config}), do: Config.resolve_api_key!(config)
end