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:
1 2 3 4 5 6 7 8 9 10 11 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
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:
1 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
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:
1 2 3 4 5 6 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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.