// For Gradle:
// dependencies {
// implementation "io.getstream:stream-chat-java:$stream_version"
// }
// You need to have io.getstream.chat.apiKey and io.getstream.chat.secretKey
// properties available, or STREAM_KEY and STREAM_SECRET environmental variables.
// For more info: https://github.com/GetStream/stream-chat-java
var token = User.createToken("john", null, null);
// Or with specific expiration:
var calendar = new GregorianCalendar();
calendar.add(Calendar.MINUTE, 60);
var token = User.createToken("john", calendar.getTime(), null);
Backend
For the average Stream integration, the development work focuses on code that executes in the client. The React, React Native, Swift, Kotlin or Flutter SDKs connect to the chat API directly from the client. However, some tasks must be executed from the server for safety.
The chat API has some features that client side code canmanage in specific cases but usually shouldn’t. While these features can be initiated with client side code. We recommend managing them server side instead unless you are certain that you need to manage them from the client side for your specific use case.
The backend has full access to the chat API.
This quick start covers the basics of a backend integration. If we don’t have an SDK for your favorite language be sure to review the REST documentation.
Generating user tokens
The backend creates a token for a user. You hand that token to the client side during login or registration. This token allows the client side to connect to the chat API for that user. Stream’s permission system does the heavy work of determining which actions are valid for the user, so the backend just needs enough logic to provide a token to give the client side access to a specific user.
The following code shows how to instantiate a client and create a token for a user on the server:
// yarn add stream-chat
import { StreamChat } from "stream-chat";
// if you're using common js
const StreamChat = require("stream-chat").StreamChat;
// instantiate your stream client using the API key and secret
// the secret is only used server side and gives you full access to the API
const serverClient = StreamChat.getInstance(
"{{ api_key }}",
"{{ api_secret }}",
);
// you can still use new StreamChat('api_key', 'api_secret');
// generate a token for the user with id 'john'
const token = serverClient.createToken("john");
// next, hand this token to the client in your in your login or registration response
# pip install stream-chat
from stream_chat import StreamChat
# instantiate your stream client using the API key and secret
# the secret is only used server side and gives you full access to the API
server_client = StreamChat(api_key="{{ api_key }}", api_secret="{{ api_secret }}")
token = server_client.create_token("john")
# next, hand this token to the client in your in your login or registration response
# gem install stream-chat-ruby
require 'stream-chat'
# instantiate your stream client using the API key and secret
# the secret is only used server side and gives you full access to the API
server_client = StreamChat::Client.new(api_key='{{ api_key }}', api_secret='{{ api_secret }}')
server_client.create_token('john')
# next, hand this token to the client in your in your login or registration response
// composer require get-stream/stream-chat
// instantiate your stream client using the API key and secret
// the secret is only used server side and gives you full access to the API
$serverClient = new GetStream\StreamChat\Client("{{ api_key }}", "{{ api_secret }}");
$token = $serverClient->createToken("john");
// next, hand this token to the client in your in your login or registration response
// go get github.com/GetStream/stream-chat-go
import stream "github.com/GetStream/stream-chat-go/v5"
// instantiate your stream client using the API key and secret
// the secret is only used server side and gives you full access to the API
client, err := stream.NewClient("{{ api_key }}", "{{ api_secret }}")
token, err := client.CreateToken("john", time.Time{})
// next, hand this token to the client in your in your login or registration response
// nuget install stream-chat-net
using StreamChat.Clients;
// Instantiate your Stream client factory using the API key and secret
// the secret is only used server side and gives you full access to the API.
var factory = new StreamClientFactory("{{ api_key }}", "{{ api_secret }}");
var userClient = factory.GetUserClient();
var token = userClient.CreateToken("john");
// Or with an expiration:
var token = userClient.CreateToken("john", DateTimeOffset.UtcNow.AddHours(1));
// Next, hand this token to the client in your in your login or registration response.
You can also generate tokens that expire after a certain time. The tokens & authentication section explains this in detail.
Syncing users
When a user starts a chat conversation with another user both users need to be present in Stream’s user storage. So you’ll want to make sure that users are synced in advance. The update users endpoint allows you to update 100 users at once, an example is shown below:
var usersUpsertRequest = User.upsert();
usersUpsertRequest.user(UserRequestObject.builder().id("bob-1").name("Bob").build());
var response = usersUpsertRequest.request();
const response = await client.upsertUsers([
{
id: userID,
role: "admin",
mycustomfield: "123",
},
]);
server_client.upsert_user({"id": user_id, "role": "admin", "mycustomfield": "123"})
client.upsert_users([{ :id => userID, :role => 'admin', :mycustomfield => '123'}])
$client->upsertUsers([['id' => 'bob-1', 'role' => 'admin', 'mycustomfield' => '123']]);
client.UpsertUser(&User{ID: userID, Role: "admin", ExtraData: map[string]interface{}{"mycustomfield": "123"}})
var user = new UserRequest
{
Id = "bob-1",
Role = Role.Admin
};
user.SetData("mycustomfield", "123");
await userClient.UpsertManyAsync(new[] { user });
curl --location --request POST 'https://chat.stream-io-api.com/users?api_key={api_key}' \
--header 'Accept: application/json' \
--header 'Stream-Auth-Type: jwt' \
--header 'Authorization: {{ YOUR TOKEN HERE }}' \
--header 'Content-Type: application/json' \
--data-raw '{
"users": { "Lakshmi": { "id" : "Lakshmi", "name": "Seethalakshmi" }}
}'
Note that user roles can only be changed server side. The role you assign to a user impacts their permissions and which actions they can take on a channel.
Syncing Channels
You can create channels client side, but for many applications you’ll want to restrict the creation of channels to the backend. Especially if a chat is related to a certain object in your database. One example is building a livestream chat like Twitch. You’ll want to create a channel for each Stream and set the channel creator to the owner of the Stream. The example below shows how to create a channel and update it:
var gandalf =
UserRequestObject.builder()
.id("gandalf-1")
.name("Gandalf the Grey")
.build();
Channel.getOrCreate("messaging", "my-team-channel")
.data(
ChannelRequestObject.builder()
.createdBy(gandalf)
.build())
.request();
const channel = client.channel(type, id, {
created_by_id: "4645",
});
await channel.create();
// create the channel and set created_by to user id 4645
const update = await channel.update({
name: "myspecialchannel",
image: "imageurl",
mycustomfield: "123",
});
channel = server_client.channel("messaging", "kung-fu")
channel.create(user_id)
channel.update({"name": "my channel", "image": "image url", "mycustomfield": "123"})
$channel = $client->Channel("messaging", "bob-and-jane");
$update = $channel->update({
'name' => 'myspecialchannel',
'color' => 'green'
});
chan = client.channel("messaging", channel_id: "bob-and-jane")
chan.update({ 'name' => 'my channel name', 'image' => 'my image url', 'mycustomfield' => '123' })
channel := client.Channel("messaging", "123")
data := map[string]interface{}{
"name": "my channel name",
"image": "img url",
"custom": "123",
}
channel.Update(ctx, data, nil)
var channelClient = factory.GetChannelClient();
var data = new ChannelRequest();
data.SetData("mycustomfield", "123");
data.CreatedBy = new UserRequest { Id = user1.Id };
await channelClient.GetOrCreateAsync("messaging", new ChannelGetRequest { Data = data });
Channel Creation
curl --location --request POST 'https://chat-proxy-singapore.stream-io-api.com/channels/{channel_type}/{cid}/query?api_key={api_key}' \
--header 'Stream-Auth-Type: jwt' \
--header 'Authorization: {{ YOUR TOKEN HERE }}' \
--header 'Content-Type: application/json' \
--data-raw '{
"data": {
"created_by_id" : "Lakshmi",
"members" : [ { "user_id" : "Bree" }, { "user_id" : "Chree"} ]
}
}'
Update Channel
curl --location --request POST 'https://chat-proxy-singapore.stream-io-api.com/channels/{channel_type}/{cid}?api_key=(api_key}' \
--header 'Stream-Auth-Type: jwt' \--header 'Authorization: {{ YOUR TOKEN HERE }}' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "Group channel",
"color": "green",
"message": { "user" : { "id" : "Lakshmi" },
"text" : "Channel color changed by Lakshmi"
}}'
You can also add a message on the channel when updating it. It’s quite common for chat apps to show messages like: “Jack invited John to the channel”, or “Kate changed the color of the channel to green”.
Adding Members or Moderators
The backend SDKs also make it easy to add or remove members from a channel. The example below shows how to add and remove members:
Channel.update("<channel-type>", "<channel-id>").addMember("john").hideHistory(true).request();
Channel.update("<channel-type>", "<channel-id>").removeMember("tommaso").request();
Channel.update("<channel-type>", "<channel-id>").addModerator("thierry").addModerator("josh").request();
Channel.update("<channel-type>", "<channel-id>").demoteModerator("tommaso").request();
await channel.addMembers(["thierry", "josh"]);
await channel.removeMembers(["tommaso"]);
await channel.addModerators(["thierry"]);
await channel.demoteModerators(["thierry"]);
channel.add_members(["thierry", "josh", "tommaso"])
channel.remove_members(["tommaso"])
channel.add_moderators(["thierry"])
channel.demote_moderators(["thierry"])
$channel.addMembers(['thierry', 'josh']);
$channel.removeMembers(['tommaso']);
$channel.addModerators(['thierry']);
$channel.demoteModerators(['thierry']);
channel.add_members(['thierry', 'josh'])
channel.remove_members(['tommaso'])
channel.add_moderators(['thierry'])
channel.demote_moderators(['thierry'])
channel.AddMembers(ctx, []string{'thierry', 'josh'});
channel.RemoveMembers(ctx, []string{'tommaso'});
channel.AddModerators(ctx, 'thierry');
channel.DemoteModerators(ctx, 'thierry');
await channelClient.AddMembersAsync("<channel-type>", "<channel-id>", "thierry", "josh");
await channelClient.RemoveMembersAsync("<channel-type>", "<channel-id>", new[] { "thierry" });
await channelClient.AddModeratorsAsync("<channel-type>", "<channel-id>", new[] { "thierry" });
await channelClient.DemoteModeratorsAsync("<channel-type>", "<channel-id>", new[] { "thierry" });
curl --location --request POST 'https://chat-proxy-singapore.stream-io-api.com/channels/{channel_type}/{cid}?api_key={api_key}' \
--header 'Accept: application/json' \
--header 'Stream-Auth-Type: jwt' \
--header 'Authorization: {{ YOUR TOKEN HERE }}' \
--header 'Content-Type: application/json' \
--data-raw '{
"add_members" : ["Seetha", "Viswa"]
}'
Sending Messages
It’s quite common that certain actions in your application trigger a message to be sent. If a new user joins an app some chat apps will notify you that your contact joined the app. The example below shows how to send a message from the backend. It’s the same syntax as you use client side, but specifying which user is sending the message is required:
var message = MessageRequestObject.builder()
.text(
"@Josh I told them I was pesca-pescatarian. Which is one who eats solely fish who eat other fish.")
.mentionedUsers(List.of(josh.getId()))
.userId(userId)
.attachment(
AttachmentRequestObject.builder()
.action(ActionRequestObject.builder().name("actionName").build())
.field(FieldRequestObject.builder().type("image").build())
.build())
.build();
message.setAdditionalField("myCustomField", "123");
Message.send("<channel-type>", "<channel-id>")
.message(message)
.request();
const toBeSent = {
text: "@Josh I told them I was pesca-pescatarian. Which is one who eats solely fish who eat other fish.",
attachments: [
{
type: "image",
asset_url: "https://bit.ly/2K74TaG",
thumb_url: "https://bit.ly/2Uumxti",
myCustomField: 123,
},
],
mentioned_users: [josh.id],
anotherCustomField: 234,
};
const message = await channel.sendMessage({ ...toBeSent, user_id: "john" });
message = {
text: "@Josh I told them I was pesca-pescatarian. Which is one who eats solely fish who eat other fish.",
attachments: [
{
type: "image",
asset_url: "https://bit.ly/2K74TaG",
thumb_url: "https://bit.ly/2Uumxti",
myCustomField: 123,
},
],
mentioned_users: [josh["id"]],
anotherCustomField: 234,
};
message = {
"text": "@Josh I told them I was pesca-pescatarian. Which is one who eats solely fish who eat other fish.",
"attachments": [
{
"type": "image",
"asset_url": "https://bit.ly/2K74TaG",
"thumb_url": "https://bit.ly/2Uumxti",
"myCustomField": 123,
}
],
"mentioned_users": [josh["id"]],
"anotherCustomField": 234,
}
channel.send_message(message, "thierry")
$toBeSent = [
"text": "@Josh I told them I was pesca-pescatarian. Which is one who eats solely fish who eat other fish.",
"attachments": [
[
"type": "image",
"asset_url": "https://bit.ly/2K74TaG",
"thumb_url": "https://bit.ly/2Uumxti",
"myCustomField": 123
]
],
"mentioned_users": [josh.id],
"anotherCustomField": 234
];
$channel->sendMessage($toBeSent, $john["id"]);
to_be_sent = {
'text' => '@Josh I told them I was pesca-pescatarian. Which is one who eats solely fish who eat other fish.',
'attachments' => [{
'type' => 'image',
'asset_url' => 'https://bit.ly/2K74TaG',
'thumb_url' => 'https://bit.ly/2Uumxti',
'myCustomField' => 123
}],
'mentioned_users' => [josh['id']],
'anotherCustomField' => 234
};
channel.send_message(to_be_sent, john['id'])
var toBeSent = &Message{
Text: '@Josh I told them I was pesca-pescatarian. Which is one who eats solely fish who eat other fish.',
Attachments: []*Attachment{
{
type: 'image',
asset_url: 'https://bit.ly/2K74TaG',
thumb_url: 'https://bit.ly/2Uumxti',
myCustomField: 123
}
},
Mentioned_users: []*User{{ID: josh.ID}},
ExtraData: map[string]interface{}{"anotherCustomField": 234},
}
channel.SendMessage(ctx, toBeSent, john.ID)
var toBeSent = new MessageRequest
{
Text = "@Josh I told them I was pesca-pescatarian. Which is one who eats solely fish who eat other fish.",
MentionedUsers = new[] { josh.ID }
};
toBeSent.SetData("customField", 234);
var attachment = new Attachment
{
Type = "image",
AssetURL = "https://bit.ly/2K74TaG",
ThumbURL = "https://bit.ly/2Uumxti",
};
attachment.SetData("myAttachmentCustomField", 123);
toBeSent.Attachments = new[] { attachment };
await messageClient.SendMessageAsync("<channel-type>", "<channel-id>", toBeSent, john.Id);
curl --location --request POST 'https://chat-proxy-singapore.stream-io-api.com/channels/{channel_type}/{cid}/message?api_key={api_key}' \
--header 'Stream-Auth-Type: jwt' \
--header 'Authorization: {{ YOUR TOKEN HERE }}' \
--header 'Content-Type: application/json' \
--data-raw '{
"message" :
{
"text" : "Hello World",
"user" : { "id" : "Lakshmi" }
}
}'
Changing Application Settings
Some application settings should only be changed using the back end for security reasons:
API Changes
A breaking change is a change that may require you to make changes to your application in order to avoid disruption to your integration. Stream will never introduce a breaking change without notifying its customers and giving them plenty of time to make the appropriate changes on their end. The following are a few examples of changes we consider breaking:
Changes to existing permission definitions.
Removal of an allowed parameter, request field or response field.
Addition of a required parameter or request field without default values.
Changes to the intended functionality of an endpoint. For example, if a DELETE request previously used to soft delete the resource but now hard deletes the resource.
Introduction of a new validation.
A non-breaking change is a change that you can adapt to at your own discretion and pace without disruption. Ensure that your application is designed to be able to handle the following types of non-breaking changes without prior notice from Stream:
Addition of new endpoints.
Addition of new methods to existing endpoints.
Addition of new fields in the following scenarios:
New fields in responses.
New optional request fields or parameters.
New required request fields that have default values.
Addition of a new value returned for an existing text field.
Changes to the order of fields returned within a response.
Addition of an optional request header.
Removal of redundant request header.
Changes to the length of data returned within a field.
Changes to the overall response size.
Changes to error messages. We do not recommend parsing error messages to perform business logic. Instead, you should only rely on HTTP response codes and error codes.
Fixes to HTTP response codes and error codes from incorrect code to correct code.
Prefix your custom data properties, we could introduce new features that might clash with custom property names you are using, by prefixing them you avoid this problem.