In this section we explain how to get access authentication tokens and implement the API in your apps.
Authentication tokens is obtained from the JunctionTV OAuth API. Along with access tokens, it is required to obtain client credentials (a client id and a client password) they are specific to the API and operations that are required to be accessed or performed.
Once credentials are obtained, access authentication token by making a POST request to:
optional
required
NOTE: {client_id}:{client_secret} string must be Base64-encoded.
1 2 3 4 5 6 |
{ version: "1.1", client_id: "XXXX", access_token: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", expires_in: 3600 } |
The expired_in value is the number of seconds that the access token is valid for.
1 2 3 4 5 |
{ result: "error", message: "UNAUTHORIZED", reason: "No Authorization Token" } |
HTTP Status 404
Implementation Strategies
App will only be making periodic calls to the JTV APIs.
If the API call (i.e. HTTP response) is successful, with response Status code is 200, then continue with further process.
Else, if the response Status code is 401, that means unauthorized call. Follow the flow loop to get Authentication Token.
At last if the response Status code is not 401, that means invalid API call, continue the loop to make API calls.
Here are some code samples to help you get started.
Python script attempts to make an Analytics API call, but if the call fails on an UNAUTHORIZED error, it fetches a new access token and retries the call.
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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
''' Proxy for JunctionTV RESTful APIs gets an access token, makes the request, and returns the response Method: POST URL: https://cloud.junctiontv.net/ums/2.0/oauth/ Include header: "Content-Type", "application/x-www-form-urlencoded" ''' import httplib, urllib, base64, json, sys # get the oauth 2.0 token def getAuthToken(client_id, client_secret): conn = httplib.HTTPSConnection("cloud.junctiontv.net") url = "/ums/2.0/oauth/" authString = base64.encodestring('%s:%s' % (client_id, client_secret)).replace('\n', '') headersMap = { "Content-Type": "application/x-www-form-urlencoded", "Authorization": "Basic " + authString } conn.request("POST", url, headers=headersMap) response = conn.getresponse() if response.status == 200: data = response.read() result = json.loads(data) return result["access_token"] else: print '[API_CALL_ERROR]' + "{error: " + str(response.status) + ",reason: "+ response.reason+" }" # call jtv API def getFeeds(token): # Use HTTPSConnection when the is called through https:// conn = httplib.HTTPConnection("www.samplejtvapi.com") url = "/xyz/abc/def/" headersMap = { "Authorization": "Bearer " + token } #The method will vary according to specific API. conn.request("GET", url, headers=headersMap) response = conn.getresponse() if response.status == 200: data = response.read() result = json.loads( data ) return result else: print '[API_CALL_ERROR]' + "{error: " + str(response.status) + ",reason: "+ response.reason+" }" def main(): client_id = "XXXX" client_secret = "XXXXXXXXX....XXXXXX" token=getAuthToken(client_id, client_secret) print "Authentication Token: ",token try: results = getFeeds(token) except: # handle an auth error by re-fetching a auth token again token = getAuthToken(client_id, client_secret) results = getFeeds(token) # print the results print results if __name__ == "__main__": main() |
This is a simple proxy that takes client credentials and an API call, gets an access token, makes the API request, and returns the results to the client.
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 |
/** * Proxy for JunctionTV RESTful APIs * gets an access token, makes the request, and returns the response * * Method: POST * URL: https://cloud.junctiontv.net/ums/2.0/oauth/ * Include header: "Content-Type", "application/x-www-form-urlencoded" * */ // CORS enablement header("Access-Control-Allow-Origin: *"); // set up request for access token $data = array(); $client_id = 'CLIENT_ID'; $client_secret = 'CLIENT_PASSWORD'; $auth_string = "{$client_id}:{$client_secret}"; $request = "https://cloud.junctiontv.net/ums/2.0/oauth/"; $ch = curl_init($request); curl_setopt_array($ch, array( CURLOPT_POST => TRUE, CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_SSL_VERIFYPEER => FALSE, CURLOPT_USERPWD => $auth_string, CURLOPT_HTTPHEADER => array( 'Content-type: application/x-www-form-urlencoded', ), CURLOPT_POSTFIELDS => $data )); $response = curl_exec($ch); curl_close($ch); // Check for errors if ($response === FALSE) { die(curl_error($ch)); } // Decode the response $responseData = json_decode($response, TRUE); $access_token = $responseData["access_token"]; // get the URL and authorization info from the form data $request = "http://www.samplejtvapi.com/xyz/abc/def/" //send the http request $ch = curl_init($request); curl_setopt_array($ch, array( CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_SSL_VERIFYPEER => FALSE, CURLOPT_HTTPHEADER => array( 'Content-type: application/json', "Authorization: Bearer {$access_token}", ) )); $response = curl_exec($ch); curl_close($ch); echo $response; |
This is a simple proxy that takes client credentials and an API call, gets an access token, makes the API request, and returns the results to the client.
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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
/** * Proxy for JunctionTV RESTful APIs * gets an access token, makes the request, and returns the response * * Method: POST * URL: https://cloud.junctiontv.net/ums/2.0/oauth/ * Include header: "Content-Type", "application/x-www-form-urlencoded" * */ // get the oauth 2.0 token private void getAuthToken(){ String clientId = "client_id"; String clientSecret = "client_secret "; String apiUrl = "https://cloud.junctiontv.net/ums/2.0/oauth/"; try{ URL url = new URL(apiUrl); HttpsURLConnection connection = (HttpsURLConnection)url.openConnection(); String data = clientId+":"+clientSecret; String encoding = Base64.encodeBase64String(data.getBytes()); encoding = encoding.replace("\n", ""); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Authorization", "Basic " + encoding); InputStream content = (InputStream)connection.getInputStream(); BufferedReader in = new BufferedReader (new InputStreamReader (content)); String line; while ((line = in.readLine()) != null) { if(null!=line){ JSONObject jobject = new JSONObject(line); if (jobject.has("access_token")) { String token = jobject.getString("access_token"); }else{ } } } connection.disconnect(); } catch(Throwable t){ } } // call jtv API private void getFeeds(String token){ String apiUrl = "http://www.samplejtvapi.com/xyz/abc/def/"; try { URL url = new URL(apiUrl); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setRequestProperty("Authorization", "Bearer " + token); InputStream content = (InputStream)connection.getInputStream(); BufferedReader in = new BufferedReader (new InputStreamReader (content)); String line; while ((line = in.readLine()) != null) { System.out.println("feed data:: "+line); } connection.disconnect(); } catch (Throwable e) { e.printStackTrace(); } } |
This is a simple proxy that takes client credentials and an API call, gets an access token, makes the API request, and returns the results to the client.
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 |
'Proxy for JunctionTV RESTful APIs' 'gets an access token, makes the request, and returns the response' 'Method: POST' 'URL: https://cloud.junctiontv.net/ums/2.0/oauth/ ' 'Include header: "Content-Type", "application/x-www-form-urlencoded" ' Function ApiAuthentication() as object Auth = { ByteArray : CreateObject("roByteArray") AuthTokenURL : "https://cloud.junctiontv.net/ums/2.0/oauth/" GetToken : GetTokenFromServer ClientID : "Client_ID" Client_secret : "Client_Secret" Auth_String : "" } return Auth End Function Function GetTokenFromServer(param as object) as String timeout% = 1000 * 3600 str = param.ClientID+":"+param.Client_secret param.ByteArray.FromAsciiString(str) param.Auth_String = param.ByteArray.ToBase64String() Http = CreateObject("roUrlTransfer") Http.SetPort(CreateObject("roMessagePort")) Http.SetUrl(param.AuthTokenURL) Http.AddHeader("Content-Type", "application/x-www-form-urlencoded") Http.AddHeader("Authorization", "Basic "+param.Auth_String.Trim()) Http.EnableEncodings(true) Http.SetCertificatesFile("common:/certs/ca-bundle.crt") Http.InitClientCertificates() Http.EnableFreshConnection(true) 'Don't reuse existing connections Http.AsyncPostFromString("") event = wait(timeout%, Http.GetPort()) if type(event) = "roUrlEvent" retstr = event.GetString() json = ParseJSON(retstr) return json.access_token end if End Function |
The ApiAuthentication() can be called from your main script like this :-
1 2 3 4 5 6 7 |
'Use ApiAuthentication() to get the token' Sub Main(args as Dynamic) print "Main called " respauth = ApiAuthentication() APIAuthToken = respauth.gettoken(respauth) print "APIAuthToken : "+APIAuthToken End Sub |
For much better understating and curated scripts follow us at Github