how do I get an access token on python serverside ...
# ask-ai
a
how do I get an access token on python serverside for my participant to join the room
t
Thanks for reaching out, Anne. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To generate an access token on a Python server-side for a participant to join a room in LiveKit, follow these steps: 1. Install the Required Package:`pip install livekit-api` 2. Set Up Environment Variables:Ensure you have the following environment variables set: ◦ `LIVEKIT_API_KEY`: Your LiveKit API key ◦ `LIVEKIT_API_SECRET`: Your LiveKit API secret 1. Generate the Token:Use the following Python code to generate the token:
Copy code
import os
from livekit import api

# Load environment variables
LIVEKIT_API_KEY = os.environ.get("LIVEKIT_API_KEY")
LIVEKIT_API_SECRET = os.environ.get("LIVEKIT_API_SECRET")

def generate_token(room_name, identity=None, name=None):
    if not identity:
        identity = f"python-user-{room_name}"

    if not name:
        name = identity

    if not LIVEKIT_API_KEY or not LIVEKIT_API_SECRET:
        raise ValueError("LIVEKIT_API_KEY and LIVEKIT_API_SECRET must be set")

    token = (
        api.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET)
        .with_identity(identity)
        .with_name(name)
        .with_grants(
            api.VideoGrants(
                room_join=True,
                room=room_name,
            )
        )
        .to_jwt()
    )

    return token
2. Optional Flask Integration:If you are using Flask, you can integrate token generation as follows: `from flask import Flask, request, jsonify from livekit import api app = Flask(name) @app.route('/generate-token', methods=['POST']) def generate_token(): data = request.json room_name = data.get("room_name") participant_identity = data.get("identity") if not room_name or not participant_identity: return jsonify({"error": "Missing roomName or identity"}), 400 token = api.AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET) \ .with_identity(participant_identity) \ .with_name(participant_identity) \ .with_grants(api.VideoGrants( room_join=True, room=room_name, )).to_jwt() return jsonify({"token": token})`This will generate a JWT token that allows the participant to join the specified room with the configured permissions. Sources: livekit-api/livekit/api/access_token.py | auth.py | complex-agents/turn-taking/turn-taking-frontend/app/api/connection-details/...