English

How to use the Livecoding.tv API using Python

Livcecoding.tv API enables you to connect your application to Livecoding and its different resources.

In this article, we will use the Django framework and Requests library. The same method can be interpolated to other frameworks and library with ease.

Prepare

To prepare to use API, register an app on https://www.livecoding.tv/developer/applications/

Authorization

The first thing we have to do before using API methods is to authorize.

Authorization in livecoding.tv API works through standard oAuth protocol, so first we need to implement methods to get an access token with API credentials and later refresh them.

Assume that we have model object with credentials data:

from django.db import models


class Credentials(models.Model):

    key = models.CharField(max_length=150)
    secret = models.CharField(max_length=150)
    redirect_url = models.URLField()
    state = models.CharField(max_length=150)
    access_token = models.CharField(max_length=150, blank=True)
    refresh_token = models.CharField(max_length=150, blank=True)

All methods implemented in the Client class:

import logging
import requests
from django.utils.dateparse import parse_datetime
from .models import Credentials


logger = logging.getLogger(__name__)


API_ROOT = 'https://www.livecoding.tv/api/'
TOKEN_ENDPOINT = 'https://www.livecoding.tv/o/token/'


class Client(object):

    def __init__(self, credentials):
        self._credentials = credentials
        self._access_token = credentials.access_token
        self._refresh_token = credentials.refresh_token

    def auth(self, code):
        try:
            url = TOKEN_ENDPOINT
            data = dict(code=code,
                        grant_type='authorization_code',
                        redirect_uri=self._credentials.redirect_url,
                        client_id=self._credentials.key,
                        client_secret=self._credentials.secret)
            auth = (self._credentials.key, self._credentials.secret)
            response = requests.post(url, data=data, auth=auth)
        except Exception as e:
            logger.error(e)
            raise Exception("Failed to make POST request to authorize")

        try:
            auth_data = response.json()
        except Exception as e:
            logger.error(e)
            raise Exception('Wrong response auth data')

        self._access_token = auth_data.get('access_token', '')
        self._refresh_token = auth_data.get('refresh_token', '')
        self._credentials.access_token = self._access_token
        self._credentials.refresh_token = self._refresh_token
        self._credentials.save()

        if not self._access_token:
            raise Exception('Not authorized!!!')

In auth() method, we make a post request to Livecoding.tv auth endpoint with an authorization code and then retrieve the access token and refresh token and save them for later use with API requests.

In order to authorise code from authorization server, we have to get request to authorization server:

https://www.livecoding.tv/o/authorize?client_id=vCk6rNsC&response_type=code&state=random_state_string&redirect_url=redirect_url\

After successful authorization Livecoding.tv redirects to our redirect URL, where we can handle authorization code, and continue the auth() procedure.

For convenient use lets create views for it:

import logging
import requests
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.urlresolvers import reverse
from .models import Credentials
from .api import Client

logger = logging.getLogger(__name__)


AUTH_ENDPOINT = 'https://www.livecoding.tv/o/authorize/'


@login_required
def auth_view(request):

    credentials, created = Credentials.objects.get_or_create()
    if not credentials.key or not credentials.secret:
        raise Exception('Credentials are empty')

    url = '{}?scope=read&state={}&redirect_uri={}&response_type=code&client_id={}'.format(
        AUTH_ENDPOINT,
        credentials.state,
        credentials.redirect_url,
        credentials.key
    )

    return redirect(url)

@login_required
def redirect_view(request):

    credentials_admin_url = reverse('admin:livecoding_api_credentials_changelist')

    credentials, created = Credentials.objects.get_or_create()
    if not credentials.key or not credentials.secret:
        messages.error(request, 'Credentials are empty')
        return redirect(credentials_admin_url)

    code = request.GET.get('code')
    if not code:
        messages.error(request, "Code param is empty/not found")
        return redirect(credentials_admin_url)

    livecoding = Client(credentials)

    try:
        livecoding.auth(code)
    except Exception as e:
        messages.error(request, e.message)
        return redirect(credentials_admin_url)

    messages.info(request, 'Authorized!!!')
    return redirect(credentials_admin_url)

 

Access token has expiration period, so we need periodically refresh it:

def refresh_auth(self):
    try:
        url = TOKEN_ENDPOINT
        data = dict(refresh_token=self._refresh_token,
                    grant_type='refresh_token',
                    redirect_uri=self._credentials.redirect_url,
                    client_id=self._credentials.key,
                    client_secret=self._credentials.secret)
        auth = (self._credentials.key, self._credentials.secret)
        response = requests.post(url, data=data, auth=auth)
    except Exception as e:
        logger.error(e)
        raise Exception("Failed to make POST request to refresh auth")

    try:
        auth_data = response.json()
    except Exception as e:
        logger.error(e)
        raise Exception('Wrong response auth data')

    access_token = auth_data.get('access_token', '')
    refresh_token = auth_data.get('refresh_token', '')

    if not access_token:
        raise Exception('Refresh failed')

    self._access_token = access_token
    self._refresh_token = refresh_token
    self._credentials.access_token = self._access_token
    self._credentials.refresh_token = self._refresh_token
    self._credentials.save()

API calls

In order to call API methods we need to supply access token with special HTTP header:

“Authorization: Bearer mytoken”

Let implement method to form it:

def get_auth_headers(self):

    if not self._access_token:
        raise Exception('No access token')

    return {"Authorization": "Bearer " + self._access_token}

And now all necessary is ready to retrieve data through API.

For example, we want to get scheduled broadcasts. So we have to make proxy method for API method “scheduledbroadcast”, and for convenient use, we will make the ability to pass any params to it.To avoid access token expiration, we will refresh it on every call.

def scheduledbroadcast(self, **kwargs):
    try:
        self.refresh_auth()
    except Exception as e:
        logger.error(e)
    url = '{}scheduledbroadcast'.format(API_ROOT)
    try:
        response = requests.get(url, params=kwargs, headers=self.get_auth_headers())
        data = response.json()
    except Exception as e:
        logger.error(e)
        return None
    results = []
    for result in data['results']:
        result['start_time'] = parse_datetime(result['start_time'])
        result['start_time_original_timezone'] = parse_datetime(result['start_time_original_timezone'])
        result['username'] = result['livestream'].strip('/').split('/')[-1]
        results.append(result)
    data['results'] = results
    return data

And then use it like:

import logging
from django.http import JsonResponse
from livecoding_api.api import Client, get_default_credentials


def schedule_json_view(request):
    livecoding = Client(get_default_credentials())
    try:
        limit = int(request.GET.get('limit'))
    except:
        limit = 10
    try:
        schedule = livecoding.scheduledbroadcast()
    except Exception as e:
        logger.error(e)
        schedule = None
    if schedule:
        return JsonResponse(schedule)
    return JsonResponse(dict())

In that way, you can use any method supported by API
https://www.livecoding.tv/developer/documentation/

Have any questions? Don’t forget to comment below and let us know.

Dr. Michael J. Garbade

I, Dr. Michael J. Garbade is the co-founder of the Education Ecosystem (aka LiveEdu), ex-Amazon, GE, Rebate Networks, Y-combinator. Python, Django, and DevOps Engineer. Serial Entrepreneur. Experienced in raising venture funding. I speak English and German as mother tongues. I have a Masters in Business Administration and Physics, and a Ph.D. in Venture Capital Financing. Currently, I am the Project Lead on the community project -Nationalcoronalvirus Hotline I write subject matter expert technical and business articles in leading blogs like Opensource.com, Dzone.com, Cybrary, Businessinsider, Entrepreneur.com, TechinAsia, Coindesk, and Cointelegraph. I am a frequent speaker and panelist at tech and blockchain conferences around the globe. I serve as a start-up mentor at Axel Springer Accelerator, NY Edtech Accelerator, Seedstars, and Learnlaunch Accelerator. I love hackathons and often serve as a technical judge on hackathon panels.

View Comments

  • Hi, I'm a frequent broadcaster was looking how for similar articles all around the web. Thanks for the info guys I was seeking to integrate my app to the website .

Recent Posts

Win Big with Our Amazon Fire Max 11 & AirPods Pro Giveaway!

We’re thrilled to announce an exciting opportunity for you to win not one but two…

1 month ago

Unleashing Potential: How Education Ecosystem Transforms Learning into Real-World Success

Acquiring practical skills is crucial for career advancement and personal growth. Education Ecosystem stands out…

3 months ago

The Role of Artificial Intelligence in Modern Software Development

Artificial Intelligence (AI) has been making significant strides in various industries, and the software development…

6 months ago

Highest Stable Coin Yields – (W16 – 2024)

Another week to bring you the top yield platforms for three of the most prominent…

7 months ago

LEDU Token OTC Trading

If you hold a large volume of LEDU tokens above 1 million units and wish…

8 months ago

Highest Stable Coin Yields – (W12 – 2024)

It’s another week and like always we have to explore the top yield platforms for…

8 months ago