The XAPlayer secure player with Python: Django and Flask

Add to your site3 min read

Get a playback token with the requests library and show the XAPlayer secure player from a Django view or a Flask route.

All guides

You’ll write one shared token function and use it from Django or Flask. The only dependency is requests.

Before you start#

  1. In your XAPlayer panel, open Settings and create an API key. It is shown only once, so copy it right away.
  2. Under Websites allowed to show your player, add your site’s full address, such as https://academy.example.com. If your site also opens with www, add that too.
  3. Get the course ID: in Settings, pick the course in “Show the player on your website” and the ID is filled into the sample code. It is also the last part of the course page’s address in the panel.
.env
# environment (or .env loaded by your settings)
XAPLAYER_API_KEY=xap_sk_...

The token function#

xaplayer.py
# xaplayer.py: shared by the Django and Flask examples (pip install requests)
import os
import requests

XAPLAYER = "https://en.xaplayer.ir/api/v1"


def player_url(course_id: str, user_id: str, name: str = "") -> str:
    res = requests.post(
        f"{XAPLAYER}/embed-tokens",
        headers={"Authorization": f"Bearer {os.environ['XAPLAYER_API_KEY']}"},
        json={"courseId": course_id, "viewer": {"id": user_id, "name": name}},
        timeout=10,
    )
    res.raise_for_status()
    return res.json()["url"]

Show the player#

courses/views.py
# courses/views.py
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.shortcuts import render

from xaplayer import player_url


@login_required
def watch(request, course_id):
    if not user_bought(request.user, course_id):  # your own orders check
        raise Http404
    url = player_url(course_id, str(request.user.pk), request.user.get_full_name())
    return render(request, "courses/watch.html", {"player_url": url})


# courses/urls.py
# path("courses/<str:course_id>/watch/", views.watch, name="watch"),

If it doesn’t work#

What you seeCause and fix
The player area is empty or the browser says it refused to connectYour site isn’t in the allowed websites, or www differs. Add the page’s exact address.
401 unauthorizedThe API key is wrong, or you created a new key and the old one stopped working. Copy the key again.
404 not_foundThe course or video ID is wrong or belongs to another account.
400 bad_requestThe body is incomplete: send exactly one of courseId or videoId, and a non-empty viewer.id.
After a few hours the player says the page timed outThe token expired. Get a fresh token every time the page opens, and never cache the player address.

Try XAPlayer free for 14 days, with 10 licenses on us.

Try it free with your own course