---
updatedAt: 2026-10-30T07:39:40.000Z
agentTools:
  projectIndex: https://docs.wati.io/llms.txt
---

# Sending Session Messages - V3

```python Python
import os
import requests

# Python with requests. One deliberate send; no automatic retry.
host = os.environ["WATI_API_HOST"].rstrip("/")  # e.g. https://live-mt-server.wati.io, without tenant ID
payload = {"target": os.environ["WATI_TARGET"], "text": "Hello from WATI", "is_bot": True}
try:
    response = requests.post(host + "/api/ext/v3/conversations/messages/text",
        headers={"Authorization": "Bearer " + os.environ["WATI_API_TOKEN"]}, json=payload, timeout=30)
except requests.RequestException as exc:
    raise RuntimeError("Outcome unknown: reconcile history/status before any resend") from exc
if not 200 <= response.status_code < 300:
    raise RuntimeError(f"HTTP {response.status_code}: inspect the response and recovery guidance; no automatic retry")
try:
    data = response.json()
except ValueError as exc:
    raise RuntimeError("Outcome unknown: expected JSON; reconcile before retrying") from exc
message = data.get("message")
if not isinstance(message, dict) or not (message.get("id") or message.get("local_message_id")):
    raise RuntimeError("Unconfirmed result: reconcile message history before retrying")
print("Returned message:", message.get("id") or message.get("local_message_id"), "— verify delivery separately")

```

```javascript JavaScript
// Node.js with built-in fetch. One deliberate send; no automatic retry.
const env = process.env;
for (const name of ["WATI_API_HOST", "WATI_API_TOKEN", "WATI_TARGET"])
  if (!env[name]) throw new Error(`Missing ${name}`);
const host = env.WATI_API_HOST.replace(/\/$/, ""); // host only, without tenant ID
const payload = {target: env.WATI_TARGET, text: "Hello from WATI", is_bot: true};
async function sendOnce() {
  let response;
  try {
    response = await fetch(host + "/api/ext/v3/conversations/messages/text", {method: "POST",
      headers: {Authorization: `Bearer ${env.WATI_API_TOKEN}`, "Content-Type": "application/json"},
      body: JSON.stringify(payload), signal: AbortSignal.timeout(30000)});
  } catch (error) { throw new Error("Outcome unknown: reconcile history/status before any resend"); }
  if (!response.ok) throw new Error(`HTTP ${response.status}: inspect response and recovery guidance; no automatic retry`);
  let data;
  try { data = await response.json(); }
  catch (error) { throw new Error("Outcome unknown: expected JSON; reconcile before retrying"); }
  const message = data.message;
if (!message || !(message.id || message.local_message_id))
  throw new Error("Unconfirmed result: reconcile message history before retrying");
console.log("Returned message:", message.id || message.local_message_id, "— verify delivery separately");
}
sendOnce().catch(error => { console.error(error.message); process.exitCode = 1; });

```

```java Java
// Java 11+ and org.json. One deliberate send; no automatic retry.
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import org.json.*;

public class WatiExample {
  static String env(String name) {
    String value = System.getenv(name);
    if (value == null || value.isEmpty()) throw new IllegalArgumentException("Missing " + name);
    return value;
  }
  public static void main(String[] args) throws Exception {
    String host = env("WATI_API_HOST").replaceAll("/$", ""); // host only, without tenant ID
    JSONObject payload = new JSONObject().put("target", env("WATI_TARGET")).put("text", "Hello from WATI").put("is_bot", true);
    HttpRequest request = HttpRequest.newBuilder(URI.create(host + "/api/ext/v3/conversations/messages/text"))
        .timeout(Duration.ofSeconds(30)).header("Authorization", "Bearer " + env("WATI_API_TOKEN"))
        .header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(payload.toString())).build();
    HttpResponse<String> response;
    try { response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); }
    catch (java.io.IOException | InterruptedException error) {
      if (error instanceof InterruptedException) Thread.currentThread().interrupt();
      throw new IllegalStateException("Outcome unknown: reconcile history/status before any resend", error);
    }
    if (response.statusCode() < 200 || response.statusCode() >= 300)
      throw new IllegalStateException("HTTP " + response.statusCode() + ": inspect response; no automatic retry");
    JSONObject data = new JSONObject(response.body());
    JSONObject message = data.optJSONObject("message");
    if (message == null || (message.optString("id").isEmpty() && message.optString("local_message_id").isEmpty()))
      throw new IllegalStateException("Unconfirmed result: reconcile message history before retrying");
    String id = message.optString("id");
    if (id.isEmpty()) id = message.optString("local_message_id");
    System.out.println("Returned message: " + id + "; verify delivery separately");
  }
}

```

```php PHP
<?php
// PHP with cURL. One deliberate send; no automatic retry.
function envRequired(string $name): string {
    $value = getenv($name);
    if ($value === false || $value === '') throw new RuntimeException("Missing $name");
    return $value;
}
$host = rtrim(envRequired('WATI_API_HOST'), '/'); // host only, without tenant ID
$payload = ['target' => envRequired('WATI_TARGET'), 'text' => 'Hello from WATI', 'is_bot' => true];
$curl = curl_init($host . '/api/ext/v3/conversations/messages/text');
curl_setopt_array($curl, [CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . envRequired('WATI_API_TOKEN'), 'Content-Type: application/json'],
    CURLOPT_POSTFIELDS => json_encode($payload, JSON_THROW_ON_ERROR)]);
$raw = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($raw === false) throw new RuntimeException('Outcome unknown: reconcile history/status before any resend');
if ($status < 200 || $status >= 300) throw new RuntimeException("HTTP $status: inspect response and recovery guidance; no automatic retry");
$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
$message = $data['message'] ?? null;
if (!is_array($message) || (empty($message['id']) && empty($message['local_message_id'])))
    throw new RuntimeException('Unconfirmed result: reconcile message history before retrying');
$id = empty($message['id']) ? $message['local_message_id'] : $message['id'];
echo 'Returned message: ' . $id . ' — verify delivery separately';

```

```csharp C#
// .NET 6+ console application. One deliberate send; no automatic retry.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;

static string Env(string name) => Environment.GetEnvironmentVariable(name) is string value && value.Length > 0
    ? value : throw new Exception("Missing " + name);
string host = Env("WATI_API_HOST").TrimEnd('/'); // host only, without tenant ID
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Env("WATI_API_TOKEN"));
var payload = new { target = Env("WATI_TARGET"), text = "Hello from WATI", is_bot = true };
HttpResponseMessage response;
try { response = await client.PostAsJsonAsync(host + "/api/ext/v3/conversations/messages/text", payload); }
catch (Exception error) when (error is HttpRequestException || error is TaskCanceledException) {
    throw new Exception("Outcome unknown: reconcile history/status before any resend", error);
}
using var responseScope = response;
if (!response.IsSuccessStatusCode) throw new Exception($"HTTP {(int)response.StatusCode}: inspect response; no automatic retry");
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var data = document.RootElement;
if (!data.TryGetProperty("message", out var message) || message.ValueKind != JsonValueKind.Object)
    throw new Exception("Unconfirmed result: reconcile message history before retrying");
string? id = message.TryGetProperty("id", out var serverId) ? serverId.GetString() : null;
if (string.IsNullOrEmpty(id)) id = message.TryGetProperty("local_message_id", out var localId) ? localId.GetString() : null;
if (string.IsNullOrEmpty(id)) throw new Exception("Unconfirmed result: reconcile before retrying");
Console.WriteLine($"Returned message: {id}; verify delivery separately");

```

```json Response Example
{
  "message": {
    "id": "<message-id>",
    "local_message_id": "<local-message-id>",
    "conversation_id": "<conversation-id>",
    "event_type": "message",
    "status": "<returned-status>"
  }
}
```

# Configure credentials

<!-- python@1 -->
<!-- javascript@1 -->
<!-- java@1 -->
<!-- php@1 -->
<!-- csharp@1 -->

Set WATI_API_HOST to your WATI API host only (for example <https://live-mt-server.wati.io>), without a workspace/tenant ID or /api suffix. Store your API token in WATI_API_TOKEN. Use the host provided for your account; do not move credentials between regions. See [Authentication](https://docs.wati.io/v2.6/reference/authentication). Examples require Python + requests, Node.js with fetch, Java 11+ + org.json, PHP + cURL, or .NET 6+.

# Select the conversation

<!-- python@1 -->
<!-- javascript@1 -->
<!-- java@1 -->
<!-- php@1 -->
<!-- csharp@1 -->

Set WATI_TARGET to a conversation ID returned by [List conversations](https://docs.wati.io/v2.6/reference/conversations_listconversations) for a supported channel. Check channel_type and the active workspace. Phone-based formats are described in [BSUID & Target Format](https://docs.wati.io/v2.6/reference/bsuid-target-format); do not guess contact/conversation IDs. List results can be limited by channel scope. This endpoint currently sends text on WhatsApp and Instagram. Automated replies use is_bot=true (the default); false is for a genuine Instagram human-agent reply, subject to its granted reply deadline. It does not bypass channel permissions or open an expired session.

# Send once and verify

<!-- python@1 -->
<!-- javascript@1 -->
<!-- java@1 -->
<!-- php@1 -->
<!-- csharp@1 -->

Confirm the recipient and text before executing. POST /api/ext/v3/conversations/messages/text with target, text and optional is_bot. HTTP 200 returns a message record; retain its id/local_message_id and confirm the final outcome through supported delivery webhooks or message history. An HTTP response is not delivery proof. On timeout, connection loss or 5xx, the send may already have been accepted; reconcile before resending. There is no idempotency guarantee in this recipe. See [Send text](https://docs.wati.io/v2.6/reference/conversations_sendtext) and [Errors](https://docs.wati.io/v2.6/reference/errors).