Metadata-Version: 2.5
Name: checkthatphone
Version: 1.0.0
Summary: Official Python client for the CheckThatPhone phone validation API — US & Canada carrier lookup, line type, TCPA litigator and state DNC screening
Project-URL: Homepage, https://checkthatphone.com
Project-URL: Documentation, https://checkthatphone.com/docs
Project-URL: Repository, https://github.com/CheckThatPhone/checkthatphone-python
Author-email: CheckThatPhone <hello@checkthatphone.com>
License-Expression: MIT
License-File: LICENSE
Keywords: carrier-lookup,dnc,litigator,nanp,phone-number,phone-validation,sms,tcpa
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Communications :: Telephony
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown

# checkthatphone

[![PyPI version](https://img.shields.io/pypi/v/checkthatphone)](https://pypi.org/project/checkthatphone/) [![CI](https://github.com/CheckThatPhone/checkthatphone-python/actions/workflows/ci.yml/badge.svg)](https://github.com/CheckThatPhone/checkthatphone-python/actions/workflows/ci.yml) [![python >= 3.9](https://img.shields.io/pypi/pyversions/checkthatphone)](https://pypi.org/project/checkthatphone/)

Official Python client for the [CheckThatPhone](https://checkthatphone.com) phone validation API. Look up US and Canadian phone numbers in real time: carrier, line type, whether the number was ported, and whether the line can receive texts. Add a TCPA litigator check, a landline SMS check, and free state do-not-call and complainer checks when you need them.

Version 1.0 calls API v2 and returns a new record. API v1 keeps working: to stay on it, stay on the 0.2.x releases of this package. See [Upgrading from 0.x](#upgrading-from-0x).

Zero dependencies (standard library only). Python 3.9+. Type hints included.

## Install

```bash
pip install checkthatphone
```

## Quick start

```python
import os
from checkthatphone import CheckThatPhone

client = CheckThatPhone(api_key=os.environ["CHECKTHATPHONE_API_KEY"])

result = client.lookup("(212) 555-0100")
data = result.data

data["number"]["valid"]          # True
data["number"]["line_type"]      # "mobile"
data["carrier"]["name"]          # "Test Wireless"
data["sms"]["line_can_receive"]  # True
result.credits_used              # 0, because 555-0100 is a test number
```

Get an API key at [checkthatphone.com](https://checkthatphone.com). The Free plan includes 500 credits a month. A lookup costs 1 credit, plus 1 for each paid check you add.

Write the number any common way: 10 digits, or 11 digits starting with 1. Other characters are ignored.

`result.data` is a plain dictionary. Three rules make it easy to read:

- A key never disappears. `None` means "not known".
- Values have real types: `True` and `False`, not `"true"` and `"false"`.
- Lists of allowed values (line types, statuses, reasons, error codes) can grow. Treat a value you do not know as the cautious case.

## Checks

A lookup runs no optional check unless you name it. Pass the names in `checks`:

```python
result = client.lookup("2125550104", checks=["litigator", "dnc_state", "dnc_complainer"])
```

| Check | Cost | What it does |
| --- | --- | --- |
| `litigator` | 1 credit, charged whenever it is requested | Checks the number against our TCPA litigator database. |
| `landline_sms` | 1 credit, charged only when the check ran (it does not run on mobile lines) | For a landline, checks whether the line is text-enabled. |
| `dnc_state` | Free | Checks the number against state do-not-call lists. It covers 38 states plus DC. It does not look at the federal Do Not Call registry. |
| `dnc_complainer` | Free | Checks the number against our list of people who have lodged complaints against telemarketers. |

The API refuses a name it does not know with the error code `unknown_check`. Nothing is looked up, so a typo can never skip a check silently.

## Reading the result

The record has seven groups:

| Group | What it holds |
| --- | --- |
| `number` | The number itself: how to write it, whether it exists, what kind of line it is. |
| `carrier` | The carrier that serves the number now. `None` for a number that is not assigned. |
| `sms` | Whether the line can take a text message. |
| `compliance` | The checks you asked for, each with its own status. |
| `location` | Where the number was issued. Not where the person is now. |
| `ip_location` | Where the IP address you sent is. `None` when you sent no `ip`. |
| `meta` | About the lookup: time, credits, request id. |

This is the full record for the lookup above, a litigator match on a mobile line:

```json
{
  "number": {
    "e164": "+12125550104",
    "national": "(212) 555-0104",
    "international": "+1 212-555-0104",
    "rfc3966": "tel:+1-212-555-0104",
    "valid": true,
    "invalid_reason": null,
    "line_type": "mobile",
    "ported": false,
    "deactivation_date": null,
    "original_carrier": null,
    "test_number": true
  },
  "carrier": {
    "name": "Test Wireless",
    "brand": "Test Wireless",
    "voip_wholesale": false,
    "ocn": "TEST",
    "lrn": "2125550104",
    "category": "WIRELESS"
  },
  "sms": {
    "line_can_receive": true,
    "reasons": [],
    "landline": { "status": "not_requested" }
  },
  "compliance": {
    "litigator": { "status": "checked", "match": true, "type": "litigator", "name": "Test Litigator" },
    "dnc_state": { "status": "checked", "listed": false },
    "dnc_complainer": { "status": "checked", "listed": false }
  },
  "location": {
    "country": "US",
    "region": "NY",
    "regions": ["NY"],
    "city": null,
    "rate_center": null,
    "time_zones": [{ "name": "America/New_York", "utc_offset": "-05:00" }]
  },
  "ip_location": null,
  "meta": {
    "checked_at": "2026-11-23T15:04:05Z",
    "credits": { "total": 0, "lookup": 0, "litigator": 0, "landline_sms": 0 },
    "request_id": "req_3f9c2a71b04e4d5a9c1e"
  }
}
```

### Can the line receive a text?

`sms.line_can_receive` is a fact about the line. It is `True` when the number is valid, the line takes texts (a mobile line, or a landline the `landline_sms` check found to be text-enabled) and the number has not been deactivated recently.

It is not advice to send. Litigator and do-not-call results never change it: in the record above the line can receive a text and the number is a litigator match. Check the `compliance` results and your own consent records before you message anyone.

When it is `False`, `sms.reasons` says why. More than one reason can apply.

| Reason | Meaning |
| --- | --- |
| `invalid_number` | The number is not assigned to anyone, or cannot exist. See `number.invalid_reason`. |
| `not_sms_capable` | The line is a landline, and the landline SMS check has not shown it to be text-enabled. |
| `recently_deactivated` | The carrier deactivated the number recently. See `number.deactivation_date`. |
| `unspecified` | The lookup found the line cannot receive texts and gave no cause we can name. |

```python
sms = result.data["sms"]
if not sms["line_can_receive"]:
    print("Cannot receive texts:", ", ".join(sms["reasons"]))
```

### Check statuses

Every check is an object with a `status`. Read the status first. The result fields (`match`, `listed`, `enabled`) are present only when the status is `checked`.

| Status | Meaning |
| --- | --- |
| `checked` | The check ran. Its result fields are present. |
| `not_requested` | The request did not ask for this check. Nothing is known either way. |
| `not_applicable` | The check cannot apply to this number, for example the landline SMS check on a mobile line. |
| `not_covered` | We have no data for this number's state or country, so a "clear" result would mean nothing. |
| `skipped` | The check was requested and applies, but did not run for this lookup. Nothing is known either way. |
| `error` | The check ran and failed. Treat the result as unavailable, never as clear. |

Only `checked` with a negative result means "clear". Every other status means you do not know.

```python
compliance = result.data["compliance"]

litigator = compliance["litigator"]
if litigator["status"] == "checked" and litigator["match"]:
    print("Litigator match:", litigator["type"])  # "litigator", "plaintiff" or "agitator"

dnc = compliance["dnc_state"]
if dnc["status"] == "checked":
    print("On a state do-not-call list:", dnc["listed"])
elif dnc["status"] == "not_covered":
    print("No state do-not-call data for this number")
else:
    print("State do-not-call result unknown:", dnc["status"])
```

`dnc_state` reports `not_covered` for a number from one of the 12 states the check does not cover (Colorado, Florida, Indiana, Louisiana, Massachusetts, Mississippi, Missouri, Oklahoma, Pennsylvania, Tennessee, Texas, Wyoming) and for numbers outside the US.

A litigator match can carry a name in `compliance.litigator.name`. Handle it with care and do not log it without need.

### Landline SMS

Some landlines can receive texts. The `landline_sms` check finds them:

```python
result = client.lookup("2125550102", checks=["landline_sms"])
landline = result.data["sms"]["landline"]
if landline["status"] == "checked" and landline["enabled"]:
    print("Text-enabled landline, served by", landline["provider"])
```

On a mobile line the status is `not_applicable` and the check costs nothing.

### Location and IP address

`location` is where the number was issued: the country and the state or province of its area code, and the city and rate centre of its exchange. It is not where the person is now. People keep their numbers when they move, so someone with a California number may live anywhere.

`location.time_zones` lists every time zone the area code covers, with its current offset from UTC. An area code that spans two zones lists both.

Send an IP address and the record also says where that address is, in `ip_location`. It describes the address, which can be a home connection, a mobile network, an office or a VPN.

```python
result = client.lookup("8182925409", ip="203.0.113.7")
ip = result.data["ip_location"]
if ip and ip["located"]:
    print(ip["region"], ip["time_zone"], ip["in_number_region"])
```

`in_number_region` is `True` when the IP address is in the same state or province as the number's area code. For a test number `located` is always `False`, because no lookup is made.

### Credits and request id

```python
result.credits_used                # credits this lookup cost
result.data["meta"]["credits"]     # {"total": 2, "lookup": 1, "litigator": 1, "landline_sms": 0}
result.request_id                  # quote it when you contact support
```

`total` is always a number. The parts (`lookup`, `litigator`, `landline_sms`) can be `None`.

## Test numbers

Any area code followed by 555-0100 to 555-0199 is a test number. Looking one up costs 0 credits and returns a fixed record, with `number.test_number` set to `True`. The last two digits pick the answer:

| Last two digits | Answer |
| --- | --- |
| `00` | A mobile line that can take texts. |
| `01` | A landline. |
| `02` | A text-enabled landline. Shown when `landline_sms` is requested; without it the record is a plain landline. |
| `03` | A mobile number the carrier deactivated 14 days ago. |
| `04` | A litigator match. Shown when `litigator` is requested. |
| `05` | Listed on a state do-not-call list and on the complainer list. Shown when those checks are requested. |
| `06` | A number that is not assigned. |
| `07` to `99` | The same as `00`. |

The area code is yours to choose, and location, time zones and state do-not-call coverage follow it. `6155550100` with `checks=["dnc_state"]` reports `not_covered`, because 615 is a Tennessee area code and Tennessee is one of the 12 states the check does not cover.

```python
result = client.lookup("2125550106")
result.data["number"]["valid"]           # False
result.data["number"]["invalid_reason"]  # "not_assigned"
result.data["carrier"]                   # None
```

## Numbers that cannot exist

A number that breaks the fixed rules of North American numbering is not an error. The lookup returns a record, costs 0 credits, and says which rule the number breaks:

```python
result = client.lookup("212-055-1234")
result.data["number"]["valid"]           # False
result.data["number"]["invalid_reason"]  # "exchange_starts_0_or_1"
result.data["sms"]["reasons"]            # ["invalid_number"]
result.credits_used                      # 0
```

| `number.invalid_reason` | Meaning |
| --- | --- |
| `not_assigned` | The carrier lookup did not find the number. |
| `wrong_length` | Not 10 digits, or 11 digits that do not start with 1. |
| `area_code_starts_0_or_1` | Area codes start with 2 to 9. |
| `area_code_is_service_code` | 211, 311 and the like are service codes, never area codes. |
| `exchange_starts_0_or_1` | The three digits after the area code start with 2 to 9. |

`not_assigned` comes from a carrier lookup. The other four are the fixed rules.

## Number info (free)

`number_info` returns what the number alone tells you: whether it can exist, how to write it, and the country, region, kind and time zones of its area code. It makes no carrier lookup, so it does not say whether the number is assigned to anyone. It costs 0 credits.

```python
info = client.number_info("416-555-0100").data

info["number"]["possible"]       # True
info["number"]["e164"]           # "+14165550100"
info["area_code"]["kind"]        # "geographic"
info["area_code"]["country"]     # "CA"
info["area_code"]["region"]      # "ON"
info["time_zones"][0]["name"]    # "America/Toronto"
```

`area_code` is `None` when the number cannot exist. `area_code.known` is `False` when the area code is not in the API's numbering data yet; it may be new.

Any active API key works, including a key on the Free plan. Note that the number is part of the URL here, while `lookup` sends it in the request body.

## Errors

A non-2xx response raises `CheckThatPhoneError`. Branch on `code` and `status`. `title` and `detail` are written for people and can be reworded.

| Attribute | What it is |
| --- | --- |
| `status` | The HTTP status. |
| `code` | A stable code, listed below. |
| `title`, `detail` | Text for people. `detail` can be `None`. |
| `request_id` | The request's id, when the response carried one. Quote it when you contact support. |
| `retry_after` | Seconds to wait before a retry, when the response said so. Otherwise `None`. |
| `retryable` | `True` when the same request may succeed later. |

| Status | Code | Meaning |
| --- | --- | --- |
| 400 | `invalid_request` | `phone`, `ip` or `checks` is missing or malformed. |
| 400 | `unknown_check` | `checks` names a check that does not exist. Nothing was looked up. |
| 401 | `unauthorized` | The API key is missing, malformed, invalid or revoked. |
| 402 | `payment_required` | The latest invoice is unpaid, so requests are paused until it is paid. |
| 402 | `safety_limit_reached` | The account reached its safety limit for this billing period. Contact support to have it raised. |
| 429 | `rate_limited` | Too many requests in a minute. Wait for the time in `retry_after`. |
| 429 | `quota_exceeded` | The plan's credits for this billing period are used up, on a plan that stops at its allowance. |
| 502 | `upstream_error` | The lookup failed on our side. No credits were charged. Retry. |
| 502 | `lookup_timeout` | The lookup took too long. No credits were charged. Retry. |
| 503 | `service_busy` | The service is briefly at capacity. No credits were charged. Retry after the time in `retry_after`. |

The API can add codes. Handle a code you do not know by its HTTP status.

```python
import time
from checkthatphone import CheckThatPhoneError

def lookup_with_retry(phone, attempts=3):
    for attempt in range(attempts):
        try:
            return client.lookup(phone, checks=["litigator"])
        except CheckThatPhoneError as err:
            if not err.retryable or attempt == attempts - 1:
                print(err.status, err.code, err.detail, err.request_id)
                raise
            time.sleep(err.retry_after or 2 ** attempt)
```

`retryable` is `True` for `rate_limited` and for the 5xx codes. It is `False` for `quota_exceeded`: the same request fails until the billing period ends or the plan changes.

The client does not retry on its own. The request timeout is 15 seconds by default; change it with `CheckThatPhone(api_key, timeout=30)`. A timeout or a network failure raises the standard library's own exception (`urllib.error.URLError` or `TimeoutError`), not `CheckThatPhoneError`.

## Upgrading from 0.x

Version 1.0 calls API v2, and `client.lookup()` returns a new record. The 0.x lookup is not in 1.0.

**To stay on API v1:** API v1 keeps working. Stay on the 0.2.x releases of this package, which call it:

```bash
pip install "checkthatphone==0.2.*"
```

**To move to v2:** follow the field-by-field [migration guide](https://checkthatphone.com/docs/migrate-to-v2). The v1 fields are in the [v1 reference](https://checkthatphone.com/docs/v1). Both pages open after you sign in to your CheckThatPhone account.

What is different in v2:

- **Checks are named in one list.** `checks=["litigator", "dnc_state"]` takes the place of the separate keyword options of 0.x. `client.lookup()` takes `phone`, `ip` and `checks`, and raises `TypeError` for any other keyword.
- **Values have real types.** v1 values were strings. v2 values are real booleans, and `None` where nothing is known.
- **A missing field is now a status.** In v1 a check's field was absent when the check did not run. In v2 every check is always there, with a `status` that says what happened.
- **A number that cannot exist is a record, not an error.** v1 answered HTTP 400 for a wrong length or an area code that starts with 0 or 1. v2 returns a record with `number.valid` set to `False`, at 0 credits.
- **v2 recommends nothing.** `sms.line_can_receive` and `sms.reasons` describe the line, and litigator and do-not-call results no longer change them. Read the checks under `compliance` and decide yourself.
- **The number and the IP address are kept apart.** `location` describes the number and `ip_location` the IP address you sent. In v1 the location fields described the IP address when you sent one.
- **`err.code` is a stable code.** It is a value such as `rate_limited`. The exception also has `title`, `request_id` and `retry_after` now.
- **The result is a `Lookup`.** It has `data`, `credits_used` and `request_id`.
- **A new method.** `client.number_info()`.

## Types

Responses are plain dictionaries. `checkthatphone.types` describes them as `TypedDict` definitions, so an editor or a type checker knows the keys:

```python
from checkthatphone.types import LookupData

def line_type(data: LookupData) -> str:
    return data["number"]["line_type"]
```

`LookupData` and `NumberInfoData` are the two response shapes. Nothing is checked at run time, and a field the API adds later is simply there in the dictionary.

## License

MIT
