top of page

How to Send Text Messages via API — Step-by-Step Guide

Updated: May 11


Smartphone screen showing chat app on a digital background, with text "API to send text messages" and a colorful SMS icon.


Whether you're building a customer notification system, sending OTPs, or automating appointment reminders, knowing how to send text messages via API is an essential skill for developers and businesses alike. This step-by-step guide covers everything — from what an SMS API is, how the underlying delivery network works, to writing your first API call in multiple programming languages, handling responses, setting up webhooks, staying compliant, and scaling to millions of messages.

By the time you finish reading, you'll have a complete understanding of how to implement SMS messaging in any application.

What Is an SMS API?

An SMS API (Application Programming Interface) is a software bridge that allows your application to send and receive text messages programmatically through a messaging provider's infrastructure. Instead of logging into a dashboard and sending messages manually, your application communicates directly with the provider's servers over HTTPS — sending a structured request and receiving a structured response in return.

Think of it this way: the SMS API is the connector between your software and the global telecommunications network. Your code talks to the API, the API talks to the carrier, and the carrier delivers the message to the recipient's handset.

How SMS Delivery Works Under the Hood

Before writing your first API call, it helps to understand what actually happens when a text message travels from your application to someone's phone.

The delivery chain looks like this:

  1. Your application sends an HTTPS POST request to the SMS API endpoint with the message payload.

  2. The SMS platform authenticates your request and validates the phone number format and message content.

  3. The platform routes the message to the appropriate carrier using the SMPP protocol (Short Message Peer-to-Peer) — the industry-standard protocol for high-throughput SMS delivery.

  4. The carrier receives the message and routes it to the subscriber's device via their mobile network.

  5. The carrier sends a delivery receipt (DLR) back through the chain, confirming whether the message was delivered, failed, or is still pending.

  6. The SMS API forwards that status update to your application via a webhook or makes it available through a status polling endpoint.

Understanding this chain explains why delivery can sometimes be delayed (carrier-side queuing), why certain numbers might reject messages (DND registrations, number formatting errors), and why delivery receipts can lag behind the actual send event.

Types of SMS Sender Numbers

One of the most common points of confusion when learning how to send text messages via API is understanding the different sender number types available. Each has different use cases, capabilities, and compliance requirements.

Long Code (10DLC in the US) — A standard 10-digit phone number with a local area code prefix. In the US, long codes used for business messaging must be registered under the 10DLC framework to avoid carrier filtering. Best for lower-volume, conversational use cases.

Short Code — A 5 or 6-digit number approved for high-volume A2P messaging. Ideal for marketing campaigns, OTP delivery, and mass notifications. Requires a formal application and takes several weeks to activate.

Toll-Free Numbers — 10-digit numbers with prefixes like 800, 833, 844, etc. Require verification for commercial use in the US and sit between long codes and short codes in throughput capacity. Well-suited for customer service and transactional messaging.

Alphanumeric Sender ID — Instead of a number, the sender appears as a brand name (e.g., "TECHTO"). Supported in India and most of Europe, but not in the US or Canada. In India, must be pre-registered on the DLT platform. Recipients cannot reply to alphanumeric sender ID messages.

SMS Character Limits and Encoding Explained

A common source of bugs in SMS integrations is character encoding. Understanding this upfront saves you from broken messages and unexpected billing.

GSM-7 (Standard Encoding) supports 128 characters including all English letters, numbers, and common punctuation. A single SMS using GSM-7 can carry up to 160 characters. Longer messages are split into segments of 153 characters each (7 characters used for segment metadata), with each segment billed separately.

Unicode (UCS-2) kicks in automatically when your message contains characters outside the GSM-7 set — such as Hindi, Arabic, Tamil, Chinese, Japanese, or emoji. Unicode messages are limited to 70 characters per segment (67 for multi-part messages).

Encoding

Characters Supported

Single SMS Limit

Multi-part Segment

GSM-7

English, basic punctuation

160 chars

153 chars

Unicode (UCS-2)

All languages, emoji

70 chars

67 chars

Watch out for: curly quotes " ", em-dashes —, and other "smart" typography characters that silently switch your message from GSM-7 to Unicode, cutting your per-segment allowance by more than half.

Step-by-Step: How to Send Text Messages via API

Step 1 — Choose an SMS API Provider

Key factors to evaluate when choosing a provider:

  • Delivery reliability and uptime SLA guarantees

  • Global reach and country coverage

  • Quality of developer documentation and SDKs

  • Number types supported (long code, short code, toll-free, alphanumeric)

  • Compliance tools — DLT registration (India), 10DLC (US), GDPR (Europe)

  • Two-way messaging and inbound SMS support

  • Real-time webhooks and delivery receipt (DLR) support

  • Free trial credits to test before committing

TechTo Networks offers a developer-ready SMS API with global carrier coverage, real-time delivery reporting, DLT compliance for India, two-way messaging, and 24/7 developer support.

Step 2 — Create an Account and Get Your API Credentials

After signing up and verifying your account, you'll typically receive:

  • API Key or Auth Token — authenticates all API requests

  • Sender ID or Phone Number — the "from" address shown to recipients

  • Sandbox environment access — for testing without real delivery or cost

Never hardcode API credentials into source code. Store them in environment variables:

bash

export SMS_API_KEY="your_api_key_here"
export SMS_SENDER_ID="TECHTO"

Step 3 — Understand the API Request Structure

Every SMS API call typically requires these parameters:

Parameter

Description

Example

to

Recipient number in E.164 format

+919876543210

from

Your sender ID or number

TECHTO

body

The message text

Your OTP is 483920

Auth header

API key passed in headers

Authorization: Bearer YOUR_KEY

E.164 format = +[country code][subscriber number], no spaces, no dashes. Invalid formats are the most common cause of 422 errors.

Step 4 — Make Your First API Call

cURL

bash

curl -X POST https://api.techtonetworks.com/v1/messages \
  -H "Authorization: Bearer $SMS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "+919876543210",
    "from": "TECHTO",
    "body": "Hello! Your OTP is 483920. Valid for 10 minutes."
  }'

Python

python

import requests, os

headers = {
    "Authorization": f"Bearer {os.environ['SMS_API_KEY']}",
    "Content-Type": "application/json"
}
payload = {
    "to": "+919876543210",
    "from": "TECHTO",
    "body": "Hello! Your OTP is 483920. Valid for 10 minutes."
}

response = requests.post("https://api.techtonetworks.com/v1/messages",
                         json=payload, headers=headers)
data = response.json()
print(f"Message ID: {data['message_id']}" if response.ok else f"Error: {data}")

Node.js (axios)

javascript

const axios = require('axios');

async function sendSMS(to, body) {
  const response = await axios.post(
    'https://api.techtonetworks.com/v1/messages',
    { to, from: 'TECHTO', body },
    { headers: { 'Authorization': `Bearer ${process.env.SMS_API_KEY}` } }
  );
  console.log('Queued:', response.data.message_id);
}

sendSMS('+919876543210', 'Your OTP is 483920. Valid for 10 minutes.');

PHP

php

<?php
$ch = curl_init('https://api.techtonetworks.com/v1/messages');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POSTFIELDS => json_encode([
        'to' => '+919876543210', 'from' => 'TECHTO',
        'body' => 'Your OTP is 483920. Valid for 10 minutes.'
    ]),
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('SMS_API_KEY'),
        'Content-Type: application/json'
    ]
]);
$data = json_decode(curl_exec($ch), true);
echo "Message ID: " . $data['message_id'];
?>

Java

java

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.techtonetworks.com/v1/messages"))
    .header("Authorization", "Bearer " + System.getenv("SMS_API_KEY"))
    .header("Content-Type", "application/json")
    .POST(BodyPublishers.ofString(
        "{\"to\":\"+919876543210\",\"from\":\"TECHTO\",\"body\":\"Your OTP is 483920.\"}"
    ))
    .build();
HttpResponse<String> res = client.send(request, BodyHandlers.ofString());
System.out.println(res.body());

Step 5 — Handle the API Response

A successful response:

json

{
  "message_id": "msg_7f3a91bc",
  "status": "queued",
  "to": "+919876543210",
  "from": "TECHTO",
  "segments": 1,
  "encoding": "GSM-7",
  "created_at": "2025-07-03T10:00:00Z"
}

Status Code

Meaning

Action

200 / 201

Message queued/sent

Log message_id for tracking

400

Bad request

Check request body and parameters

401

Unauthorized

Verify API key is valid

422

Validation error

Fix phone number format (E.164)

429

Rate limit exceeded

Implement exponential backoff

500 / 503

Server error

Retry after delay; check provider status page

Step 6 — Track Delivery Status with Webhooks

status: queued means accepted by the API — not delivered to the handset. Set up a webhook for real delivery confirmation.

Register a delivery webhook:

bash

curl -X POST https://api.techtonetworks.com/v1/webhooks \
  -H "Authorization: Bearer $SMS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"event": "message.delivered", "url": "https://yourdomain.com/api/sms-status"}'

Payload your server receives:

json

{
  "event": "message.delivered",
  "message_id": "msg_7f3a91bc",
  "status": "delivered",
  "delivered_at": "2025-07-03T10:00:03Z"
}

Express.js webhook receiver:

javascript

app.post('/api/sms-status', (req, res) => {
  const { message_id, status, delivered_at } = req.body;
  // Update your DB here
  res.status(200).json({ received: true }); // Always respond fast with 200
});

Always respond with 200 OK immediately. Slow responses cause the provider to retry — leading to duplicate events. Process the payload asynchronously if needed.

Step 7 — Send Bulk SMS via API

python

import requests, os

payload = {
    "from": "TECHTO",
    "messages": [
        {"to": "+919876543210", "body": "Hi Rahul, your order #1001 is confirmed."},
        {"to": "+919876543211", "body": "Hi Priya, your order #1002 is confirmed."},
        {"to": "+919876543212", "body": "Hi Arjun, your order #1003 is confirmed."},
    ]
}

response = requests.post(
    "https://api.techtonetworks.com/v1/messages/batch",
    json=payload,
    headers={"Authorization": f"Bearer {os.environ['SMS_API_KEY']}"}
)
print(response.json())

If you hit a 429 Too Many Requests error, implement exponential backoff — wait 1s, then 2s, then 4s before retrying. Never brute-force retry at full speed.

Step 8 — Receive Inbound SMS (Two-Way Messaging)

Register an inbound webhook. Your server will receive payloads like:

json

{
  "event": "message.inbound",
  "from": "+919876543210",
  "body": "STOP",
  "received_at": "2025-07-03T10:05:00Z"
}

Handle opt-out keywords (STOP, UNSUBSCRIBE) automatically — update your suppression list immediately and cease all future messages to that number.

Step 9 — Schedule Messages

python

payload = {
    "to": "+919876543210",
    "from": "TECHTO",
    "body": "Reminder: Your appointment is tomorrow at 10:00 AM.",
    "send_at": "2025-07-04T04:30:00Z"  # Always UTC
}

Always schedule in UTC and convert to the recipient's local timezone in your app logic. Sending at 2 AM local time is both a compliance risk and poor user experience.

Step 10 — Go Live with Compliance Checks

India — DLT Registration (TRAI) All commercial SMS requires registering your business entity, Sender ID (header), and every message template on the DLT platform with the correct category: Transactional, Service Implicit, Service Explicit, or Promotional. Unregistered traffic is blocked by Indian carriers.

United States — 10DLC Long-code A2P SMS must be registered via The Campaign Registry (TCR). Register your brand, use-case campaign, and link your phone numbers. Unregistered traffic faces carrier filtering.

Europe — GDPR Maintain records of explicit consent, provide clear opt-out in every marketing message, and process opt-outs immediately.

Universal rules:

  • Never send to opted-out numbers

  • Identify the sender clearly in every message

  • Avoid sending between 9 PM – 8 AM in the recipient's local timezone

  • Keep consent and message logs for compliance auditing

Troubleshooting Common SMS API Issues

Problem

Likely Cause

Fix

422 Invalid phone number

Not in E.164 format

Add + and country code; strip spaces and dashes

Message not delivered

DND / template mismatch

Verify DLT registration and template approval (India)

401 Unauthorized

Wrong or expired API key

Regenerate key in provider dashboard

429 Rate limit exceeded

Too many requests/second

Implement exponential backoff

Message truncated

Unicode exceeded segment limit

Audit for non-GSM-7 characters; shorten message

Webhook not firing

Wrong URL or server returning non-200

Test endpoint manually; check server logs

Delayed delivery

Carrier queuing during peak hours

Normal behavior; compare DLR vs. send timestamps

Missing delivery receipt

DLR or webhook not configured

Enable DLR in account settings; register webhook URL

SMS API Security Best Practices

  1. Store credentials in environment variables or a secrets manager — never in code or version control.

  2. Validate incoming webhook signatures using HMAC-SHA256 to confirm payloads are genuinely from your provider.

  3. Use IP allowlisting where available to restrict API access to known server IPs.

  4. Rotate API keys periodically and immediately after any suspected compromise.

  5. Validate and sanitize all user-submitted phone numbers before passing them to the API.

  6. Rate-limit sending on the application side to prevent accidental bulk sends due to code bugs.

  7. Log all API requests and responses (excluding sensitive message content) for auditing.

Pre-Launch Testing Checklist

  •  API credentials stored in environment variables, not hardcoded

  •  Phone numbers validated against E.164 before every call

  •  Error handling covers 4xx and 5xx responses with fallback logic

  •  Exponential backoff retry implemented for 429 and 503 errors

  •  Webhook endpoint returns 200 OK within 5 seconds

  •  Delivery receipt processing is idempotent (safe to receive same webhook twice)

  •  Opt-out keywords (STOP, UNSUBSCRIBE) handled in inbound webhook logic

  •  DLT registration complete (India) or 10DLC approved (US)

  •  Templates tested on real devices across multiple carriers

  •  Character count validated before sending to avoid unexpected segmentation

  •  Scheduling uses UTC timestamps with correct timezone conversion

Use Cases by Industry

E-Commerce — Order confirmations, shipping alerts, delivery notifications, abandoned cart recovery.

Fintech & Banking — OTP delivery for authentication, account balance alerts, fraud detection notifications, payment confirmations.

Healthcare — Appointment reminders (can reduce no-shows by up to 40%), prescription pickup alerts, lab result notifications.

EdTech — Fee reminders, exam schedules, result announcements, class cancellation notices.

HR & Operations — Shift scheduling, emergency broadcast alerts, maintenance downtime notices, internal survey links.

Logistics — Real-time tracking updates, delivery window confirmation, driver arrival alerts, post-delivery feedback requests.

SMS API vs. WhatsApp API vs. RCS

Feature

SMS API

WhatsApp Business API

RCS

Internet required

No

Yes

Yes (Android only)

Global reach

195+ countries

180+ countries

Limited

Rich media

No

Yes

Yes

Two-way messaging

Yes

Yes

Yes

Per-message cost

Low

Medium

Medium

Setup complexity

Low

Medium-High

Medium

Best for

OTPs, alerts, mass reach

Customer engagement

Rich interactive campaigns

Compliance

DLT / 10DLC

Meta verification

Carrier approval

SMS remains the most universally reliable channel for reach, OTPs, and low-connectivity areas. WhatsApp and RCS work best as complementary layers on top of a solid SMS foundation.

SMS API Glossary

A2P (Application-to-Person) — SMS sent from a software application to a person's phone, as opposed to person-to-person messaging.

DLR (Delivery Receipt) — A carrier confirmation that a message was successfully delivered to the handset.

DLT — TRAI's Distributed Ledger Technology framework in India mandating registration of commercial SMS senders and templates.

E.164 — International phone number standard: +[country code][subscriber number], e.g., +919876543210.

GSM-7 — The standard 7-bit SMS character encoding supporting 160 characters per segment.

SMPP — Short Message Peer-to-Peer, the binary protocol SMS gateways use to communicate with carrier networks.

Sender ID / Header — The "from" name or number shown to recipients. Must be DLT-registered in India.

10DLC — The US framework for registering 10-digit business phone numbers for A2P SMS via The Campaign Registry.

Unicode (UCS-2) — Character encoding for all international scripts and emoji; limits SMS to 70 characters per segment.

Webhook — An HTTP callback sent to your server when a messaging event occurs (e.g., delivered, failed, inbound reply).

Frequently Asked Questions

How quickly can I start sending messages after signing up? Most providers allow sandbox test messages within minutes. Production sending in regulated markets like India requires DLT registration first.

Do I need to register my sender ID in India? Yes. TRAI mandates DLT registration of your business entity, sender ID, and every message template. Unregistered traffic is blocked by Indian carriers.

What is the character limit for a single SMS? 160 characters with GSM-7 encoding. 70 characters with Unicode encoding (for regional scripts and emoji). Longer messages split into multi-part segments, each billed individually.

What is the difference between SMS status "sent" and "delivered"? "Sent" means the message left the API platform toward the carrier. "Delivered" means the carrier confirmed it reached the subscriber's handset. A message can be "sent" but not "delivered" if the phone is off, unreachable, or the number is disconnected.

How do I handle opt-outs automatically? Listen for inbound "STOP" keywords via webhook. Update your suppression database immediately and never send to opted-out numbers again. Violating opt-out requests is a regulatory offense in most jurisdictions.

Can I send SMS in Hindi, Tamil, or other regional languages? Yes. Unicode encoding supports all scripts. Note that Unicode messages carry fewer characters per segment (70 vs. 160) and are billed per segment.

Is an SMS API suitable for startups? Yes. Most providers offer pay-as-you-go pricing with free trial credits — no monthly minimums. TechTo Networks provides complimentary credits to fully test your integration before committing to production volume.

What happens if my server is down when a webhook fires? Most providers retry failed webhook deliveries automatically using exponential backoff over 24-48 hours. Implement idempotent processing in your handler so duplicate deliveries don't cause double actions or data corruption.

How do I send bulk SMS efficiently? Use your provider's batch endpoint to submit multiple messages in one API call. Implement rate-limit-aware throttling with exponential backoff for large volumes. Monitor delivery rates in real time to catch and retry failures quickly.

Can SMS reach users in low-connectivity rural areas? Yes. SMS runs over the carrier's core voice network, not the internet — making it far more resilient than WhatsApp or RCS in areas with poor mobile data coverage.

Final Thoughts

Learning how to send text messages via API is one of the most practical integrations you can add to any application. Once you understand the delivery chain, number types, character encoding, compliance requirements, webhook handling, and error management, you have everything needed to build a messaging system that is reliable, scalable, and compliant from day one.

TechTo Networks provides a production-ready SMS API built for developers and enterprises of all sizes — with global carrier coverage, real-time delivery reports, DLT compliance support for India, two-way messaging, multi-language Unicode support, and 24/7 developer assistance. Sign up for a free trial to test the API with complimentary credits.

bottom of page