Developers

    Create a UPCS Embed Session in Python

    Python example using the requests library to create a UPCS embed session on your server and return only the session token to the browser.

    Updated 14 October 2026 · 2 min read

    In Python the embed session call is a single requests.post. The function below raises an exception carrying the UPCS error code so your web framework can respond sensibly.

    The function

    import os
    import requests
    
    UPCS_BASE = "https://api.upcs.io/api"
    
    
    class UpcsError(Exception):
        def __init__(self, message, status=None, code=None):
            super().__init__(message)
            self.status = status
            self.code = code
    
    
    def create_embed_session(origin, ttl=None):
        payload = {"origin": origin}
        if ttl:
            payload["ttl"] = ttl  # 60-3600 seconds
    
        resp = requests.post(
            f"{UPCS_BASE}/v1/embed/sessions",
            json=payload,
            headers={
                "x-api-key": os.environ["UPCS_API_KEY"],
                "Accept": "application/json",
            },
            timeout=10,
        )
    
        try:
            data = resp.json()
        except ValueError:
            data = {}
    
        if not resp.ok or data.get("success") is False:
            raise UpcsError(
                data.get("message", "UPCS request failed"),
                status=resp.status_code,
                code=data.get("code"),
            )
        return data  # session_token, expires_at, embed_url
    

    Using it

    session = create_embed_session("https://shop.example.com")
    token = session["session_token"]
    

    Send only token (and optionally expires_at) to your page. A Django view that wraps this is shown in the Django example.

    Practical tips

    • Always set timeout; the default for requests is to wait indefinitely.
    • Read the key from the environment or a secrets manager; see securing your UPCS API key.
    • Catch UpcsError and branch on status and code, for example origin_not_allowed or partner_required. The error codes reference explains each.
    • Use a fixed origin from configuration instead of a value supplied by the client.

    For the browser side, continue with UPCS.mount options explained.

    Frequently asked questions

    Is there an official Python package?

    No. UPCS has no official SDKs. The requests library with the x-api-key header is sufficient.

    How should I treat a 429 response?

    A 429 with the code rate_limited means a key's hourly request limit was reached. Wait before retrying and reduce how often you call the API.