← Back to Services

Chat Service gRPC-Web API - Automation Guide

This document provides curl commands for testing and automating the Chat Service gRPC-Web API.

Endpoints

gRPC vs gRPC-Web

This service supports both native gRPC and gRPC-Web protocols:

Native gRPC (Direct Connection)

gRPC-Web (via Envoy Proxy)

Accessing via Envoy Proxy

When using grpcurl to access services through Envoy proxy on port 443, use the following format:

# List available services (chat is default, no special header needed)
grpcurl -insecure grpc-envoy.qa.akamai.com:443 list

# Call a service method
grpcurl -insecure -d '{}' \
  grpc-envoy.qa.akamai.com:443 chat.ChatService/GetRooms

Why no header? The chat service is configured as the default backend in Envoy, so requests without an x-service-target header automatically route to the chat service. Other services (ecommerce, stock-ticker) require the x-service-target header to explicitly route to their respective backends.

Note: The -servername flag is required when using localhost with TLS to match the certificate's domain name.

Prerequisites

All requests use: - Content-Type: application/grpc-web+proto - X-Grpc-Web: 1 - X-User-Agent: grpc-web-javascript/0.1

Python Helper Script

First, create a helper script to generate protobuf messages:

cat > /tmp/grpc_helper.py << 'EOF'
import struct
import sys

def encode_varint(value):
    result = []
    while value >= 0x80:
        result.append((value & 0x7F) | 0x80)
        value >>= 7
    result.append(value)
    return bytes(result)

def encode_string_field(field_number, value):
    string_bytes = value.encode('utf-8')
    tag = (field_number << 3) | 2  # Wire type 2 (length-delimited)
    return encode_varint(tag) + encode_varint(len(string_bytes)) + string_bytes

def create_grpc_frame(message):
    return b'\x00' + struct.pack('>I', len(message)) + message

def create_send_message(room_id, username, content):
    message = (
        encode_string_field(1, room_id) +
        encode_string_field(2, username) +
        encode_string_field(3, content)
    )
    return create_grpc_frame(message)

def create_leave_room(room_id, username):
    message = (
        encode_string_field(1, room_id) +
        encode_string_field(2, username)
    )
    return create_grpc_frame(message)

def create_get_rooms():
    return create_grpc_frame(b'')  # Empty message

def create_get_room_users(room_id):
    message = encode_string_field(1, room_id)
    return create_grpc_frame(message)

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python grpc_helper.py <command> [args...]")
        sys.exit(1)

    command = sys.argv[1]

    if command == "send_message":
        if len(sys.argv) != 5:
            print("Usage: python grpc_helper.py send_message <room_id> <username> <content>")
            sys.exit(1)
        data = create_send_message(sys.argv[2], sys.argv[3], sys.argv[4])
    elif command == "leave_room":
        if len(sys.argv) != 4:
            print("Usage: python grpc_helper.py leave_room <room_id> <username>")
            sys.exit(1)
        data = create_leave_room(sys.argv[2], sys.argv[3])
    elif command == "get_rooms":
        data = create_get_rooms()
    elif command == "get_room_users":
        if len(sys.argv) != 3:
            print("Usage: python grpc_helper.py get_room_users <room_id>")
            sys.exit(1)
        data = create_get_room_users(sys.argv[2])
    else:
        print(f"Unknown command: {command}")
        sys.exit(1)

    sys.stdout.buffer.write(data)
EOF

Protobuf Response Parser

Add this helper script to decode gRPC-Web responses into readable protobuf:

cat > /tmp/parse_grpc_response.py << 'EOF'
import struct
import sys
import subprocess
import os

def parse_grpc_web_response(response_file, message_type, proto_file="chat-service/proto/chat.proto"):
    """Parse gRPC-Web binary response and decode using protoc"""

    # Read the response data
    with open(response_file, "rb") as f:
        data = f.read()

    if len(data) < 5:
        print("Response too short")
        return

    # Parse gRPC-Web frames
    i = 0
    frame_count = 0

    while i < len(data):
        if i + 5 > len(data):
            break

        flag = data[i]
        n = struct.unpack(">I", data[i+1:i+5])[0]
        i += 5

        if i + n > len(data):
            break

        body = data[i:i+n]
        i += n

        if flag == 0:  # data frame (uncompressed)
            frame_file = f"/tmp/frame{frame_count}.pb"
            with open(frame_file, "wb") as f:
                f.write(body)

            print(f"=== Frame {frame_count} (Data) ===")

            # Use protoc to decode the protobuf message
            try:
                result = subprocess.run([
                    "protoc", 
                    f"--proto_path={os.path.dirname(proto_file)}/", 
                    "--decode", message_type, 
                    proto_file
                ], input=body, capture_output=True)

                if result.returncode == 0:
                    print(result.stdout.decode('utf-8'))
                else:
                    print(f"Protoc decode error: {result.stderr.decode('utf-8')}")
                    print(f"Raw hex: {body.hex()}")
            except FileNotFoundError:
                print("protoc not found, showing raw hex:")
                print(f"Raw hex: {body.hex()}")

            frame_count += 1

        elif flag == 0x80:  # trailer frame
            print(f"=== Frame {frame_count} (Trailers) ===")
            trailer_text = body.decode('utf-8', errors='ignore')
            print(trailer_text)
            frame_count += 1

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python parse_grpc_response.py <response_file> <message_type> [proto_file]")
        print("Examples:")
        print("  python parse_grpc_response.py /tmp/response.bin chat.GetRoomsResponse")
        print("  python parse_grpc_response.py /tmp/response.bin chat.GetRoomUsersResponse")
        sys.exit(1)

    response_file = sys.argv[1]
    message_type = sys.argv[2]
    proto_file = sys.argv[3] if len(sys.argv) > 3 else "chat-service/proto/chat.proto"

    parse_grpc_web_response(response_file, message_type, proto_file)
EOF

Basic Operations

1. Get List of Active Rooms

Method A: Native gRPC (Direct to Service)

# List all available services
grpcurl -plaintext localhost:8051 list

# Get all active rooms - simplest method
grpcurl -plaintext localhost:8051 chat.ChatService/GetRooms

# Using proto file explicitly
grpcurl -proto chat-service/proto/chat.proto \
  -plaintext localhost:8051 \
  chat.ChatService/GetRooms

Method B: gRPC via Envoy Proxy (TLS)

# Via HTTPS proxy (production)
grpcurl -d '{}' grpc-envoy.qa.akamai.com:443 chat.ChatService/GetRooms

# Via local Envoy proxy
grpcurl -plaintext -d '{}' localhost:8080 chat.ChatService/GetRooms

Method C: gRPC-Web via curl

# Create the request
python3 /tmp/grpc_helper.py get_rooms > /tmp/get_rooms.bin

# Send the request and save response
curl -s -X POST \
  https://grpc-envoy.qa.akamai.com/chat.ChatService/GetRooms \
  -H "Content-Type: application/grpc-web+proto" \
  -H "X-Grpc-Web: 1" \
  -H "X-User-Agent: grpc-web-javascript/0.1" \
  --data-binary @/tmp/get_rooms.bin \
  --output /tmp/get_rooms_response.bin

# Parse the response
python3 /tmp/parse_grpc_response.py /tmp/get_rooms_response.bin chat.GetRoomsResponse

2. Send Message (Auto-creates room and joins user)

Method A: Native gRPC (Direct to Service)

# Send message (creates room if it doesn't exist and adds user)
grpcurl -plaintext -d '{
  "room_id": "lobby",
  "username": "alice",
  "content": "Hello everyone!"
}' localhost:8051 chat.ChatService/SendMessage

# Send different messages to different rooms
grpcurl -plaintext -d '{"room_id": "general", "username": "bob", "content": "Hi from Bob!"}' localhost:8051 chat.ChatService/SendMessage
grpcurl -plaintext -d '{"room_id": "tech-talk", "username": "charlie", "content": "Anyone discussing React?"}' localhost:8051 chat.ChatService/SendMessage

Method B: gRPC via Envoy Proxy (TLS)

# Via HTTPS proxy
grpcurl -d '{
  "room_id": "lobby",
  "username": "alice",
  "content": "Hello from production!"
}' grpc-envoy.qa.akamai.com:443 chat.ChatService/SendMessage

# Via local Envoy proxy
grpcurl -plaintext -d '{
  "room_id": "general",
  "username": "bob",
  "content": "Testing via Envoy proxy"
}' localhost:8080 chat.ChatService/SendMessage

Method C: gRPC-Web via curl

# Send a message to "lobby" room as "alice"
python3 /tmp/grpc_helper.py send_message "lobby" "alice" "Hello everyone!" > /tmp/send_message.bin

curl -v -X POST \
  https://grpc-envoy.qa.akamai.com/chat.ChatService/SendMessage \
  -H "Content-Type: application/grpc-web+proto" \
  -H "X-Grpc-Web: 1" \
  -H "X-User-Agent: grpc-web-javascript/0.1" \
  --data-binary @/tmp/send_message.bin \
  --output /tmp/send_response.bin

# Parse the response
python3 /tmp/parse_grpc_response.py /tmp/send_response.bin chat.SendMessageResponse

3. GetRoomUsers

Get a list of all users currently in a specific chat room.

gRPC Definition:

rpc GetRoomUsers(GetRoomUsersRequest) returns (GetRoomUsersResponse);

message GetRoomUsersRequest {
  string room_id = 1;
}

message GetRoomUsersResponse {
  repeated string usernames = 1;
  bool success = 2;
  string error_message = 3;
}

Method A: Direct gRPC (grpcurl with reflection)

# Get users in the "lobby" room
grpcurl -plaintext -d '{"room_id": "lobby"}' \
  localhost:8051 chat.ChatService/GetRoomUsers

# Get users in different rooms
grpcurl -plaintext -d '{"room_id": "general"}' \
  localhost:8051 chat.ChatService/GetRoomUsers

grpcurl -plaintext -d '{"room_id": "tech-talk"}' \
  localhost:8051 chat.ChatService/GetRoomUsers

Method B: gRPC via Envoy (grpcurl with TLS)

# External access through Envoy proxy
grpcurl -d '{"room_id": "lobby"}' \
  grpc-envoy.qa.akamai.com:443 chat.ChatService/GetRoomUsers

# Get users with error handling
grpcurl -d '{"room_id": "nonexistent-room"}' \
  grpc-envoy.qa.akamai.com:443 chat.ChatService/GetRoomUsers

Method C: gRPC-Web via HTTP (curl)

# Get users in lobby room
echo '{"room_id": "lobby"}' | \
curl -k -X POST https://grpc-envoy.qa.akamai.com/chat.ChatService/GetRoomUsers \
  -H "Content-Type: application/grpc-web+json" \
  -H "X-Grpc-Web: 1" \
  --data-binary @-

# Get users in general room
echo '{"room_id": "general"}' | \
curl -k -X POST https://grpc-envoy.qa.akamai.com/chat.ChatService/GetRoomUsers \
  -H "Content-Type: application/grpc-web+json" \
  -H "X-Grpc-Web: 1" \
  --data-binary @-

Sample Response:

{
  "users": [
    {
      "username": "alice",
      "joinedAt": "1760419937"
    },
    {
      "username": "bob",
      "joinedAt": "1760419958"
    }
  ]
}

4. LeaveRoom

Remove a user from a specific chat room.

gRPC Definition:

rpc LeaveRoom(LeaveRoomRequest) returns (LeaveRoomResponse);

message LeaveRoomRequest {
  string room_id = 1;
  string username = 2;
}

message LeaveRoomResponse {
  bool success = 1;
  string message = 2;
  string error_message = 3;
}

Method A: Direct gRPC (grpcurl with reflection)

# User "alice" leaves the "lobby" room
grpcurl -plaintext -d '{
  "room_id": "lobby",
  "username": "alice"
}' localhost:8051 chat.ChatService/LeaveRoom

# Multiple users leaving different rooms
grpcurl -plaintext -d '{"room_id": "general", "username": "bob"}' \
  localhost:8051 chat.ChatService/LeaveRoom

grpcurl -plaintext -d '{"room_id": "tech-talk", "username": "charlie"}' \
  localhost:8051 chat.ChatService/LeaveRoom

Method B: gRPC via Envoy (grpcurl with TLS)

# External access through Envoy proxy
grpcurl -d '{
  "room_id": "lobby",
  "username": "alice"
}' grpc-envoy.qa.akamai.com:443 chat.ChatService/LeaveRoom

# Leave with error handling for non-existent user
grpcurl -d '{
  "room_id": "lobby", 
  "username": "nonexistent_user"
}' grpc-envoy.qa.akamai.com:443 chat.ChatService/LeaveRoom

Method C: gRPC-Web via HTTP (curl)

# User leaves lobby room
echo '{
  "room_id": "lobby",
  "username": "alice"
}' | curl -k -X POST https://grpc-envoy.qa.akamai.com/chat.ChatService/LeaveRoom \
  -H "Content-Type: application/grpc-web+json" \
  -H "X-Grpc-Web: 1" \
  --data-binary @-

# Multiple users leaving
echo '{"room_id": "general", "username": "bob"}' | \
curl -k -X POST https://grpc-envoy.qa.akamai.com/chat.ChatService/LeaveRoom \
  -H "Content-Type: application/grpc-web+json" \
  -H "X-Grpc-Web: 1" \
  --data-binary @-

echo '{"room_id": "tech-talk", "username": "charlie"}' | \
curl -k -X POST https://grpc-envoy.qa.akamai.com/chat.ChatService/LeaveRoom \
  -H "Content-Type: application/grpc-web+json" \
  -H "X-Grpc-Web: 1" \
  --data-binary @-

Sample Response:

{
  "success": true
}

Complete Automation Script

Here's a complete script that demonstrates the workflow:

#!/bin/bash
# chat_automation.sh

ENDPOINT="https://grpc-envoy.qa.akamai.com"

echo "=== Chat Service Automation Demo ==="

# Step 1: Check initial rooms (should be empty)
echo "1. Getting initial rooms..."
python3 /tmp/grpc_helper.py get_rooms > /tmp/get_rooms.bin
curl -s -X POST "$ENDPOINT/chat.ChatService/GetRooms" \
  -H "Content-Type: application/grpc-web+proto" \
  -H "X-Grpc-Web: 1" \
  -H "X-User-Agent: grpc-web-javascript/0.1" \
  --data-binary @/tmp/get_rooms.bin \
  --output /tmp/get_rooms_response.bin
python3 /tmp/parse_grpc_response.py /tmp/get_rooms_response.bin chat.GetRoomsResponse
echo

# Step 2: Create room by having first user send message
echo "2. Alice joins 'general' room..."
python3 /tmp/grpc_helper.py send_message "general" "alice" "Hi, I'm Alice!" > /tmp/send1.bin
curl -s -X POST "$ENDPOINT/chat.ChatService/SendMessage" \
  -H "Content-Type: application/grpc-web+proto" \
  -H "X-Grpc-Web: 1" \
  -H "X-User-Agent: grpc-web-javascript/0.1" \
  --data-binary @/tmp/send1.bin \
  --output /tmp/send1_response.bin -k
python3 /tmp/parse_grpc_response.py /tmp/send1_response.bin chat.SendMessageResponse
echo "Alice sent message"

# Step 3: Second user joins
echo "3. Bob joins 'general' room..."
python3 /tmp/grpc_helper.py send_message "general" "bob" "Hey Alice, it's Bob!" > /tmp/send2.bin
curl -s -X POST "$ENDPOINT/chat.ChatService/SendMessage" \
  -H "Content-Type: application/grpc-web+proto" \
  -H "X-Grpc-Web: 1" \
  -H "X-User-Agent: grpc-web-javascript/0.1" \
  --data-binary @/tmp/send2.bin \
  --output /tmp/send2_response.bin -k
python3 /tmp/parse_grpc_response.py /tmp/send2_response.bin chat.SendMessageResponse
echo "Bob sent message"

# Step 4: Third user joins
echo "4. Charlie joins 'general' room..."
python3 /tmp/grpc_helper.py send_message "general" "charlie" "Hello Alice and Bob!" > /tmp/send3.bin
curl -s -X POST "$ENDPOINT/chat.ChatService/SendMessage" \
  -H "Content-Type: application/grpc-web+proto" \
  -H "X-Grpc-Web: 1" \
  -H "X-User-Agent: grpc-web-javascript/0.1" \
  --data-binary @/tmp/send3.bin \
  --output /tmp/send3_response.bin
python3 /tmp/parse_grpc_response.py /tmp/send3_response.bin chat.SendMessageResponse
echo "Charlie sent message"

# Step 5: Check rooms (should show 1 room with 3 users)
echo "5. Checking rooms after all users joined..."
curl -s -X POST "$ENDPOINT/chat.ChatService/GetRooms" \
  -H "Content-Type: application/grpc-web+proto" \
  -H "X-Grpc-Web: 1" \
  -H "X-User-Agent: grpc-web-javascript/0.1" \
  --data-binary @/tmp/get_rooms.bin \
  --output /tmp/get_rooms_response2.bin
python3 /tmp/parse_grpc_response.py /tmp/get_rooms_response2.bin chat.GetRoomsResponse
echo

# Step 6: Check users in room
echo "6. Getting users in 'general' room..."
python3 /tmp/grpc_helper.py get_room_users "general" > /tmp/get_users.bin
curl -s -X POST "$ENDPOINT/chat.ChatService/GetRoomUsers" \
  -H "Content-Type: application/grpc-web+proto" \
  -H "X-Grpc-Web: 1" \
  -H "X-User-Agent: grpc-web-javascript/0.1" \
  --data-binary @/tmp/get_users.bin \
  --output /tmp/get_users_response.bin
python3 /tmp/parse_grpc_response.py /tmp/get_users_response.bin chat.GetRoomUsersResponse
echo

# Step 7: Alice leaves
echo "7. Alice leaves the room..."
python3 /tmp/grpc_helper.py leave_room "general" "alice" > /tmp/leave1.bin
curl -s -X POST "$ENDPOINT/chat.ChatService/LeaveRoom" \
  -H "Content-Type: application/grpc-web+proto" \
  -H "X-Grpc-Web: 1" \
  -H "X-User-Agent: grpc-web-javascript/0.1" \
  --data-binary @/tmp/leave1.bin \
  --output /tmp/leave1_response.bin
python3 /tmp/parse_grpc_response.py /tmp/leave1_response.bin chat.LeaveRoomResponse
echo "Alice left"

# Step 8: Bob leaves
echo "8. Bob leaves the room..."
python3 /tmp/grpc_helper.py leave_room "general" "bob" > /tmp/leave2.bin
curl -s -X POST "$ENDPOINT/chat.ChatService/LeaveRoom" \
  -H "Content-Type: application/grpc-web+proto" \
  -H "X-Grpc-Web: 1" \
  -H "X-User-Agent: grpc-web-javascript/0.1" \
  --data-binary @/tmp/leave2.bin \
  --output /tmp/leave2_response.bin
python3 /tmp/parse_grpc_response.py /tmp/leave2_response.bin chat.LeaveRoomResponse
echo "Bob left"

# Step 9: Check room status (should show 1 user)
echo "9. Checking room after 2 users left..."
curl -s -X POST "$ENDPOINT/chat.ChatService/GetRooms" \
  -H "Content-Type: application/grpc-web+proto" \
  -H "X-Grpc-Web: 1" \
  -H "X-User-Agent: grpc-web-javascript/0.1" \
  --data-binary @/tmp/get_rooms.bin \
  --output /tmp/get_rooms_response3.bin
python3 /tmp/parse_grpc_response.py /tmp/get_rooms_response3.bin chat.GetRoomsResponse
echo

# Step 10: Charlie leaves (room should be deleted)
echo "10. Charlie leaves the room (should delete room)..."
python3 /tmp/grpc_helper.py leave_room "general" "charlie" > /tmp/leave3.bin
curl -s -X POST "$ENDPOINT/chat.ChatService/LeaveRoom" \
  -H "Content-Type: application/grpc-web+proto" \
  -H "X-Grpc-Web: 1" \
  -H "X-User-Agent: grpc-web-javascript/0.1" \
  --data-binary @/tmp/leave3.bin \
  --output /tmp/leave3_response.bin
python3 /tmp/parse_grpc_response.py /tmp/leave3_response.bin chat.LeaveRoomResponse
echo "Charlie left"

# Step 11: Final check (should be empty)
echo "11. Final check - rooms should be empty..."
curl -s -X POST "$ENDPOINT/chat.ChatService/GetRooms" \
  -H "Content-Type: application/grpc-web+proto" \
  -H "X-Grpc-Web: 1" \
  -H "X-User-Agent: grpc-web-javascript/0.1" \
  --data-binary @/tmp/get_rooms.bin \
  --output /tmp/get_rooms_response4.bin
python3 /tmp/parse_grpc_response.py /tmp/get_rooms_response4.bin chat.GetRoomsResponse

echo "=== Demo Complete ==="

Response Format

All responses are in gRPC-Web format: - First 5 bytes: gRPC frame header (compression flag + 4-byte length) - Remaining bytes: Protobuf message data - Trailers: gRPC status and message headers

Error Handling

Make Scripts Executable

chmod +x /tmp/grpc_helper.py
chmod +x /tmp/parse_grpc_response.py
chmod +x chat_automation.sh

Example Usage

# Create the helper scripts first
python3 /tmp/grpc_helper.py get_rooms > /tmp/test.bin

# Test protobuf parsing
curl -s -X POST https://grpc-envoy.qa.akamai.com/chat.ChatService/GetRooms \
  -H "Content-Type: application/grpc-web+proto" \
  -H "X-Grpc-Web: 1" \
  -H "X-User-Agent: grpc-web-javascript/0.1" \
  --data-binary @/tmp/test.bin \
  --output /tmp/test_response.bin

python3 /tmp/parse_grpc_response.py /tmp/test_response.bin chat.GetRoomsResponse

# Run the full automation
./chat_automation.sh

Sample Parsed Output

The protobuf parser will show readable output like:

=== Frame 0 (Data) ===
rooms {
  room_id: "general"
  name: "general"
  user_count: 2
}

=== Frame 1 (Trailers) ===
grpc-status:0
grpc-message:

This automation script demonstrates: 1. ✅ Create a room by having users send messages 2. ✅ Join 3 users (alice, bob, charlie)
3. ✅ Send chat messages between users 4. ✅ Have 2 users leave the room 5. ✅ Verify user counts are updated correctly 6. ✅ Show room deletion when last user leaves