Metadata-Version: 2.5
Name: oxisms
Version: 1.0.0
Summary: Official Python library for the OxiSMS API (send SMS, track deliveries, manage senders and exclusion lists)
Project-URL: Homepage, https://github.com/oxemis/oxisms-python
Project-URL: Documentation, https://api.oxisms.com/doc/
Project-URL: Changelog, https://github.com/oxemis/oxisms-python/blob/main/CHANGELOG.md
Author-email: Oxemis <support@oxemis.com>
License-Expression: MIT
License-File: LICENSE
Keywords: api,oxemis,oxisms,sms,text message
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Communications :: Telephony
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.24
Provides-Extra: dev
Requires-Dist: mypy>=1.8; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: ruff>=0.4; extra == 'dev'
Description-Content-Type: text/markdown

# Official OxiSMS Python Library

![MIT License](https://img.shields.io/badge/license-MIT-007EC7.svg?style=flat-square)
![Current Version](https://img.shields.io/badge/version-1.0.0-green.svg)
![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)

## Overview

This repository contains the official Python library for the [OxiSMS API](https://api.oxisms.com/doc/).
You don't have to know how the API works to use it: every route is available through typed Python objects,
documented with docstrings.

To get started, create an account on [account.oxemis.com](https://account.oxemis.com/) (a free trial is available).

## What is OxiSMS?

OxiSMS is a solution designed to let you **send your SMS quickly and easily**, from our web application,
our software, or your own programs with this library.

We offer worldwide coverage and sender personalization when it is allowed by the operators of your recipients
(see [the destinations](https://faq.oxemis.com/en/faq/oxisms/to-which-destinations-can-i-send-my-sms-messages/)).
All our SMS are sent via **Premium routes**, for the best possible deliverability.

We're a small team, but we're recognized for the quality of our support and expertise.

## Table of contents

- [Requirements](#requirements)
- [Installation](#installation)
- [Quick start](#quick-start)
- [Authentication and client options](#authentication-and-client-options)
- [Getting information about your account](#getting-information-about-your-account)
- [Sending SMS](#sending-sms)
  - [Your first SMS](#your-first-sms)
  - [Customized messages](#customized-messages)
  - [Using a custom sender](#using-a-custom-sender)
  - [How many characters can I put in my message?](#how-many-characters-can-i-put-in-my-message)
  - [How many credits will a sending use?](#how-many-credits-will-a-sending-use)
  - [Choosing the strategy](#choosing-the-strategy)
  - [Scheduling a sending](#scheduling-a-sending)
  - [Letting your recipients reply](#letting-your-recipients-reply)
  - [Shortening a URL](#shortening-a-url)
- [Tracking your messages](#tracking-your-messages)
  - [Status of a sending](#status-of-a-sending)
  - [Status over a period (pagination)](#status-over-a-period-pagination)
  - [Replies](#replies)
  - [Statistics](#statistics)
- [History of your sendings](#history-of-your-sendings)
- [Unsubscribe list and bounce list](#unsubscribe-list-and-bounce-list)
- [Phone number analysis](#phone-number-analysis)
- [Error handling](#error-handling)
- [Dates and time zones](#dates-and-time-zones)
- [Testing your code without calling the API](#testing-your-code-without-calling-the-api)
- [Links](#links)
- [Contribute](#contribute)

## Requirements

- **Python 3.10** or higher;
- [httpx](https://www.python-httpx.org/) 0.24 or higher (installed with the library, its only dependency).

## Installation

```bash
pip install oxisms
```

## Quick start

```python
import os

from oxisms import Message, OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

message = Message(text="Hi there! This is my first SMS sent with the oxisms Python library.")
message.add_recipient("+33600000001")

sending = client.send_api.send(message)
print(f"Sending ID: {sending.sending_id}, cost: {sending.total_cost} credit(s)")
```

## Authentication and client options

You can create your API keys in your [Oxemis account](https://account.oxemis.com).
We recommend keeping them out of your code, in environment variables:

```bash
export OXISMS_API_LOGIN='your API login'
export OXISMS_API_PWD='your API password'
```

```python
import os

from oxisms import OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

# Optional settings (keyword arguments), all optional:
client = OxiSmsClient(
    os.environ["OXISMS_API_LOGIN"],
    os.environ["OXISMS_API_PWD"],
    timeout=30,              # maximum duration of a request, in seconds (default 30)
    connect_timeout=10,      # maximum duration to connect, in seconds (default 10)
    max_retries=3,           # retries on "429 Too Many Requests", honoring Retry-After (default 3, 0 to disable)
    user_agent="MyApp/2.0",  # added at the end of the User-Agent header: "oxisms-python/1.0.0 (Python 3.13.1) MyApp/2.0"
    # base_url="https://api.oxisms.com",  # URL of the API
    # transport=...,                      # an httpx transport, for your tests (see below)
    # http_client=httpx.Client(...),      # your own httpx client (proxies, certificates...)
)
```

With `http_client`, the settings of your client apply (`timeout`, `connect_timeout` and `transport` are then
ignored) and the library does not close it.

The client keeps its connections open between calls. Use it as a context manager (or call `client.close()`)
to close them when you are done:

```python
with OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"]) as client:
    print(client.user_api.get_user().credits)
```

The client gives access to every feature of the API through these attributes:

| Attribute         | What for                                                                      |
|-------------------|-------------------------------------------------------------------------------|
| `user_api`        | your account: company name, credits, rates                                    |
| `send_api`        | send SMS now or later, compute their cost, list and cancel scheduled sendings |
| `senders_api`     | your custom senders                                                           |
| `tracking_api`    | delivery status, replies of your recipients, statistics                       |
| `history_api`     | the sendings made on your account                                             |
| `blacklists_api`  | your unsubscribe list (historical name of the route)                          |
| `bounces_api`     | your bounce list (invalid numbers)                                            |
| `tools_api`       | phone number analysis, URL shortener, health check of the API                 |

Every object returned by the library is a frozen dataclass with typed attributes (the package ships its
type hints: `mypy --strict` and your IDE know every field).

## Getting information about your account

```python
import os

from oxisms import OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])
user = client.user_api.get_user()

print(f"Name: {user.company_name}")
print(f"Remaining credits: {user.credits}")

# Last day of validity of your credits, INCLUDED (None if they don't expire)
if user.credits_valid_before is not None:
    print(f"Valid until: {user.credits_valid_before:%Y-%m-%d} (included)")
if not user.is_credits_valid_on():
    print("Your credits have expired.")

# Rates: cost in credits of one SMS, per destination
for rate in user.rates:
    print(f"{rate.country} (+{rate.country_code}): {rate.cost} credit(s)")
print(f"France: {user.get_rate_for_country_code(33)} credit(s) per SMS")
```

> `credits` is a float: some destinations cost more than one credit per SMS (1.7 for example), so your balance
> may have decimals.

## Sending SMS

### Your first SMS

Build a `Message`, then send it with `client.send_api.send()`:

```python
import os

from oxisms import Message, OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

message = Message(
    text="Hi there! This is my first SMS sent with the oxisms Python library.",
    campaign_name="Welcome",  # optional, groups your sendings in your history and statistics
)
message.add_recipient("+33600000001").add_recipient("+33600000002")

sending = client.send_api.send(message)

print(f"Sending ID: {sending.sending_id}")  # to follow it with tracking_api
print(f"Cost: {sending.total_cost} credit(s)")

for recipient in sending.ok_recipients:
    print(f"{recipient.msisdn}: message {recipient.token}")
for recipient in sending.filtered_recipients:
    # FILTERED_UNSUBSCRIBED, FILTERED_BOUNCED or FILTERED_NOT_COVERED
    print(f"{recipient.phone_number} was removed: {recipient.filtered_reason}")
for recipient in sending.invalid_recipients:
    print(f"{recipient.phone_number} is not a valid number")
```

Phone numbers should be given in international format (`+33600000001` or `33600000001`); French national
numbers (`0600000001`) are also accepted. If no valid recipient is left, nothing is sent and `sending_id` is
`None`.

### Customized messages

Every `{{Name}}` in the text is replaced by the meta data `Name` of each recipient:

```python
import os

from oxisms import Message, OxiSmsClient, Recipient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

message = Message(
    text="Hi {{Name}}! This is your ID: {{ID}}",
    recipients=[
        Recipient("+33600000001", {"Name": "Joe", "ID": 1}),
        Recipient("+33600000002", {"Name": "Jane", "ID": 2}),
    ],
)
# Same thing, one by one: message.add_recipient("+33600000003", {"Name": "Ann", "ID": 3})

# Two messages in one call: "Hi Joe! This is your ID: 1" and "Hi Jane! This is your ID: 2"
client.send_api.send(message)
```

> If a merge field is missing for some recipients, the sending is refused with an `OxiSmsError` whose `reason`
> is `UNKNOWN_MERGE_FIELDS` (see [Error handling](#error-handling)).

### Using a custom sender

By default, SMS are sent with a short code (36xxx in France for example). You can display your own sender
instead:

- an **alphanumeric sender**: 3 to 11 characters (letters A-Z, digits, spaces), with at least one letter.
  It **must first be added to your senders and validated by our team**;
- a **numeric sender**: 3 to 15 digits.

Some operators don't accept custom senders: a short code is then used. With the `commercial` strategy,
an unsubscribe mention is added to your message ("STOP au 36111" for example), which makes it longer.

```python
import os

from oxisms import Message, OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

# 1. Add the sender (once): it stays pending until our team validates it
result = client.senders_api.add_sender("MyShop")
if not result.is_success:
    print(result.errors)  # e.g. {"My Shop": "Invalid sender: must be alphanumeric, no spaces, ..."}

# 2. Check its status
senders = client.senders_api.get_senders()
print(senders.validated)  # usable senders
print(senders.pending)    # waiting for validation
print(senders.blocked)    # refused (contact the support to know why)

# 3. Use it
if senders.is_validated("MyShop"):
    message = Message(text="Your order is ready!", sender="MyShop").add_recipient("+33600000001")
    client.send_api.send(message)

# Remove a sender (the result tells whether it was refused, like add_sender())
client.senders_api.delete_sender("OldName")
```

### How many characters can I put in my message?

It depends on the encoding (see [What is encoding?](https://faq.oxemis.com/en/faq/oxisms/what-is-encoding/)):

- **GSM** (letters, digits, common punctuation and some accents): up to **160 characters** per SMS;
- **Unicode** (emojis, other accents such as `ê`...): up to **70 characters** per SMS;
- longer messages are sent as a **long SMS** of up to 8 parts, displayed as one message on the phone;
  each part then holds **153 characters** (GSM) or **67 characters** (Unicode), and costs one SMS.

Keep the default `ENCODING_AUTO`: OxiSMS uses GSM when the text allows it, Unicode otherwise.
You can force it with `encoding=ENCODING_GSM` (characters outside the GSM alphabet are replaced, `ê` becomes
`e`) or `encoding=ENCODING_UNICODE`.
More details in the [FAQ](https://faq.oxemis.com/en/faq/oxisms/what-is-the-maximum-number-of-characters-of-a-text-message/).

```python
from oxisms import ENCODING_UNICODE, Message

message = Message(text="Merry Christmas 🎄", encoding=ENCODING_UNICODE)  # or Message.ENCODING_UNICODE
```

### How many credits will a sending use?

Use `get_cost_of_message()`: nothing is sent and no credit is used.

```python
import os

from oxisms import Message, OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

message = Message(text="Our sales start tomorrow!")
message.add_recipient("+33600000001").add_recipient("+32470000001")

cost = client.send_api.get_cost_of_message(message)
print(f"This sending will use {cost.total_cost} credit(s), you have {cost.credits}")
if cost.insufficient_credits:
    print("Not enough credits: the sending would be refused.")
for recipient in cost.ok_recipients:
    print(f"{recipient.msisdn}: {recipient.cost} credit(s), {recipient.encoding}")
```

You can also set a maximum with `max_credits_per_sending`: if the sending would cost more, it is refused.

```python
from oxisms import OxiSmsError

message.max_credits_per_sending = 1

try:
    client.send_api.send(message)
except OxiSmsError as e:
    # Code 406: "Total credits needed to send the message (2) exceeds the MaxCreditsPerSending parameter (1)."
    print(f"{e.code}: {e.message}")
```

### Choosing the strategy

| Strategy                    | Use it for                                                         | Restrictions                                                                                                                                                                  |
|-----------------------------|--------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **Commercial** (default)    | **marketing** messages, i.e. anything that promotes your activities or events, even free ones | Not sent after 9:00 p.m., before 8:00 a.m., on Sundays and public holidays. **They are not rejected**: they are automatically postponed to the next allowed period. |
| **Notification**            | **notifications** (password reset, two-factor code, appointment reminder...) | None                                                                                                                                                                           |

> **Please be very careful selecting the strategy.** Sending marketing messages with the "notification" strategy
> will probably get your account locked because of complaints from your recipients.
> See [What strategy should I choose?](https://faq.oxemis.com/en/faq/oxisms/what-strategy-should-i-choose-to-send-my-sms-messages/)

```python
import os
import secrets

from oxisms import STRATEGY_NOTIFICATION, Message, OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])
two_factor_code = 100000 + secrets.randbelow(900000)

message = Message(text=f"Here is your code to authenticate: {two_factor_code}", strategy=STRATEGY_NOTIFICATION)
message.add_recipient("+33600000001")

client.send_api.send(message)
```

### Scheduling a sending

The date must be at least 5 minutes away and no more than 90 days away. The credits are used when the sending
is scheduled and given back if you cancel it.

```python
import os
from datetime import datetime, timedelta

from oxisms import Message, OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

tomorrow_evening = (datetime.now().astimezone() + timedelta(days=1)).replace(hour=18, minute=0, second=0)
message = Message(
    text="Reminder: your appointment is tomorrow at 10:00.",
    scheduled_datetime=tomorrow_evening,
).add_recipient("+33600000001")
sending = client.send_api.send(message)

# List the scheduled sendings (empty list if there is none)
for scheduled in client.send_api.get_scheduled():
    print(f"{scheduled.sending_id} on {scheduled.scheduled_datetime}: "
          f"{scheduled.nb_sms} SMS, {scheduled.cost} credit(s)")

# Cancel one (raises an OxiSmsError, code 404, if it is unknown or no longer scheduled)
client.send_api.delete_scheduled(sending.sending_id)
```

### Letting your recipients reply

With the reply mode, your recipients can answer your SMS (a custom sender can't be used with it).
See [How does the response mode work?](https://faq.oxemis.com/en/faq/oxisms/how-does-the-response-mode-work/)

```python
import os

from oxisms import Message, OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

message = Message(text="Will you attend our meeting on Friday? Answer YES or NO.", allow_reply=True)
message.add_recipient("+33600000001")
sending = client.send_api.send(message)

# Later: read the replies (see "Replies" below)
for reply in client.tracking_api.get_replies_for_sending(sending.sending_id):
    print(f"{reply.from_} answered: {reply.message}")
```

### Shortening a URL

Short URLs save characters, and some URLs refused by the operators (other URL shorteners for example) are made
safe:

```python
import os

from oxisms import Message, OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

url = client.tools_api.shorten_url("https://www.example.com/sales/2026/winter?utm_source=sms")
print(url.shortened_url)      # with "https://"
print(url.shortened_url_sms)  # without "https://": the one to put in your SMS

message = Message(text=f"Our winter sales: {url.shortened_url_sms}").add_recipient("+33600000001")
client.send_api.send(message)
```

## Tracking your messages

### Status of a sending

Each message gets a `status_state`, which tells what its (many) status codes mean:
`delivered`, `pending` (still on its way, or no delivery receipt yet), `failed` or `unknown`.

```python
import os

from oxisms import STATE_FAILED, OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

for status in client.tracking_api.get_status_by_sending_id("abc1234def"):
    print(f"{status.recipient}: {status.status_state} ({status.status_desc})")
    if status.status_state == STATE_FAILED:  # or status.is_failed
        ...

# One message (token returned by send()), or every message sent to a number
status = client.tracking_api.get_status_by_token("1234abc567")  # None if unknown
statuses = client.tracking_api.get_status_by_recipient("33600000001")

# Every possible status code, with its description
for definition in client.tracking_api.get_status_list():
    print(f"{definition.status_code}: {definition.status_desc_detail}")
```

### Status over a period (pagination)

You can get the status of every message sent over a period of up to 31 days (start included, end excluded).
The results are paged (up to 10,000 messages per page). `get_status_for_period()` reads every page for you,
as you iterate:

```python
import os
from datetime import datetime
from zoneinfo import ZoneInfo

from oxisms import OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

paris = ZoneInfo("Europe/Paris")
start = datetime(2026, 11, 1, tzinfo=paris)
end = datetime(2026, 12, 1, tzinfo=paris)

for status in client.tracking_api.get_status_for_period(start, end):
    print(f"{status.sent_on} {status.recipient}: {status.status_state}")
```

Or page by page, if you want to stop and resume later (the next page is given by the `X-Next-After` header of
the API, in `next_after`):

```python
after = None
while True:
    page = client.tracking_api.get_status_page(start, end, after, 1000)
    for status in page:
        ...
    if not page.has_more:
        break
    after = page.next_after
```

### Replies

Replies are available for the messages sent with `allow_reply=True` (they are not paged):

```python
import os
from datetime import datetime, timedelta

from oxisms import OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

replies = client.tracking_api.get_replies_for_sending("abc1234def")  # replies to a sending
replies = client.tracking_api.get_replies_for_message("1234abc567")  # replies to one message
now = datetime.now().astimezone()
replies = client.tracking_api.get_replies_for_period(now - timedelta(days=7), now)  # 31 days max

for reply in replies:
    print(f"{reply.received_on} {reply.from_}: {reply.message}")
```

### Statistics

Delivery counters per sending, already computed: use them instead of the status of each message whenever you
need an overview.

```python
import os
from datetime import datetime

from oxisms import OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

# Some sendings...
stats = client.tracking_api.get_statistics(["abc1234def", "ghi5678jkl"])
# ...or every sending of a period (the period actually used is in start_date / end_date)
stats = client.tracking_api.get_statistics_for_period(
    datetime(2026, 11, 1).astimezone(), datetime(2026, 11, 30).astimezone()
)

for sending in stats:
    print(f"{sending.sending_id}: {sending.nb_delivered}/{sending.nb_messages} delivered, "
          f"{sending.nb_failed} failed, {sending.nb_pending} pending")
print(stats.totals)                 # sum of the counters of all the sendings
print(stats.sending_ids_not_found)  # unknown sendings are not an error
```

## History of your sendings

```python
import os
from datetime import datetime

from oxisms import HISTORY_TYPE_API, OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

# Without dates: the last 7 days
history = client.history_api.get_history(
    datetime(2026, 11, 1).astimezone(),
    datetime(2026, 11, 30).astimezone(),
    type=HISTORY_TYPE_API,  # optional: HISTORY_TYPE_ALL (default), HISTORY_TYPE_CAMPAIGN or HISTORY_TYPE_API
    # source=HISTORY_SOURCE_APP,  # optional: HISTORY_SOURCE_SOFTWARE, HISTORY_SOURCE_APP or HISTORY_SOURCE_API
)

print(f"From {history.start_date} to {history.end_date}")
for sending in history:
    print(f"{sending.sent_on} {sending.campaign}: "
          f"{sending.total_recipients} recipient(s), {sending.total_cost} credit(s)")

# One sending (searched in the last 7 days unless you give the dates); None if not found
sending = client.history_api.get_sending(
    "abc1234def", datetime(2026, 10, 1).astimezone(), datetime(2026, 11, 30).astimezone()
)
```

The filters are also available on the class: `HistoryAPI.TYPE_API`, `HistoryAPI.SOURCE_APP`...
The values of `HistoryEntry.type` and `HistoryEntry.source` are `HistoryEntry.TYPE_CAMPAIGN` / `TYPE_API` and
`HistoryEntry.SOURCE_SOFTWARE` / `SOURCE_APP` / `SOURCE_API`.

## Unsubscribe list and bounce list

Numbers of your **unsubscribe list** (`blacklists_api`: recipients who answered STOP, or numbers you added) and
of your **bounce list** (`bounces_api`: invalid numbers) are automatically removed from your sendings.

```python
import os

from oxisms import ExclusionEntry, OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

# Numbers, indexed by their ID ({} if the list is empty)
numbers = client.blacklists_api.get_blacklisted_phone_numbers()

# Entries with the date they were added and their origin
entries = client.blacklists_api.get_blacklist_entries()
for entry in entries:
    origin = "answered STOP" if entry.source == ExclusionEntry.SOURCE_SMS else "added manually"
    print(f"{entry.phone_number} added on {entry.date_added} ({origin})")
if entries.details_complete is False:
    print("Some details are not available yet, ask again later.")

# Only the numbers added since your last call
newer = client.blacklists_api.get_blacklist_entries(entries.last_id or -1)

# Add or remove numbers: one number, a list, or numbers separated by ";"
result = client.blacklists_api.add_to_blacklist(["+33600000002", "+33600000003"])
print(result.is_success)  # True if every number was accepted
print(result.ok)          # numbers added
print(result.errors)      # numbers refused
client.blacklists_api.remove_from_blacklist("+33600000002")

# Same methods for the bounce list
client.bounces_api.get_bouncelist_entries()
client.bounces_api.add_to_bouncelist("+33600000009")
client.bounces_api.remove_from_bouncelist("+33600000009")
```

The numbers you add or remove are sent in the body of the requests, never in the URL (they are personal data).
Several numbers can be given as a list or as a string separated by `;`.

## Phone number analysis

Check the format of numbers before sending (their existence is not checked):

```python
import os

from oxisms import OxiSmsClient

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

# Second parameter: the country the numbers are called from, for numbers in national format (default "FR")
for info in client.tools_api.get_phone_numbers_info(["06.00.00.00.01", "+32470000001", "123"], "FR"):
    kind = "mobile" if info.is_mobile else "not mobile"
    validity = "valid" if info.is_valid else "invalid"
    print(f"{info.original_phone_number} => {info.msisdn} ({info.country_iso}, {kind}, {validity})")

# One number (None if the API gives nothing back)
info = client.tools_api.get_phone_number_info("0600000001")

# Is the API up? (no authentication needed)
print(client.tools_api.is_api_healthy())
```

## Error handling

Every error of the API, and every network error, is an `oxisms.OxiSmsError`:

| Attribute          | Content                                                                                          |
|--------------------|--------------------------------------------------------------------------------------------------|
| `code`             | the code sent by the API: the HTTP status (400, 401, 403, 404, 406...); 0 for a network error; 666 (`CODE_LIBRARY`) for an error detected by the library |
| `message`          | the message of the API, in English (also `str(e)`)                                               |
| `reason`           | the reason sent by the API (`UNKNOWN_MERGE_FIELDS`); `INVALID_ARGUMENT` or `INVALID_RESPONSE` for an error of code 666; None otherwise (HTTP error without reason, network error) |
| `details`          | the details of the reason (e.g. which merge fields are missing, for how many recipients)          |
| `http_status`      | the HTTP status (None for a network error)                                                        |
| `response_body`    | the raw answer of the API                                                                         |
| `is_network_error` | True for a DNS error, a timeout, a refused connection (the original exception is in `__cause__`) |

```python
import os

from oxisms import REASON_UNKNOWN_MERGE_FIELDS, Message, OxiSmsClient, OxiSmsError

client = OxiSmsClient(os.environ["OXISMS_API_LOGIN"], os.environ["OXISMS_API_PWD"])

message = Message(text="Hi {{FirstName}}!").add_recipient("+33600000001")  # no meta data "FirstName"

try:
    client.send_api.send(message)
except OxiSmsError as e:
    if e.is_network_error:
        print(f"The API could not be reached: {e}")
    elif e.reason == REASON_UNKNOWN_MERGE_FIELDS:
        for detail in e.details or []:
            print(f"Missing {detail['Field']} for {detail['MissingFor']} recipient(s)")
    else:
        print(f"Error {e.code}: {e.message}")
```

When the API answers `429 Too Many Requests`, the request is retried automatically (`max_retries` option),
after the delay given by its `Retry-After` header (up to 60 seconds).

Additions and removals answer item by item: they are not exceptions when some items are refused.
`add_to_blacklist()`, `remove_from_blacklist()`, `add_to_bouncelist()`, `remove_from_bouncelist()`, `add_sender()`
and `delete_sender()` return a `ListUpdateResult`: `is_success` is True only if every item was accepted, `errors`
lists the refused items. The other actions (`delete_scheduled()`) return None and raise an `OxiSmsError` when they
fail.

Invalid arguments are detected before any request and raise an `OxiSmsError` with code 666 and reason
`INVALID_ARGUMENT` (`REASON_INVALID_ARGUMENT`): an unknown encoding or strategy, an unknown history filter, no
criterion for `get_status()`, an empty list of numbers, a text that can't be encoded as UTF-8... An answer of the
API that is not valid JSON gives code 666 and reason `INVALID_RESPONSE`. Only an invalid option of the client
constructor (or a value of the wrong type) raises a standard `TypeError`.

## Dates and time zones

- Every instant returned by the library is a `datetime` **with its time zone**, as sent by the API.
- Calendar days (`User.credits_valid_before`) are `date` objects: the last day of validity, in Paris time,
  **included**. Use `user.is_credits_valid_on()` rather than comparing with the current time.
- The dates you give (periods, scheduled date) should have a time zone: `datetime.now().astimezone()`,
  `datetime(2026, 11, 1, tzinfo=ZoneInfo("Europe/Paris"))`... A naive datetime is read as the local time of your
  computer.

## Testing your code without calling the API

Give an [httpx mock transport](https://www.python-httpx.org/advanced/transports/#mock-transports) to the client
to simulate the answers of the API:

```python
import httpx

from oxisms import OxiSmsClient


def fake_api(request: httpx.Request) -> httpx.Response:
    assert request.url.path == "/user"
    return httpx.Response(200, json={"CompanyName": "ACME", "Credits": 100, "CreditsValidBefore": None, "Rates": []})


client = OxiSmsClient("login", "password", transport=httpx.MockTransport(fake_api))
print(client.user_api.get_user().company_name)  # "ACME", without any request to the API
```

## Links

- [API reference](https://api.oxisms.com/doc/)
- [OxiSMS FAQ](https://faq.oxemis.com/en/)
- [Oxemis APIs for developers](https://www.oxemis.com/en/api-developer)
- [Your account](https://account.oxemis.com)

## Contribute

Feel free to ask anything, and contribute to this project. To run the tests, the type checker and the linter:

```bash
pip install -e ".[dev]"
pytest
mypy --strict src
ruff check .
```

Need help? 👉 support@oxemis.com
