Errors
Error responses, status codes, and when to retry.
The API uses conventional HTTP status codes. 2xx means it worked, 4xx means the request needs to change, 5xx means something went wrong on EZ Texting's side. Every error carries a JSON body that tells you what and, usually, which field.
The error body
{
"status": 400,
"title": "Malformed Request",
"detail": "The request could not be understood by the server due to malformed syntax.",
"errors": [
{
"code": "InvalidPhoneNumber",
"title": "Validation Failure",
"message": "toNumbers[0]: '555-1234' is not a valid phone number"
}
]
}| Field | What it is |
|---|---|
status | The HTTP status, repeated in the body for convenience. |
title | A short, human-readable category. |
detail | A sentence describing the problem. |
errors[] | Zero or more specifics. Each has a code, a title, and a message that usually names the offending field. |
Log the whole body. detail is what you show a developer; errors[].message is what tells them which field to fix. Don't show either to end users verbatim. (The code and message values above are illustrative; the shape is what's guaranteed.)
429 responses have no body: the information you need is in the X-Rate-Limit-Retry-After-Milliseconds header.
Status codes
| Code | Meaning | What to do |
|---|---|---|
| 200 OK | The request succeeded. | — |
| 201 Created | A resource was created. The body contains its id. | Store the ID. For messages, remember that created means accepted, not delivered. |
| 400 Bad Request | The request body or query is invalid: a malformed phone number, a missing required field, or bad JSON. | Read errors[].message, fix the request. Don't retry unchanged. |
| 401 Unauthorized | Missing, malformed, wrong, or expired credentials, or your plan doesn't include API access. | Check the Authorization header. With tokens, refresh and retry once. → Authentication |
| 403 Forbidden | Authenticated, but not allowed to do this: a feature not enabled on the account, or a resource that belongs to someone else. | Don't retry. Check the account's plan and permissions. |
| 404 Not Found | No resource at this path. For contacts, that includes a phone number in the wrong format. | Verify the ID or number. → Phone number formatting |
| 415 Unsupported Media Type | The request didn't say Content-Type: application/json. | Add the header. |
| 429 Too Many Requests | You've exceeded 200 requests per minute. | Wait the number of milliseconds in X-Rate-Limit-Retry-After-Milliseconds, then retry. → Rate limits |
| 500 Internal Server Error | Something failed on EZ Texting's side. | Retry with backoff for reads, upserts, and deletes. For POST /v1/messages, check whether it went out before resending (see below). If it persists, check status.eztexting.com and contact support with the request details and time. |
A retry policy you can copy
The rule has two halves:
- Retry only what EZ Texting has confirmed it did not accept. A
429is always safe to retry. A5xxor a timeout is safe to retry only when the request is idempotent: reads, contact upserts, deletes, PUTs. Never retry a4xxother than429; it will fail the same way again. - Treat a
5xxor timeout onPOST /v1/messagesas ambiguous. The request may have been accepted and queued before the error was produced (a proxy timeout, a dropped connection on the way back). Retrying it can send the message twice. Check whether it went out before sending again. See Idempotency & retries.
import time, random, requests
class AmbiguousOutcome(Exception):
"""A non-idempotent request failed in a way that doesn't prove it was rejected."""
def ez_request(method, url, *, auth, idempotent, max_attempts=5, **kw):
for attempt in range(1, max_attempts + 1):
try:
resp = requests.request(method, url, auth=auth, timeout=30, **kw)
except requests.RequestException:
if idempotent and attempt < max_attempts:
time.sleep(min(2 ** attempt, 30) + random.uniform(0, 1)); continue
raise AmbiguousOutcome()
# confirmed: not accepted
if resp.status_code == 429:
time.sleep(int(resp.headers.get("X-Rate-Limit-Retry-After-Milliseconds", 1000)) / 1000)
continue
if resp.status_code >= 500:
if idempotent and attempt < max_attempts:
time.sleep(min(2 ** attempt, 30) + random.uniform(0, 1)); continue
# may have been accepted
raise AmbiguousOutcome()
# 2xx or a definitive 4xx
return resp
raise AmbiguousOutcome()
# Reads and upserts: retry freely
contact = ez_request("GET", "https://a.eztexting.com/v1/contacts/15551234567", auth=auth, idempotent=True)
# Sends: never retry an ambiguous failure
try:
resp = ez_request("POST", "https://a.eztexting.com/v1/messages", auth=auth, idempotent=False,
json={"toNumbers": ["15551234567"], "message": "Hello"})
except AmbiguousOutcome:
# look it up later; do not resend automatically
mark_unknown_for_reconciliation()
else:
if resp.status_code >= 400:
err = resp.json() if resp.content else {}
raise RuntimeError(f"EZ Texting {resp.status_code}: {err.get('detail')} {err.get('errors')}")// a non-idempotent request failed without proof it was rejected
class AmbiguousOutcome extends Error {}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function ezRequest(url, init, { idempotent, maxAttempts = 5 }) {
for (let attempt = 1; ; attempt++) {
let res;
try {
res = await fetch(url, { ...init, signal: AbortSignal.timeout(30_000) });
} catch (err) {
if (idempotent && attempt < maxAttempts) { await sleep(Math.min(2 ** attempt, 30) * 1000 + Math.random() * 1000); continue; }
throw new AmbiguousOutcome(String(err));
}
// confirmed: not accepted
if (res.status === 429) {
await sleep(Number(res.headers.get("X-Rate-Limit-Retry-After-Milliseconds") ?? 1000)); continue;
}
if (res.status >= 500) {
if (idempotent && attempt < maxAttempts) { await sleep(Math.min(2 ** attempt, 30) * 1000 + Math.random() * 1000); continue; }
// may have been accepted
throw new AmbiguousOutcome(`HTTP ${res.status}`);
}
// 2xx or a definitive 4xx
return res;
}
}
// Reads and upserts: retry freely
const contact = await ezRequest("https://a.eztexting.com/v1/contacts/15551234567", { headers }, { idempotent: true });
// Sends: never retry an ambiguous failure
try {
const res = await ezRequest("https://a.eztexting.com/v1/messages", {
method: "POST", headers, body: JSON.stringify({ toNumbers: ["15551234567"], message: "Hello" }),
}, { idempotent: false });
if (!res.ok) { const err = await res.json(); throw new Error(`EZ Texting ${res.status}: ${err.detail}`); }
} catch (err) {
// look it up later; do not resend
if (err instanceof AmbiguousOutcome) await markUnknownForReconciliation();
else throw err;
}<?php
// a non-idempotent request failed without proof it was rejected
class AmbiguousOutcome extends Exception {}
function ezRequest(string $method, string $url, ?array $body, bool $idempotent, int $maxAttempts = 5): array {
for ($attempt = 1; ; $attempt++) {
$ch = curl_init($url);
$headers = [];
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_USERPWD => getenv("EZTEXTING_USERNAME") . ":" . getenv("EZTEXTING_PASSWORD"),
CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$headers) {
$parts = explode(':', $line, 2);
if (count($parts) === 2) $headers[strtolower(trim($parts[0]))] = trim($parts[1]);
return strlen($line);
},
]);
if ($body !== null) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
$resp = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// network error, timeout, or 5xx
if ($resp === false || $status >= 500) {
if ($idempotent && $attempt < $maxAttempts) { usleep((min(2 ** $attempt, 30) + random_int(0, 1000) / 1000) * 1_000_000); continue; }
// may have been accepted
throw new AmbiguousOutcome("HTTP $status");
}
// confirmed: not accepted
if ($status === 429) {
usleep((int) ($headers['x-rate-limit-retry-after-milliseconds'] ?? 1000) * 1000);
continue;
}
// 2xx or a definitive 4xx
return [$status, json_decode($resp, true)];
}
}
// Reads and upserts: retry freely
[$status, $contact] = ezRequest("GET", "https://a.eztexting.com/v1/contacts/15551234567", null, idempotent: true);
// Sends: never retry an ambiguous failure
try {
[$status, $err] = ezRequest("POST", "https://a.eztexting.com/v1/messages",
["toNumbers" => ["15551234567"], "message" => "Hello"], idempotent: false);
if ($status >= 400) throw new RuntimeException("EZ Texting $status: " . ($err['detail'] ?? ''));
} catch (AmbiguousOutcome $e) {
// look it up later; do not resend automatically
markUnknownForReconciliation();
}require "net/http"
require "json"
# a non-idempotent request failed without proof it was rejected
class AmbiguousOutcome < StandardError; end
def ez_request(method, url, body: nil, idempotent:, max_attempts: 5)
uri = URI(url)
attempt = 0
loop do
attempt += 1
req = Net::HTTPGenericRequest.new(method, !body.nil?, true, uri, "Content-Type" => "application/json")
req.basic_auth(ENV.fetch("EZTEXTING_USERNAME"), ENV.fetch("EZTEXTING_PASSWORD"))
req.body = body.to_json if body
begin
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true, read_timeout: 30) { |http| http.request(req) }
rescue StandardError
if idempotent && attempt < max_attempts
sleep([2**attempt, 30].min + rand); next
end
raise AmbiguousOutcome
end
# confirmed: not accepted
if res.code == "429"
sleep((res["X-Rate-Limit-Retry-After-Milliseconds"] || "1000").to_i / 1000.0); next
end
if res.code.to_i >= 500
if idempotent && attempt < max_attempts
sleep([2**attempt, 30].min + rand); next
end
# may have been accepted
raise AmbiguousOutcome, "HTTP #{res.code}"
end
# 2xx or a definitive 4xx
return res
end
end
# Reads and upserts: retry freely
contact = ez_request("GET", "https://a.eztexting.com/v1/contacts/15551234567", idempotent: true)
# Sends: never retry an ambiguous failure
begin
res = ez_request("POST", "https://a.eztexting.com/v1/messages",
body: { toNumbers: ["15551234567"], message: "Hello" }, idempotent: false)
raise "EZ Texting #{res.code}: #{JSON.parse(res.body)['detail']}" if res.code.to_i >= 400
rescue AmbiguousOutcome
# look it up later; do not resend automatically
mark_unknown_for_reconciliation
end// a non-idempotent request failed without proof it was rejected
class AmbiguousOutcome extends Exception {
AmbiguousOutcome(String msg) { super(msg); }
}
HttpResponse<String> ezRequest(HttpRequest request, boolean idempotent, int maxAttempts) throws Exception {
for (int attempt = 1; ; attempt++) {
HttpResponse<String> res;
try {
// build request with .timeout(Duration.ofSeconds(30))
res = client.send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException e) {
if (idempotent && attempt < maxAttempts) { Thread.sleep(backoffMs(attempt)); continue; }
throw new AmbiguousOutcome(e.toString());
}
// confirmed: not accepted
if (res.statusCode() == 429) {
Thread.sleep(res.headers().firstValue("X-Rate-Limit-Retry-After-Milliseconds").map(Long::parseLong).orElse(1000L));
continue;
}
if (res.statusCode() >= 500) {
if (idempotent && attempt < maxAttempts) { Thread.sleep(backoffMs(attempt)); continue; }
// may have been accepted
throw new AmbiguousOutcome("HTTP " + res.statusCode());
}
// 2xx or a definitive 4xx
return res;
}
}
long backoffMs(int attempt) {
return Math.min(1L << attempt, 30) * 1000 + ThreadLocalRandom.current().nextLong(1000);
}
// Sends: never retry an ambiguous failure
try {
HttpResponse<String> res = ezRequest(sendRequest, false, 5);
if (res.statusCode() >= 400) throw new RuntimeException("EZ Texting " + res.statusCode() + ": " + res.body());
} catch (AmbiguousOutcome e) {
// look it up later; do not resend automatically
markUnknownForReconciliation();
}async Task<HttpResponseMessage> EzRequestAsync(Func<HttpRequestMessage> makeRequest, bool idempotent, int maxAttempts = 5)
{
for (var attempt = 1; ; attempt++)
{
HttpResponseMessage res;
try
{
// set client.Timeout = TimeSpan.FromSeconds(30)
res = await client.SendAsync(makeRequest());
}
catch (Exception e) when (e is HttpRequestException or TaskCanceledException)
{
if (idempotent && attempt < maxAttempts) { await Task.Delay(Backoff(attempt)); continue; }
throw new AmbiguousOutcome(e.Message);
}
// confirmed: not accepted
if (res.StatusCode == HttpStatusCode.TooManyRequests)
{
var waitMs = res.Headers.TryGetValues("X-Rate-Limit-Retry-After-Milliseconds", out var v) ? int.Parse(v.First()) : 1000;
await Task.Delay(waitMs);
continue;
}
if ((int)res.StatusCode >= 500)
{
if (idempotent && attempt < maxAttempts) { await Task.Delay(Backoff(attempt)); continue; }
// may have been accepted
throw new AmbiguousOutcome($"HTTP {(int)res.StatusCode}");
}
// 2xx or a definitive 4xx
return res;
}
}
static TimeSpan Backoff(int attempt) =>
TimeSpan.FromMilliseconds(Math.Min(Math.Pow(2, attempt), 30) * 1000 + Random.Shared.Next(1000));
// Sends: never retry an ambiguous failure
try
{
var res = await EzRequestAsync(() => new HttpRequestMessage(HttpMethod.Post, "https://a.eztexting.com/v1/messages")
{
Content = JsonContent.Create(new { toNumbers = new[] { "15551234567" }, message = "Hello" })
}, idempotent: false);
if (!res.IsSuccessStatusCode) throw new Exception($"EZ Texting {(int)res.StatusCode}: {await res.Content.ReadAsStringAsync()}");
}
catch (AmbiguousOutcome)
{
// look it up later; do not resend automatically
await MarkUnknownForReconciliationAsync();
}
// a non-idempotent request failed without proof it was rejected
class AmbiguousOutcome : Exception
{
public AmbiguousOutcome(string message) : base(message) { }
}var ErrAmbiguous = errors.New("ambiguous outcome: request may have been accepted")
func ezRequest(makeReq func() *http.Request, idempotent bool, maxAttempts int) (*http.Response, error) {
client := &http.Client{Timeout: 30 * time.Second}
backoff := func(attempt int) time.Duration {
return time.Duration(min(1<<attempt, 30))*time.Second + time.Duration(rand.Intn(1000))*time.Millisecond
}
for attempt := 1; ; attempt++ {
resp, err := client.Do(makeReq())
if err != nil {
if idempotent && attempt < maxAttempts {
time.Sleep(backoff(attempt))
continue
}
return nil, ErrAmbiguous
}
// confirmed: not accepted
if resp.StatusCode == 429 {
resp.Body.Close()
waitMs, _ := strconv.Atoi(resp.Header.Get("X-Rate-Limit-Retry-After-Milliseconds"))
if waitMs <= 0 {
waitMs = 1000
}
time.Sleep(time.Duration(waitMs) * time.Millisecond)
continue
}
if resp.StatusCode >= 500 {
resp.Body.Close()
if idempotent && attempt < maxAttempts {
time.Sleep(backoff(attempt))
continue
}
// may have been accepted
return nil, ErrAmbiguous
}
// 2xx or a definitive 4xx
return resp, nil
}
}
// Sends: never retry an ambiguous failure
resp, err := ezRequest(newSendRequest, false, 5)
if errors.Is(err, ErrAmbiguous) {
// look it up later; do not resend automatically
markUnknownForReconciliation()
}What this gets right that a generic retry loop misses:
- It honors the server's wait time on
429instead of guessing. The header is in milliseconds, and a429is the one failure where you know nothing was accepted. - It never retries a definitive
4xx. A malformed request will be malformed again. - It distinguishes "rejected" from "unknown" on sends. Reads can be repeated at will; a message send that timed out might already be on its way to a phone.
Errors that aren't HTTP errors
Some problems come back as a 201 and only show up later:
| What happened | Where it shows |
|---|---|
A number in toNumbers was invalid (only possible with strictValidation: false) | It was skipped silently. The delivery report adds up to fewer recipients than your list. |
| A contact in a group send had opted out | Not sent in the delivery report. A direct send to an opted-out number in toNumbers doesn't get this far: it's rejected with a 400, "The phone numbers that you're sending to are opted out". |
| The number was a landline or disconnected | Bounced in the delivery report, after the carrier responds. |
| A scheduled message came due after the account ran out of credits | Not sent in the delivery report. GET /v1/credits shows totalCredits: 0. A send made while the account is out of credits doesn't get this far: it's rejected with a 400 with INSUFFICIENT_BALANCE. |
| The carrier filtered the message | Bounced or stuck in queued. See Troubleshooting. |
If a send matters, read GET /v1/message-reports/{id} afterwards.
Related
- Rate limits
- Idempotency & retries
- Troubleshooting — organized by symptom
Try Troubleshooting, check status.eztexting.com, or contact support.
Updated 2 days ago