# Your First API Request
URL: /docs/getting-started/first-request

> Send your very first transactional SMS message in under five minutes with copy-pasteable examples in cURL, TypeScript, Python, PHP, and Java.

This guide sends the first SMS with an `sk_test_` key on `https://api.smspro.com`. Magic numbers keep the send simulated and free of wallet charges.

---

## 1. The API Request [#1-the-api-request]

To send a message, submit an HTTP `POST` request to the `/api/v1/public/sms/send` endpoint. 

Select your language of choice below to copy a complete, functional code sample:

<Tabs items={["cURL","TypeScript (Node.js)","Python","PHP","Java"]}>
<Tab value="cURL">
```bash
curl -X POST "https://api.smspro.com/api/v1/public/sms/send" \
  -H "X-Api-Key: sk_test_948f293048a1b2c3d4e5f60718" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)" \
  -d '{
    "to": "+233200000001",
    "senderId": "SMSPRO",
    "message": "Welcome to SMS Pro! Your first API test is successful."
  }'
```
</Tab>

<Tab value="TypeScript (Node.js)">
```ts title="send-sms.ts"
import crypto from 'node:crypto';

interface SendSmsResponse {
  status: string;
  message: string;
  data: {
    jobId: string;
    messageId: string;
    status: string;
    segmentCount: number;
    totalUnits: number;
  };
}

async function sendFirstSms() {
  const apiKey = process.env.SMSPRO_API_KEY || 'sk_test_948f293048a1b2c3d4e5f60718';
  const baseUrl = 'https://api.smspro.com';

  const response = await fetch(`${baseUrl}/api/v1/public/sms/send`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Api-Key': apiKey,
      'Idempotency-Key': crypto.randomUUID(),
    },
    body: JSON.stringify({
      to: '+233200000001',
      senderId: 'SMSPRO',
      message: 'Welcome to SMS Pro! Your first API test is successful.',
    }),
  });

  const payload: SendSmsResponse = await response.json();

  if (!response.ok) {
    console.error(`Dispatch failed [${response.status}]:`, payload);
    return;
  }

  console.log('✅ SMS Queued Successfully:');
  console.log(`Job ID:     ${payload.data.jobId}`);
  console.log(`Message ID: ${payload.data.messageId}`);
  console.log(`Segments:   ${payload.data.segmentCount}`);
}

sendFirstSms();
```
</Tab>

<Tab value="Python">
```python title="send_sms.py"
import os
import uuid
import requests

API_KEY = os.getenv("SMSPRO_API_KEY", "sk_test_948f293048a1b2c3d4e5f60718")
BASE_URL = "https://api.smspro.com"

headers = {
    "Content-Type": "application/json",
    "X-Api-Key": API_KEY,
    "Idempotency-Key": str(uuid.uuid4())
}

payload = {
    "to": "+233200000001",
    "senderId": "SMSPRO",
    "message": "Welcome to SMS Pro! Your first API test is successful."
}

response = requests.post(f"{BASE_URL}/api/v1/public/sms/send", json=payload, headers=headers)
data = response.json()

if response.status_code == 202:
    print("✅ SMS Queued Successfully:")
    print(f"Job ID:     {data['data']['jobId']}")
    print(f"Message ID: {data['data']['messageId']}")
    print(f"Segments:   {data['data']['segmentCount']}")
else:
    print(f"❌ Error [{response.status_code}]: {data}")
```
</Tab>

<Tab value="PHP">
```php title="send_sms.php"
<?php

$apiKey = getenv('SMSPRO_API_KEY') ?: 'sk_test_948f293048a1b2c3d4e5f60718';
$baseUrl = 'https://api.smspro.com';

$payload = [
    'to' => '+233200000001',
    'senderId' => 'SMSPRO',
    'message' => 'Welcome to SMS Pro! Your first API test is successful.'
];

$ch = curl_init("{$baseUrl}/api/v1/public/sms/send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'X-Api-Key: ' . $apiKey,
    'Idempotency-Key: ' . bin2hex(random_bytes(16))
]);

$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$data = json_decode($response, true);

if ($statusCode === 202) {
    echo "✅ SMS Queued Successfully:\n";
    echo "Job ID:     " . $data['data']['jobId'] . "\n";
    echo "Message ID: " . $data['data']['messageId'] . "\n";
} else {
    echo "❌ Error [{$statusCode}]: " . $response . "\n";
}
```
</Tab>

<Tab value="Java">
```java title="SendSms.java"
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.UUID;

public class SendSms {
    public static void main(String[] args) throws Exception {
        String apiKey = System.getenv().getOrDefault("SMSPRO_API_KEY", "sk_test_948f293048a1b2c3d4e5f60718");
        String endpoint = "https://api.smspro.com/api/v1/public/sms/send";

        String jsonPayload = """
            {
                "to": "+233200000001",
                "senderId": "SMSPRO",
                "message": "Welcome to SMS Pro! Your first API test is successful."
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(endpoint))
            .header("Content-Type", "application/json")
            .header("X-Api-Key", apiKey)
            .header("Idempotency-Key", UUID.randomUUID().toString())
            .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("HTTP Status: " + response.statusCode());
        System.out.println("Response:    " + response.body());
    }
}
```
</Tab>
</Tabs>

---

## 2. Request Component Breakdown [#2-request-component-breakdown]

Let's dissect each component of the request:

### HTTP Headers [#http-headers]
- **`X-Api-Key`**: Authenticates the call. `sk_test_` simulates delivery on this same API.
- **`Content-Type: application/json`**: Signals to the gateway that the request body is a JSON-encoded string.
- **`Idempotency-Key`**: A random UUID identifying this specific transmission attempt. If network connectivity drops and your client retries the exact same call, the gateway guarantees the message will not be queued a second time.

### JSON Request Body [#json-request-body]
- **`to`**: Destination phone number. In this example, `+233200000001` is a reserved **Sandbox Magic Number** that causes the mock gateway to simulate an immediate successful delivery (`DELIVERED`). In production, SMS Pro accepts local format (`0241234567`), international without plus (`233241234567`), and standard E.164 (`+233241234567`), normalizing them automatically.
- **`senderId`**: Up to 11 alphanumeric characters (e.g. `SMSPRO`).
- **`message`**: The text string to deliver to the recipient.

---

## 3. Dissecting the Response [#3-dissecting-the-response]

A successful dispatch returns **HTTP `202 Accepted`**. The `202` status code indicates that the message has been validated, accepted by the ingestion pipeline, and queued for telco transmission:

```json
{
  "status": "success",
  "message": "Queued",
  "data": {
    "jobId": "job-d41d8cd9-8f00-4b11-b841-892104ab0123",
    "messageIds": ["c7a8b9e0-1234-5678-9abc-def012345678"],
    "messageId": "c7a8b9e0-1234-5678-9abc-def012345678",
    "status": "ACCEPTED",
    "segmentCount": 1,
    "totalUnits": 1
  }
}
```

### Response Fields Explained [#response-fields-explained]
- **`jobId`**: Identifier for the background dispatch job. For bulk sends, one job encompasses many messages.
- **`messageId`**: Unique identifier for this specific recipient delivery. Store this key in your database to correlate future delivery receipts (`DLR`).
- **`status`**: Current pipeline state. Begins at `ACCEPTED` or `QUEUED`, and later transitions to `SENT`, `DELIVERED`, or `FAILED`.
- **`segmentCount`**: The number of 160-character (GSM-7) or 70-character (UCS-2) SMS segments computed for your message text.
- **`totalUnits`**: Billing unit cost calculated for this dispatch (in sandbox, 0 balance is deducted).

---

## 4. Polling Delivery Status [#4-polling-delivery-status]

To query the current state of your message, send a `GET` request to `/api/v1/public/sms/messages/{messageId}`:

```bash
curl -X GET "https://api.smspro.com/api/v1/public/sms/messages/c7a8b9e0-1234-5678-9abc-def012345678" \
  -H "X-Api-Key: sk_test_948f293048a1b2c3d4e5f60718"
```

Because `+233200000001` is a success magic number, the status will immediately report `DELIVERED`:

```json
{
  "status": "success",
  "message": "Message details retrieved",
  "data": {
    "id": "c7a8b9e0-1234-5678-9abc-def012345678",
    "to": "+233200000001",
    "senderId": "SMSPRO",
    "status": "DELIVERED",
    "deliveredAt": "2026-11-18T08:45:10Z"
  }
}
```

---

## Next Step [#next-step]

Learn how to parse standard response envelopes, handle HTTP status codes, and manage errors in [Understanding Responses](/docs/getting-started/understanding-responses).