# SMS verification in Python

A complete script with the requests library: buy a temporary number, wait for the code and close the order. No SDK needed.

## How do I receive an SMS verification code in Python?

Use requests with the X-Api-Key header: POST /v1/orders to get a number, poll GET /v1/orders/{id} every 4 seconds until messages has the SMS, read messages[-1]["code"] and POST finish. If nothing arrives in time, POST cancel to get the frozen amount back.

## Setup

- Python 3.8 or newer.
- pip install requests
- Export your key: export SMSNITRO_API_KEY=...

## Complete script

**activation.py**

```python
import os
import time
import requests

API = "https://smsnitro.com/api/v1"
session = requests.Session()
session.headers["X-Api-Key"] = os.environ["SMSNITRO_API_KEY"]


def api(method, path, **kw):
    r = session.request(method, API + path, timeout=30, **kw)
    if r.status_code >= 400:
        raise RuntimeError(f"{r.status_code}: {r.json().get('detail')}")
    return r.json()


print("Balance:", api("GET", "/balance")["balance"], "USD")

order = api("POST", "/orders", json={"product": "telegram", "country": "usa"})
print("Number:", order["phone"], "order", order["id"])

deadline = time.time() + 600  # numbers stay reserved for up to 20 minutes
while time.time() < deadline:
    order = api("GET", f"/orders/{order['id']}")
    if order["messages"]:
        print("Code:", order["messages"][-1]["code"])
        api("POST", f"/orders/{order['id']}/finish")
        break
    if order["status"] in ("CANCELED", "TIMEOUT", "BANNED", "FINISHED"):
        print("Ended without SMS:", order["status"], "(not charged)")
        break
    time.sleep(4)  # poll every 3 to 5 seconds
else:
    api("POST", f"/orders/{order['id']}/cancel")  # refund the frozen amount
    print("No SMS: cancelled and refunded")
```

## How the script works

- One requests.Session keeps the connection and the key header for every call.
- Any 4xx or 5xx raises with the detail message from the API.
- It polls every 4 seconds for up to 10 minutes, then cancels, so a missing SMS costs nothing.
- Change product and country to the app and country you need; GET /v1/services lists them.

Source: https://smsnitro.com/developers/python
