# Client setup

### Mục tiêu

Trang này chuẩn hoá cách khởi tạo client, cấu hình, và xử lý lỗi.

### Mục lục nhanh

* [Cài API key](#cai-api-key)
* [Khởi tạo client](#khoi-tao-client)
* [Quy ước đặt tên (Python vs API)](#quy-uoc-dat-ten-python-vs-api)
* [Cấu hình HTTP (timeout/retry/base URL)](#cau-hinh-http-timeoutretrybase-url)
* [Xử lý lỗi](#xu-ly-loi)
* [Đóng session](#dong-session)

### Cài API key

Client đọc API key theo thứ tự ưu tiên:

1. Tham số `api_key` khi khởi tạo.
2. Biến môi trường `XAPIKEY`.
3. Biến môi trường `X_API_KEY`.

Client tự gọi `load_dotenv()`. Bạn có thể đặt key trong file `.env`.

{% hint style="info" %}
Tạo API key tại: `https://smtp.dev/tokens/`.
{% endhint %}

> Tip: local dev dùng `.env`. CI/CD nên set environment variables trực tiếp.

### Khởi tạo client

{% code title="basic.py" %}

```python
from smtppy import SMTPDevClient

client = SMTPDevClient(api_key="YOUR_API_KEY")

domains = client.list_domains()
print(domains)
```

{% endcode %}

### Quy ước đặt tên (Python vs API)

* Method và tham số trong Python dùng `snake_case`. Ví dụ: `list_domains(is_active=True)`.
* Field trong JSON payload/response từ API thường là `camelCase`. Ví dụ: `isActive`, `expiresAt`.

Client tự map đúng key khi gửi request. Bạn chỉ cần truyền tham số theo signature Python.

### Cấu hình HTTP (timeout/retry/base URL)

Cấu hình nằm trong `SMTPConfig`.

* `base_url` (mặc định `https://api.smtp.dev`)
* `timeout` (mặc định `30` giây)
* `max_retries` (mặc định `3`)
* `backoff_factor` (mặc định `0.3`)

{% code title="config.py" %}

```python
from smtppy import SMTPDevClient, SMTPConfig

config = SMTPConfig(
    base_url="https://api.smtp.dev",
    timeout=30,
    max_retries=3,
    backoff_factor=0.3,
)

client = SMTPDevClient(api_key="YOUR_API_KEY", config=config)
```

{% endcode %}

<details>

<summary>Retry strategy đang áp dụng</summary>

Client retry khi gặp các status code:

* `429`
* `500`, `502`, `503`, `504`

Client cho phép retry trên các method:

* `GET`, `POST`, `PATCH`, `PUT`, `DELETE`, ...

</details>

### Xử lý lỗi

Client có 3 nhóm exception chính:

* `SMTPDevAuthError`: thiếu API key.
* `SMTPDevAPIError`: request thất bại. Có thể đọc thêm:
  * `status_code`
  * `response_data` (nếu server trả JSON lỗi)
* `SMTPDevException`: base class.

{% code title="errors.py" %}

```python
from smtppy import SMTPDevClient
from smtppy import SMTPDevAPIError, SMTPDevAuthError

try:
    client = SMTPDevClient(api_key="bad-key")
    client.list_domains()
except SMTPDevAuthError as e:
    print("Missing key:", e)
except SMTPDevAPIError as e:
    print("HTTP status:", e.status_code)
    print("Response:", e.response_data)
    raise
```

{% endcode %}

### Đóng session

Client dùng `requests.Session()`.

* Gọi `client.close()` khi xong.
* Hoặc dùng context manager.

{% code title="with.py" %}

```python
from smtppy import SMTPDevClient

with SMTPDevClient(api_key="YOUR_API_KEY") as client:
    accounts = client.list_accounts(page=1)
    print(accounts)
```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://reno.gitbook.io/smtp-py/getting-started/client-setup.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
