PieSocket Server Side

PieSocket server-side SDKs and examples help you publish channel events and messages from the backend, over plain HTTP, without opening a WebSocket connection yourself. See the REST API reference for the full endpoint list, and PieSocket Protocol V3 to V4 for what else changes between versions. To subscribe and listen for these messages from a browser or app, see WebSocket clients instead, this page only covers publishing.

Which path you call depends on which protocol version the connections you're targeting use, a V3 connection won't receive anything published to the V4 path and vice versa, so pick the tab that matches your cluster.

Every snippet below uses a public demo key and secret, meant only for quick testing, don't use it in your application. Get your free API key and secret here.

cURL/CLI

Using curl

curl --location --request POST 'https://CLUSTER_ID.piesocket.com/api/v4/publish' \
--header 'Content-Type: application/json' \
--data-raw '{
    "key": "oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm",
    "secret": "d8129f82f8dd71910aa4a7efa30a7297",
    "roomId": "room-1",
    "message": {"event": "new-message", "data": "Hello"}
}'

Using wget

wget --no-check-certificate --quiet \
  --method POST \
  --timeout=0 \
  --header 'Content-Type: application/json' \
  --body-data '{
    "key": "oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm",
    "secret": "d8129f82f8dd71910aa4a7efa30a7297",
    "roomId": "room-1",
    "message": {"event": "new-message", "data": "Hello"}
}' \
   'https://CLUSTER_ID.piesocket.com/api/v4/publish'

This sends a JSON event to the room room-1. To send a plain string instead, replace "message": {"event": "new-message", "data": "Hello"} with "message": "Hello world!".

PHP

$curl = curl_init();

$post_fields = [
    "key" => "oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm", // Demo key, get yours at https://piesocket.com
    "secret" => "d8129f82f8dd71910aa4a7efa30a7297", // Demo secret, get yours at https://piesocket.com
    "roomId" => "room-1",
    "message" => ["event" => "new-message", "data" => "Hello"]
];
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://CLUSTER_ID.piesocket.com/api/v4/publish",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode($post_fields),
  CURLOPT_HTTPHEADER => array(
    "Content-Type: application/json"
  ),
));

$response = curl_exec($curl);
print_r($response);

Node.js

With the PieSocket Node.js SDK

Install piesocket-nodejs:

npm i piesocket-nodejs
const PieSocket = require("piesocket-nodejs");
var piesocket = new PieSocket({
    clusterId: 'YOUR_CLUSTER_ID',
    apiKey: 'YOUR_API_KEY',
    secret: 'YOUR_API_SECRET',
    version: 4
});

piesocket.publish(roomId, data);

version defaults to 3 when omitted, see PieSocket Protocol V3 to V4.

With a raw HTTP request

var unirest = require('unirest');

var payload = {
    "key": "oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm", // Demo key, get yours at https://piesocket.com
    "secret": "d8129f82f8dd71910aa4a7efa30a7297", // Demo secret, get yours at https://piesocket.com
    "roomId": "room-1",
    "message": {"event": "new-message", "data": "Hello"}
}

var req = unirest('POST', 'https://CLUSTER_ID.piesocket.com/api/v4/publish')
    .headers({
        'Content-Type': 'application/json'
    })
    .send(JSON.stringify(payload))
    .end(function(res) {
        if (res.error) throw new Error(res.error);
        console.log(res.raw_body);
    });

Python

import requests
import json

url = "https://CLUSTER_ID.piesocket.com/api/v4/publish"
payload = json.dumps({
    "key": "oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm",  # Demo key, get yours at https://piesocket.com
    "secret": "d8129f82f8dd71910aa4a7efa30a7297",  # Demo secret, get yours at https://piesocket.com
    "roomId": "room-1",
    "message": {"event": "new-message", "data": "Hello"}
})
headers = {
  'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text.encode('utf8'))

Ruby

require "uri"
require "net/http"
require "json"

url = URI("https://CLUSTER_ID.piesocket.com/api/v4/publish")

https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Content-Type"] = "application/json"
request.body = {
    key: "oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm", # Demo key, get yours at https://piesocket.com
    secret: "d8129f82f8dd71910aa4a7efa30a7297", # Demo secret, get yours at https://piesocket.com
    roomId: "room-1",
    message: {"event": "new-message", "data": "Hello"}
}.to_json

response = https.request(request)
puts response.read_body

Java

public class Publish {

  public static void main(String[] args) throws Exception {

    OkHttpClient client = new OkHttpClient().newBuilder().build();
    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(
      mediaType,
      // Demo key and secret, get yours at https://piesocket.com
      "{\"key\":\"oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm\",\"secret\":\"d8129f82f8dd71910aa4a7efa30a7297\",\"roomId\":\"room-1\",\"message\":{\"event\":\"new-message\",\"data\":\"Hello\"}}"
    );
    Request request = new Request.Builder()
      .url("https://CLUSTER_ID.piesocket.com/api/v4/publish")
      .method("POST", body)
      .addHeader("Content-Type", "application/json")
      .build();
    Response response = client.newCall(request).execute();

  }

}

Go

package main

import (
  "fmt"
  "io"
  "net/http"
  "strings"
)

func main() {
  url := "https://CLUSTER_ID.piesocket.com/api/v4/publish"
  method := "POST"

  // Demo key and secret, get yours at https://piesocket.com
  payload := strings.NewReader(`{"key":"oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm","secret":"d8129f82f8dd71910aa4a7efa30a7297","roomId":"room-1","message":{"event":"new-message","data":"Hello"}}`)

  client := &http.Client{}
  req, err := http.NewRequest(method, url, payload)
  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()
  body, err := io.ReadAll(res.Body)

  fmt.Println(string(body))
}

C#

using System.Net.Http;
using System.Text;
using System.Text.Json;

var payload = new
{
    key = "oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm", // Demo key, get yours at https://piesocket.com
    secret = "d8129f82f8dd71910aa4a7efa30a7297", // Demo secret, get yours at https://piesocket.com
    roomId = "room-1",
    message = new { @event = "new-message", data = "Hello" }
};

using var client = new HttpClient();
var content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://CLUSTER_ID.piesocket.com/api/v4/publish", content);

Console.WriteLine(await response.Content.ReadAsStringAsync());

Help

Facing difficulties? Use the chat box on the bottom-right corner of this page to reach us.