# Stream Message Resource

A Stream Message is a JSON message that can be sent at a high rate to an elastic group of subscribers.

* Messages are ephemeral - they can be published (created), but they cannot be queried, updated or deleted
* The maximum Message payload size as serialized JSON is 4KB.
* The maximum Message publishing rate per Stream is 30 per second.
* Message delivery to remote endpoints is not guaranteed.
* Messages may be received by remote endpoints in a different order than they were published.

## Stream Message properties

```json
{"type":"object","refName":"sync.v1.service.sync_stream.stream_message","modelName":"sync_v1_service_sync_stream_stream_message","properties":{"sid":{"type":"string","minLength":34,"maxLength":34,"pattern":"^TZ[0-9a-fA-F]{32}$","nullable":true,"description":"The unique string that we created to identify the Stream Message resource."},"data":{"nullable":true,"description":"An arbitrary, schema-less object that contains the Stream Message body. Can be up to 4 KiB in length.","x-twilio":{"pii":{"handling":"sensitive","deleteSla":0}}}}}
```

## Create a Stream Message resource

`POST https://sync.twilio.com/v1/Services/{ServiceSid}/Streams/{StreamSid}/Messages`

Publishes a new message to the Stream. The message contains an arbitrary JSON object that is serialized and percent-encoded as a `POST` parameter.

### Path parameters

```json
[{"name":"ServiceSid","in":"path","description":"The SID of the [Sync Service](/docs/sync/api/service) to create the new Stream Message in.","schema":{"type":"string"},"required":true},{"name":"StreamSid","in":"path","description":"The SID of the Sync Stream to create the new Stream Message resource for.","schema":{"type":"string"},"required":true}]
```

### Request body parameters

```json
{"schema":{"type":"object","title":"CreateStreamMessageRequest","required":["Data"],"properties":{"Data":{"description":"A JSON string that represents an arbitrary, schema-less object that makes up the Stream Message body. Can be up to 4 KiB in length.","x-twilio":{"pii":{"handling":"sensitive","deleteSla":0}}}}},"examples":{"create":{"value":{"lang":"json","value":"{\n  \"Data\": \"{}\"\n}","meta":"","code":"{\n  \"Data\": \"{}\"\n}","tokens":[["{","#C9D1D9"],"\n  ",["\"Data\"","#7EE787"],[":","#C9D1D9"]," ",["\"{}\"","#A5D6FF"],"\n",["}","#C9D1D9"]],"annotations":[],"themeName":"github-dark","style":{"color":"#c9d1d9","background":"#0d1117"}}}},"encodingType":"application/x-www-form-urlencoded","conditionalParameterMap":{}}
```

Create a Stream Message resource

```js
// Download the helper library from https://www.twilio.com/docs/node/install
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

async function createStreamMessage() {
  const streamMessage = await client.sync.v1
    .services("ServiceSid")
    .syncStreams("StreamSid")
    .streamMessages.create({ data: {} });

  console.log(streamMessage.sid);
}

createStreamMessage();
```

```python
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)

stream_message = (
    client.sync.v1.services("ServiceSid")
    .sync_streams("StreamSid")
    .stream_messages.create(data={})
)

print(stream_message.sid)
```

```csharp
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Sync.V1.Service.SyncStream;
using System.Threading.Tasks;
using System.Collections.Generic;

class Program {
    public static async Task Main(string[] args) {
        // Find your Account SID and Auth Token at twilio.com/console
        // and set the environment variables. See http://twil.io/secure
        string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var streamMessage = await StreamMessageResource.CreateAsync(
            data: new Dictionary<string, Object>() {

            }, pathServiceSid: "ServiceSid", pathStreamSid: "StreamSid");

        Console.WriteLine(streamMessage.Sid);
    }
}
```

```java
// Install the Java helper library from twilio.com/docs/java/install

import java.util.HashMap;
import com.twilio.Twilio;
import com.twilio.rest.sync.v1.service.syncstream.StreamMessage;

public class Example {
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
    public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        StreamMessage streamMessage = StreamMessage
                                          .creator("ServiceSid",
                                              "StreamSid",
                                              new HashMap<String, Object>() {
                                                  {
                                                  }
                                              })
                                          .create();

        System.out.println(streamMessage.getSid());
    }
}
```

```go
// Download the helper library from https://www.twilio.com/docs/go/install
package main

import (
	"fmt"
	"github.com/twilio/twilio-go"
	sync "github.com/twilio/twilio-go/rest/sync/v1"
	"os"
)

func main() {
	// Find your Account SID and Auth Token at twilio.com/console
	// and set the environment variables. See http://twil.io/secure
	// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
	client := twilio.NewRestClient()

	params := &sync.CreateStreamMessageParams{}
	params.SetData(map[string]interface{}{})

	resp, err := client.SyncV1.CreateStreamMessage("ServiceSid",
		"StreamSid",
		params)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		if resp.Sid != nil {
			fmt.Println(*resp.Sid)
		} else {
			fmt.Println(resp.Sid)
		}
	}
}
```

```php
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "/path/to/vendor/autoload.php";

use Twilio\Rest\Client;

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = getenv("TWILIO_ACCOUNT_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);

$stream_message = $twilio->sync->v1
    ->services("ServiceSid")
    ->syncStreams("StreamSid")
    ->streamMessages->create(
        [] // Data
    );

print $stream_message->sid;
```

```ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'twilio-ruby'

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)

stream_message = @client
                 .sync
                 .v1
                 .services('ServiceSid')
                 .sync_streams('StreamSid')
                 .stream_messages
                 .create(data: {

                   })

puts stream_message.sid
```

```bash
# Install the twilio-cli from https://twil.io/cli

twilio api:sync:v1:services:streams:messages:create \
   --service-sid ServiceSid \
   --stream-sid StreamSid \
   --data "{}"
```

```bash
DATA_OBJ=$(cat << EOF
{

}
EOF
)
curl -X POST "https://sync.twilio.com/v1/Services/ServiceSid/Streams/StreamSid/Messages" \
--data-urlencode "Data=$DATA_OBJ" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
```

```json
{
  "sid": "TZaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "data": {}
}
```
