Can you give me an example of how to use webhook r...
# ask-ai
m
Can you give me an example of how to use webhook receiver in python backend? I mainly want to ingest room connection and room finished events.
t
Thanks for reaching out, Rishabh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Here's a friendly example of how you can use a webhook receiver in a Python backend to handle room connection and room finished events. Hopefully, this makes things a bit easier for you! Using aiohttp:
Copy code
from livekit import api
from aiohttp import web
import json
import logging

LIVEKIT_API_KEY = "your-api-key"
LIVEKIT_API_SECRET = "your-api-secret"

async def handle_webhook(request):
    token_verifier = api.TokenVerifier(LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
    webhook_receiver = api.WebhookReceiver(token_verifier)

    auth_token = request.headers.get("Authorization")
    if not auth_token:
        return web.Response(status=401, text="Missing Authorization header")

    try:
        body = await request.read()
        body_str = body.decode("utf-8")
        event = webhook_receiver.receive(body_str, auth_token)
        await handle_room_events(event)
        return web.Response(status=200, text="OK")
    except Exception as e:
        logging.error(f"Webhook processing error: {e}")
        return web.Response(status=400, text=f"Error: {e}")

async def handle_room_events(event):
    event_data = json.loads(event)
    event_type = event_data.get("event")

    if event_type == "room_started":
        await handle_room_started(event_data)
    elif event_type == "room_finished":
        await handle_room_finished(event_data)

async def handle_room_started(event_data):
    room = event_data.get("room", {})
    logging.info(f"Room started: {room.get('name')} (SID: {room.get('sid')})")

async def handle_room_finished(event_data):
    room = event_data.get("room", {})
    logging.info(f"Room finished: {room.get('name')} (SID: {room.get('sid')})")

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    app = web.Application()
    app.router.add_post("/webhook", handle_webhook)
    web.run_app(app, port=3000)
Using Flask:
Copy code
from flask import Flask, request, jsonify
from livekit import api
import json
import logging

app = Flask(__name__)

LIVEKIT_API_KEY = "your-api-key"
LIVEKIT_API_SECRET = "your-api-secret"

@app.route('/webhook', methods=['POST'])
def handle_webhook():
    try:
        token_verifier = api.TokenVerifier(LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
        webhook_receiver = api.WebhookReceiver(token_verifier)

        auth_token = request.headers.get("Authorization")
        if not auth_token:
            return jsonify({"error": "Missing Authorization header"}), 401

        body = request.get_data(as_text=True)
        event = webhook_receiver.receive(body, auth_token)
        event_data = json.loads(event)

        handle_room_events_sync(event_data)
        return jsonify({"status": "success"}), 200
    except Exception as e:
        logging.error(f"Webhook error: {e}")
        return jsonify({"error": str(e)}), 400

def handle_room_events_sync(event_data):
    event_type = event_data.get("event")

    if event_type == "room_started":
        handle_room_started_sync(event_data)
    elif event_type == "room_finished":
        handle_room_finished_sync(event_data)

def handle_room_started_sync(event_data):
    room = event_data.get("room", {})
    print(f"🟢 Room '{room.get('name')}' started (SID: {room.get('sid')})")

def handle_room_finished_sync(event_data):
    room = event_data.get("room", {})
    print(f"🔴 Room '{room.get('name')}' finished (SID: {room.get('sid')})")

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    app.run(host='0.0.0.0', port=3000, debug=True)
These snippets show you how to validate and process webhook events for room connection and room finished events. If you want me to walk you through any part or need more help, just let me know—I'm here for you! Sources: livekit-rtc/livekit/rtc/room.py | Webhooks | LiveKit Docs
m
ERRORrootWebhook error: the JSON object must be str, bytes or bytearray, not WebhookEvent 400
t
Hey there! The error you’re seeing means that the JSON object should be a string, bytes, or bytearray, but instead, a
WebhookEvent
object was passed. This usually happens when the webhook payload isn’t handled as raw data before it’s processed by the
WebhookReceiver
. To fix this, here’s what you can do: 1. Make sure you’re passing the raw body of the webhook request directly to the
WebhookReceiver.receive()
method. Avoid parsing the JSON before passing it along. 2. Double-check that your server is set up to give you raw body access for webhook endpoints. For instance, if you’re using
aiohttp
, you can use
await request.read()
to grab the raw body as a string. 3. Confirm that the
Content-Type
of the webhook request is
application/webhook+json
. Here’s a quick example of how to handle the webhook properly:
Copy code
async def handle_webhook(request):
    token_verifier = api.TokenVerifier(LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
    webhook_receiver = api.WebhookReceiver(token_verifier)

    auth_token = request.headers.get("Authorization")
    if not auth_token:
        return web.Response(status=401, text="Missing Authorization header")

    try:
        body = await request.read()  # Get raw body
        body_str = body.decode("utf-8")  # Decode to string
        event = webhook_receiver.receive(body_str, auth_token)  # Pass raw string
        await handle_room_events(event)
        return web.Response(status=200, text="OK")
    except Exception as e:
        logging.error(f"Webhook processing error: {e}")
        return web.Response(status=400, text=f"Error: {e}")
If anything’s still unclear or you want a hand with this, just let me know—I’m here to help!