Start
First message in 5 minutes
From the key to the delivery status: five steps after which your system sends SMS through api.sendsms.to.
#1. Prepare the cabinet
Sign in to the cabinet at app.sendsms.to. Sending opens when the cabinet shows that the account is ready to send. Until the account is admitted you can send one trial SMS to your own confirmed number, from the platform sender.
#2. Issue an API key
- In the cabinet open “API and integrations” and create a key for your integration.
- Tick the permissions:
messages.sendto send andmessages.readfor statuses;balance.readif you need the balance. - Enter the external IP address of the server that will call the API: a key without addresses does not work (see IP address allowlist).
- Keep the key in your server secrets: it is shown once.
export SENDSMS_API_KEY='your-key'#3. Check access
Ask for the balance: 200 means the key, its permissions and the address are fine. 401 — wrong key; 403 ip_not_allowed — the server address is not on the key’s list (the answer carries clientIp, the address we see).
/v1/balancecURL. The key is in the SENDSMS_API_KEY environment variable.
curl --max-time 30 --request GET \
--url 'https://api.sendsms.to/v1/balance' \
--header "X-API-Key: $SENDSMS_API_KEY"Node.js 18+ (built-in fetch).
const response = await fetch("https://api.sendsms.to/v1/balance", {
method: "GET",
headers: {
'X-API-Key': process.env.SENDSMS_API_KEY,
},
signal: AbortSignal.timeout(30000),
});
console.log(response.status, await response.text());Python 3.8+, standard library only.
import json
import os
import urllib.error
import urllib.request
request = urllib.request.Request(
"https://api.sendsms.to/v1/balance",
method="GET",
headers={
"X-API-Key": os.environ["SENDSMS_API_KEY"],
},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
print(response.status, response.read().decode("utf-8"))
except urllib.error.HTTPError as error:
print(error.code, error.read().decode("utf-8"))PHP with the cURL extension.
<?php
$ch = curl_init("https://api.sendsms.to/v1/balance");
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'X-API-Key: ' . getenv('SENDSMS_API_KEY'),
],
]);
$body = curl_exec($ch);
if ($body === false) {
throw new RuntimeException(curl_error($ch));
}
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), PHP_EOL, $body, PHP_EOL;
curl_close($ch);Ruby 2.6+, standard library: net/http, uri.
require 'net/http'
require 'uri'
uri = URI('https://api.sendsms.to/v1/balance')
request = Net::HTTPGenericRequest.new('GET', false, true, uri.request_uri)
request['X-API-Key'] = ENV.fetch('SENDSMS_API_KEY')
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 30, read_timeout: 30) { |http| http.request(request) }
puts "#{response.code} #{response.body}"Go, standard library.
package main
import (
"fmt"
"io"
"net/http"
"os"
"time"
)
func main() {
req, err := http.NewRequest("GET", "https://api.sendsms.to/v1/balance", nil)
if err != nil {
panic(err)
}
req.Header.Set("X-API-Key", os.Getenv("SENDSMS_API_KEY"))
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(data))
}.NET 6+ (HttpClient, top-level statements).
using System;
using System.Net.Http;
using System.Text;
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.sendsms.to/v1/balance");
request.Headers.Add("X-API-Key", Environment.GetEnvironmentVariable("SENDSMS_API_KEY"));
using var response = await client.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");Java 11+ (java.net.http). File SendSmsExample.java.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.UUID;
public class SendSmsExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.sendsms.to/v1/balance"))
.timeout(Duration.ofSeconds(30))
.header("X-API-Key", System.getenv("SENDSMS_API_KEY"))
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode() + " " + response.body());
}
}Dart 2.12+, dart:io and dart:convert only.
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 30);
final request = await client.openUrl('GET', Uri.parse('https://api.sendsms.to/v1/balance'));
request.headers.set('X-API-Key', Platform.environment['SENDSMS_API_KEY'] ?? '');
final response = await request.close().timeout(const Duration(seconds: 30));
final body = await response.transform(utf8.decoder).join();
print('${response.statusCode} $body');
client.close();
}{
"money": {
"balance": "125.12345",
"currency": "USD"
},
"smsCredits": {
"total": "1500.00"
}
}200 — the key, permissions and address are fine. Money and SMS credits are separate strings; do not add them up. All fields and responses — on the method page →
If something is wrong
401 No X-API-Key header. Send the key in the X-API-Key header.
{
"error": "Отсутствует X-API-Key",
"code": "api_key_missing"
}403 The request came from an address that is not on the key’s allowlist. clientIp in the answer is the address we see. Add that address to the key in the cabinet (“Change addresses”).
{
"error": "ip_not_allowed",
"message": "Запрос пришёл с IP-адреса, которого нет в белом списке этого API-ключа. Если адрес вашего сервера изменился, добавьте новый адрес в кабинете: API / Developers → ключ → «Разрешённые IP-адреса».",
"clientIp": "203.0.113.10"
}#4. Send an SMS
Put an approved sender name of your account in from (the list: GET /v1/senders). Pass an Idempotency-Key: a repeat with the same key does not create a second message. First send a trial request with the X-Dry-Run: true header — it passes every check but sends nothing (Trial requests); then the same request without the header.
202 means “accepted for processing”, not “delivered”. Keep the messageId.
/v1/messagescURL. The key is in the SENDSMS_API_KEY environment variable.
curl --max-time 30 --request POST \
--url 'https://api.sendsms.to/v1/messages' \
--header "X-API-Key: $SENDSMS_API_KEY" \
--header "Idempotency-Key: $(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)" \
--header 'X-Dry-Run: true' \
--header 'Content-Type: application/json' \
--data '{
"channel": "sms",
"to": "994XXXXXXXXX",
"from": "APPROVED_SENDER",
"text": "Your order is ready",
"trafficClass": "transactional"
}'Node.js 18+ (built-in fetch).
const response = await fetch("https://api.sendsms.to/v1/messages", {
method: "POST",
headers: {
'X-API-Key': process.env.SENDSMS_API_KEY,
'Idempotency-Key': crypto.randomUUID(),
'X-Dry-Run': 'true',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"channel": "sms",
"to": "994XXXXXXXXX",
"from": "APPROVED_SENDER",
"text": "Your order is ready",
"trafficClass": "transactional"
}),
signal: AbortSignal.timeout(30000),
});
console.log(response.status, await response.text());Python 3.8+, standard library only.
import json
import os
import urllib.error
import urllib.request
import uuid
payload = {
"channel": "sms",
"to": "994XXXXXXXXX",
"from": "APPROVED_SENDER",
"text": "Your order is ready",
"trafficClass": "transactional",
}
request = urllib.request.Request(
"https://api.sendsms.to/v1/messages",
method="POST",
headers={
"X-API-Key": os.environ["SENDSMS_API_KEY"],
"Idempotency-Key": str(uuid.uuid4()),
"X-Dry-Run": "true",
"Content-Type": "application/json",
},
data=json.dumps(payload).encode("utf-8"),
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
print(response.status, response.read().decode("utf-8"))
except urllib.error.HTTPError as error:
print(error.code, error.read().decode("utf-8"))PHP with the cURL extension.
<?php
$ch = curl_init("https://api.sendsms.to/v1/messages");
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'X-API-Key: ' . getenv('SENDSMS_API_KEY'),
'Idempotency-Key: ' . bin2hex(random_bytes(16)),
'X-Dry-Run: true',
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => '{"channel":"sms","to":"994XXXXXXXXX","from":"APPROVED_SENDER","text":"Your order is ready","trafficClass":"transactional"}',
]);
$body = curl_exec($ch);
if ($body === false) {
throw new RuntimeException(curl_error($ch));
}
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), PHP_EOL, $body, PHP_EOL;
curl_close($ch);Ruby 2.6+, standard library: net/http, uri.
require 'net/http'
require 'uri'
require 'securerandom'
uri = URI('https://api.sendsms.to/v1/messages')
request = Net::HTTPGenericRequest.new('POST', true, true, uri.request_uri)
request['X-API-Key'] = ENV.fetch('SENDSMS_API_KEY')
request['Idempotency-Key'] = SecureRandom.uuid
request['X-Dry-Run'] = 'true'
request['Content-Type'] = 'application/json'
request.body = '{"channel":"sms","to":"994XXXXXXXXX","from":"APPROVED_SENDER","text":"Your order is ready","trafficClass":"transactional"}'
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 30, read_timeout: 30) { |http| http.request(request) }
puts "#{response.code} #{response.body}"Go, standard library.
package main
import (
"crypto/rand"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
func main() {
body := strings.NewReader("{\"channel\":\"sms\",\"to\":\"994XXXXXXXXX\",\"from\":\"APPROVED_SENDER\",\"text\":\"Your order is ready\",\"trafficClass\":\"transactional\"}")
req, err := http.NewRequest("POST", "https://api.sendsms.to/v1/messages", body)
if err != nil {
panic(err)
}
req.Header.Set("X-API-Key", os.Getenv("SENDSMS_API_KEY"))
key := make([]byte, 16)
if _, err := rand.Read(key); err != nil {
panic(err)
}
req.Header.Set("Idempotency-Key", fmt.Sprintf("%x", key))
req.Header.Set("X-Dry-Run", "true")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(data))
}.NET 6+ (HttpClient, top-level statements).
using System;
using System.Net.Http;
using System.Text;
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.sendsms.to/v1/messages");
request.Headers.Add("X-API-Key", Environment.GetEnvironmentVariable("SENDSMS_API_KEY"));
request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString());
request.Headers.Add("X-Dry-Run", "true");
request.Content = new StringContent("{\"channel\":\"sms\",\"to\":\"994XXXXXXXXX\",\"from\":\"APPROVED_SENDER\",\"text\":\"Your order is ready\",\"trafficClass\":\"transactional\"}", Encoding.UTF8, "application/json");
using var response = await client.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");Java 11+ (java.net.http). File SendSmsExample.java.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.UUID;
public class SendSmsExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.sendsms.to/v1/messages"))
.timeout(Duration.ofSeconds(30))
.header("X-API-Key", System.getenv("SENDSMS_API_KEY"))
.header("Idempotency-Key", UUID.randomUUID().toString())
.header("X-Dry-Run", "true")
.header("Content-Type", "application/json")
.method("POST", HttpRequest.BodyPublishers.ofString("{\"channel\":\"sms\",\"to\":\"994XXXXXXXXX\",\"from\":\"APPROVED_SENDER\",\"text\":\"Your order is ready\",\"trafficClass\":\"transactional\"}"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode() + " " + response.body());
}
}Dart 2.12+, dart:io and dart:convert only.
import 'dart:convert';
import 'dart:io';
import 'dart:math';
Future<void> main() async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 30);
final request = await client.openUrl('POST', Uri.parse('https://api.sendsms.to/v1/messages'));
request.headers.set('X-API-Key', Platform.environment['SENDSMS_API_KEY'] ?? '');
final random = Random.secure();
request.headers.set('Idempotency-Key', List.generate(16, (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0')).join());
request.headers.set('X-Dry-Run', 'true');
request.headers.contentType = ContentType.json;
request.write('{"channel":"sms","to":"994XXXXXXXXX","from":"APPROVED_SENDER","text":"Your order is ready","trafficClass":"transactional"}');
final response = await request.close().timeout(const Duration(seconds: 30));
final body = await response.transform(utf8.decoder).join();
print('${response.statusCode} $body');
client.close();
}{
"messageId": "00000000-0000-0000-0000-000000000000",
"status": "queued",
"dryRun": true
}202 and messageId — the message is accepted for processing (not delivered yet). Keep the messageId. All fields and responses — on the method page →
/v1/messagescURL. The key is in the SENDSMS_API_KEY environment variable.
curl --max-time 30 --request POST \
--url 'https://api.sendsms.to/v1/messages' \
--header "X-API-Key: $SENDSMS_API_KEY" \
--header "Idempotency-Key: $(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)" \
--header 'Content-Type: application/json' \
--data '{
"channel": "sms",
"to": "994XXXXXXXXX",
"from": "APPROVED_SENDER",
"text": "Your order is ready",
"trafficClass": "transactional"
}'Node.js 18+ (built-in fetch).
const response = await fetch("https://api.sendsms.to/v1/messages", {
method: "POST",
headers: {
'X-API-Key': process.env.SENDSMS_API_KEY,
'Idempotency-Key': crypto.randomUUID(),
'Content-Type': 'application/json',
},
body: JSON.stringify({
"channel": "sms",
"to": "994XXXXXXXXX",
"from": "APPROVED_SENDER",
"text": "Your order is ready",
"trafficClass": "transactional"
}),
signal: AbortSignal.timeout(30000),
});
console.log(response.status, await response.text());Python 3.8+, standard library only.
import json
import os
import urllib.error
import urllib.request
import uuid
payload = {
"channel": "sms",
"to": "994XXXXXXXXX",
"from": "APPROVED_SENDER",
"text": "Your order is ready",
"trafficClass": "transactional",
}
request = urllib.request.Request(
"https://api.sendsms.to/v1/messages",
method="POST",
headers={
"X-API-Key": os.environ["SENDSMS_API_KEY"],
"Idempotency-Key": str(uuid.uuid4()),
"Content-Type": "application/json",
},
data=json.dumps(payload).encode("utf-8"),
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
print(response.status, response.read().decode("utf-8"))
except urllib.error.HTTPError as error:
print(error.code, error.read().decode("utf-8"))PHP with the cURL extension.
<?php
$ch = curl_init("https://api.sendsms.to/v1/messages");
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'X-API-Key: ' . getenv('SENDSMS_API_KEY'),
'Idempotency-Key: ' . bin2hex(random_bytes(16)),
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => '{"channel":"sms","to":"994XXXXXXXXX","from":"APPROVED_SENDER","text":"Your order is ready","trafficClass":"transactional"}',
]);
$body = curl_exec($ch);
if ($body === false) {
throw new RuntimeException(curl_error($ch));
}
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), PHP_EOL, $body, PHP_EOL;
curl_close($ch);Ruby 2.6+, standard library: net/http, uri.
require 'net/http'
require 'uri'
require 'securerandom'
uri = URI('https://api.sendsms.to/v1/messages')
request = Net::HTTPGenericRequest.new('POST', true, true, uri.request_uri)
request['X-API-Key'] = ENV.fetch('SENDSMS_API_KEY')
request['Idempotency-Key'] = SecureRandom.uuid
request['Content-Type'] = 'application/json'
request.body = '{"channel":"sms","to":"994XXXXXXXXX","from":"APPROVED_SENDER","text":"Your order is ready","trafficClass":"transactional"}'
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 30, read_timeout: 30) { |http| http.request(request) }
puts "#{response.code} #{response.body}"Go, standard library.
package main
import (
"crypto/rand"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
func main() {
body := strings.NewReader("{\"channel\":\"sms\",\"to\":\"994XXXXXXXXX\",\"from\":\"APPROVED_SENDER\",\"text\":\"Your order is ready\",\"trafficClass\":\"transactional\"}")
req, err := http.NewRequest("POST", "https://api.sendsms.to/v1/messages", body)
if err != nil {
panic(err)
}
req.Header.Set("X-API-Key", os.Getenv("SENDSMS_API_KEY"))
key := make([]byte, 16)
if _, err := rand.Read(key); err != nil {
panic(err)
}
req.Header.Set("Idempotency-Key", fmt.Sprintf("%x", key))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(data))
}.NET 6+ (HttpClient, top-level statements).
using System;
using System.Net.Http;
using System.Text;
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
using var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.sendsms.to/v1/messages");
request.Headers.Add("X-API-Key", Environment.GetEnvironmentVariable("SENDSMS_API_KEY"));
request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString());
request.Content = new StringContent("{\"channel\":\"sms\",\"to\":\"994XXXXXXXXX\",\"from\":\"APPROVED_SENDER\",\"text\":\"Your order is ready\",\"trafficClass\":\"transactional\"}", Encoding.UTF8, "application/json");
using var response = await client.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");Java 11+ (java.net.http). File SendSmsExample.java.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.UUID;
public class SendSmsExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.sendsms.to/v1/messages"))
.timeout(Duration.ofSeconds(30))
.header("X-API-Key", System.getenv("SENDSMS_API_KEY"))
.header("Idempotency-Key", UUID.randomUUID().toString())
.header("Content-Type", "application/json")
.method("POST", HttpRequest.BodyPublishers.ofString("{\"channel\":\"sms\",\"to\":\"994XXXXXXXXX\",\"from\":\"APPROVED_SENDER\",\"text\":\"Your order is ready\",\"trafficClass\":\"transactional\"}"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode() + " " + response.body());
}
}Dart 2.12+, dart:io and dart:convert only.
import 'dart:convert';
import 'dart:io';
import 'dart:math';
Future<void> main() async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 30);
final request = await client.openUrl('POST', Uri.parse('https://api.sendsms.to/v1/messages'));
request.headers.set('X-API-Key', Platform.environment['SENDSMS_API_KEY'] ?? '');
final random = Random.secure();
request.headers.set('Idempotency-Key', List.generate(16, (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0')).join());
request.headers.contentType = ContentType.json;
request.write('{"channel":"sms","to":"994XXXXXXXXX","from":"APPROVED_SENDER","text":"Your order is ready","trafficClass":"transactional"}');
final response = await request.close().timeout(const Duration(seconds: 30));
final body = await response.transform(utf8.decoder).join();
print('${response.statusCode} $body');
client.close();
}{
"messageId": "00000000-0000-4000-8000-000000000001",
"status": "queued"
}202 and messageId — the message is accepted for processing (not delivered yet). Keep the messageId. All fields and responses — on the method page →
#5. Get the status
Ask no more often than poll_after_seconds in the answer suggests. Details: Delivery reports.
Done. Next: templates with variables, batch sending, event scenarios, error codes.
/v1/messages/{id}cURL. The key is in the SENDSMS_API_KEY environment variable.
curl --max-time 30 --request GET \
--url 'https://api.sendsms.to/v1/messages/MESSAGE_ID' \
--header "X-API-Key: $SENDSMS_API_KEY"Node.js 18+ (built-in fetch).
const response = await fetch("https://api.sendsms.to/v1/messages/MESSAGE_ID", {
method: "GET",
headers: {
'X-API-Key': process.env.SENDSMS_API_KEY,
},
signal: AbortSignal.timeout(30000),
});
console.log(response.status, await response.text());Python 3.8+, standard library only.
import json
import os
import urllib.error
import urllib.request
request = urllib.request.Request(
"https://api.sendsms.to/v1/messages/MESSAGE_ID",
method="GET",
headers={
"X-API-Key": os.environ["SENDSMS_API_KEY"],
},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
print(response.status, response.read().decode("utf-8"))
except urllib.error.HTTPError as error:
print(error.code, error.read().decode("utf-8"))PHP with the cURL extension.
<?php
$ch = curl_init("https://api.sendsms.to/v1/messages/MESSAGE_ID");
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => [
'X-API-Key: ' . getenv('SENDSMS_API_KEY'),
],
]);
$body = curl_exec($ch);
if ($body === false) {
throw new RuntimeException(curl_error($ch));
}
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), PHP_EOL, $body, PHP_EOL;
curl_close($ch);Ruby 2.6+, standard library: net/http, uri.
require 'net/http'
require 'uri'
uri = URI('https://api.sendsms.to/v1/messages/MESSAGE_ID')
request = Net::HTTPGenericRequest.new('GET', false, true, uri.request_uri)
request['X-API-Key'] = ENV.fetch('SENDSMS_API_KEY')
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 30, read_timeout: 30) { |http| http.request(request) }
puts "#{response.code} #{response.body}"Go, standard library.
package main
import (
"fmt"
"io"
"net/http"
"os"
"time"
)
func main() {
req, err := http.NewRequest("GET", "https://api.sendsms.to/v1/messages/MESSAGE_ID", nil)
if err != nil {
panic(err)
}
req.Header.Set("X-API-Key", os.Getenv("SENDSMS_API_KEY"))
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(data))
}.NET 6+ (HttpClient, top-level statements).
using System;
using System.Net.Http;
using System.Text;
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
using var request = new HttpRequestMessage(new HttpMethod("GET"), "https://api.sendsms.to/v1/messages/MESSAGE_ID");
request.Headers.Add("X-API-Key", Environment.GetEnvironmentVariable("SENDSMS_API_KEY"));
using var response = await client.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");Java 11+ (java.net.http). File SendSmsExample.java.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.UUID;
public class SendSmsExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.sendsms.to/v1/messages/MESSAGE_ID"))
.timeout(Duration.ofSeconds(30))
.header("X-API-Key", System.getenv("SENDSMS_API_KEY"))
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode() + " " + response.body());
}
}Dart 2.12+, dart:io and dart:convert only.
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 30);
final request = await client.openUrl('GET', Uri.parse('https://api.sendsms.to/v1/messages/MESSAGE_ID'));
request.headers.set('X-API-Key', Platform.environment['SENDSMS_API_KEY'] ?? '');
final response = await request.close().timeout(const Duration(seconds: 30));
final body = await response.transform(utf8.decoder).join();
print('${response.statusCode} $body');
client.close();
}{
"id": "00000000-0000-0000-0000-000000000002",
"status": "sent",
"status_info": {
"outcome": "pending",
"poll_after_seconds": 5
}
}status is the technical state, status_info.outcome what it means for you; poll_after_seconds — when to ask again (null — no need any more). All fields and responses — on the method page →
{
"id": "00000000-0000-0000-0000-000000000002",
"status": "delivered",
"status_info": {
"outcome": "delivered",
"poll_after_seconds": null
}
}