### Quick Start with API v2 Source: https://docs.jwplayer.com/platform/reference/migrate-to-management-api-v2 Provides initial steps for getting started with the Platform Management API v2, including authentication and client library usage. ```APIDOC ## Quick Start 1. Familiarize yourself with [API v2 authentication](ref:api-v2-authentication). 2. Choose and use one of our [Platform Management API v2 client libraries](ref:developer-tools#platform-management-api-v2) to integrate functionality into your workflow. > **Note**: If you use an officially supported client library, update to the latest version. ``` -------------------------------- ### dash.js Basic Setup Example Source: https://docs.jwplayer.com/platform/reference/studio-drm-standalone-web-players This JavaScript snippet shows the basic setup for initializing a dash.js media player. It declares variables for the stream URL and VUDRM token, and then creates a new MediaPlayer instance. This setup is the foundation for integrating Studio DRM Standalone with dash.js. ```javascript var streamUrl = ""; var vudrmToken = ""; var player = dashjs.MediaPlayer().create(); ``` -------------------------------- ### Install JW Player Go Client Library Source: https://docs.jwplayer.com/platform/reference/developer-tools Installs the official JW Player Go client library using the go get command. This library facilitates integration with JW Player's platform services. ```text go get -u github.com/jwplayer/jwplatform-go ``` -------------------------------- ### Base API Call Examples Source: https://docs.jwplayer.com/platform/reference/get-started-with-the-management-api Demonstrates the base API call structure for POST and GET requests to the JW Player Management API v2. ```APIDOC ## Base API Calls ### Description These examples show the fundamental structure of API calls, including the HTTP verb, base URL, and resource route. ### POST Request Example ``` POST https://api.jwplayer.com/v2/{resource} ``` ### GET Request Example ``` GET https://api.jwplayer.com/v2/sites/{site_id}/{resource} ``` ### Route Types | Route Type | Description | |--------------|------------------------------------------------| | **Collection** | Retrieves or appends to a list of objects | | | - `GET` | | | - `POST` | | **Object** | Retrieves, edits, removes, or creates an object | | | - `GET` | | | - `PATCH` | | | - `DELETE` | | **Action** | | | | - `PUT` | ``` -------------------------------- ### Get Live Stream Manifest (Node.js) Source: https://docs.jwplayer.com/platform/reference/broadcast-live-3 Example using Node.js to request a live stream manifest. This snippet utilizes the 'axios' library for making HTTP GET requests. Ensure you have 'axios' installed (`npm install axios`). ```javascript const axios = require('axios'); const getLiveManifest = async (mediaId, manifestExtension = 'm3u8', timeShift, type) => { let url = `https://cdn.jwplayer.com/live/broadcast/${mediaId}.${manifestExtension}`; const params = []; if (timeShift !== undefined) { params.push(`time_shift=${timeShift}`); } if (type !== undefined) { params.push(`type=${type}`); } if (params.length > 0) { url += `?${params.join('&')}`; } try { const response = await axios.get(url); return response.data; } catch (error) { console.error('Error fetching live manifest:', error); throw error; } }; // Example usage: // getLiveManifest('your_media_id', 'm3u8', 3600, 'chromecast') // .then(manifest => console.log(manifest)) // .catch(err => console.error('Failed to get manifest')); ``` -------------------------------- ### List Players using Node.js Source: https://docs.jwplayer.com/platform/reference/players-1 This Node.js example shows how to fetch a list of players from the JW Player API. It uses the 'axios' library to send a GET request with appropriate headers and query parameters for pagination and sorting. Make sure to install 'axios' (`npm install axios`). ```javascript const axios = require('axios'); const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key const siteId = 'YOUR_SITE_ID'; // Replace with your actual site ID const headers = { 'Authorization': `ApiKey ${apiKey}`, 'Accept': 'application/json' }; const params = { page: 1, page_length: 10, sort: 'created:dsc' }; const url = `https://api.jwplayer.com/v2/sites/${siteId}/players/`; axios.get(url, { headers: headers, params: params }) .then(response => { console.log(response.data); }) .catch(error => { console.error(`Error: ${error.response.status} - ${error.response.data}`); }); ``` -------------------------------- ### Metadata and Setup Configuration Source: https://docs.jwplayer.com/platform/reference/migrate-to-management-api-v2 Explains the structure of metadata and setup configuration parameters for player settings in v1 and v2. ```APIDOC ## Metadata and Setup Configuration ### Description This section outlines the differences in handling player metadata and setup configuration between v1 and v2 of the API. ### Metadata (v1) - **Format**: Direct key-value pairs within the `metadata` object. #### Example (v1) ```json { "metadata": { "name": "Example player", "release_channel": "latest", "aspectratio": "16:9", "responsive": true, "autostart": false, "displaydescription": true, "displaytitle": true, "playback_rate_controls": true, "preload": "metadata", "repeat": false, "stretching": "uniform" } } ``` ### Metadata and Setup Configuration (v2) - **Format**: Most player settings are moved into a `setup_config` object within `metadata`. `name` and `release_channel` remain in `metadata`. - **Note**: This change allows for more player options but removes API validation for those options. #### Example (v2) ```json { "metadata": { "name": "Example player", "release_channel": "latest", "setup_config": { "aspectratio": "16:9", "responsive": true, "autostart": false, "displaydescription": true, "displaytitle": true, "playbackRateControls": true, "preload": "metadata", "repeat": false, "stretching": "uniform" } } } ``` ``` -------------------------------- ### List Players using Python Source: https://docs.jwplayer.com/platform/reference/players-1 Example of how to list players via the JW Player API using Python. It utilizes the 'requests' library to make a GET request to the players endpoint, including query parameters for pagination and sorting. Ensure you have the 'requests' library installed (`pip install requests`). ```python import requests api_key = "YOUR_API_KEY" # Replace with your actual API key site_id = "YOUR_SITE_ID" # Replace with your actual site ID headers = { "Authorization": f"ApiKey {api_key}", "Accept": "application/json" } params = { "page": 1, "page_length": 10, "sort": "created:dsc" } url = f"https://api.jwplayer.com/v2/sites/{site_id}/players/" response = requests.get(url, headers=headers, params=params) if response.status_code == 200: players = response.json() print(players) else: print(f"Error: {response.status_code} - {response.text}") ``` -------------------------------- ### DRM Session GET Request Example Source: https://docs.jwplayer.com/platform/reference/studio-drm-token-api Illustrates an example HTTP GET request to a DRM license server, including a session ID as a query parameter. ```http GET https://some-url.com/valid?sessionId=abc1234 ``` -------------------------------- ### DRM Session GET Request Example Source: https://docs.jwplayer.com/platform/reference/studio-drm-token-api-v2 Illustrates a GET request to a DRM license server, including the session ID as a query parameter. This is used when 'policy.method' is set to 'GET' and JW Player requests a license. ```http GET https://some-url.com/valid?sessionId=abc123 ``` -------------------------------- ### List Media - Go SDK Example Source: https://docs.jwplayer.com/platform/reference/get_v2-sites-site-id-media This Go example shows how to list media using the JW Player Management API. It uses the `jwplatform-go` SDK and requires an API key. The function takes the site ID and a map for query parameters. ```go package main import ( "fmt" "github.com/jwplatform/jwplatform-go/jwplatform" ) func listMedia(siteID string, queryParams map[string]string) (string, error) { /** * Lists media resources for a given site ID. * * @param siteID string The unique ID of the site. * @param queryParams map[string]string Map of query parameters for filtering and sorting. * * @return string The JSON string of the media resources, or an error. */ client := jwplatform.NewClient("YOUR_API_KEY") // Replace with your actual API key resp, err := client.Media.List(siteID, queryParams) if err != nil { return "", fmt.Errorf("error listing media: %w", err) } return resp.String(), nil } // Example usage: // func main() { // ssiteID := "YOUR_SITE_ID" // Replace with your site ID // queryParams := map[string]string{ // "q": "title:my_video", // "sort": "created:asc", // } // mediaList, err := listMedia(siteID, queryParams) // if err != nil { // fmt.Println(err) // return // } // fmt.Println(mediaList) // } ``` -------------------------------- ### List Media - Ruby SDK Example Source: https://docs.jwplayer.com/platform/reference/get_v2-sites-site-id-media This Ruby example demonstrates fetching a list of media resources via the JW Player Management API. It uses the `jwplatform-ruby` gem and requires authentication with an API key. The function takes a site ID and an optional hash for query parameters. ```ruby require 'jwplatform' def list_media(site_id, query_params = {}) """ Lists media resources for a given site ID. Args: site_id (String): The unique ID of the site. query_params (Hash): Hash of query parameters for filtering and sorting. Returns: Hash: A hash containing the media resources. """ client = Jwplatform::Client.new(api_key: 'YOUR_API_KEY') # Replace with your actual API key response = client.get("/v2/sites/#{site_id}/media/", query: query_params) response.body end # Example usage: # site_id = 'YOUR_SITE_ID' # Replace with your site ID # media_list = list_media(site_id, { 'q' => 'title:my_video', 'sort' => 'created:asc' }) # puts media_list ``` -------------------------------- ### Get Live Channel Status (Node.js) Source: https://docs.jwplayer.com/platform/reference/live-channel This example shows how to fetch the live channel status using Node.js with the 'axios' library. It sends a GET request to the JW Player API endpoint and handles the JSON response. ```javascript const axios = require('axios'); const channelId = 'YOUR_CHANNEL_ID'; // Replace with your actual channel ID const apiUrl = `https://cdn.jwplayer.com/live/channels/${channelId}.json`; axios.get(apiUrl, { headers: { 'accept': 'application/json; charset=utf-8' } }) .then(response => { console.log('Channel Status:', response.data); }) .catch(error => { console.error('Error fetching channel status:', error); }); ``` -------------------------------- ### Base API Call Examples Source: https://docs.jwplayer.com/platform/reference/building-a-request Examples of the base API calls for the JW Player Management API v2, showing different resource access methods. ```APIDOC ## Base API Call Examples ### Description Provides examples of the base structure for API calls, including the HTTP method, base URL, and resource path. ### Method POST or GET ### Endpoint `https://api.jwplayer.com/v2/{resource}` or `https://api.jwplayer.com/v2/sites/{site_id}/{resource}` ### Parameters None directly at this level, but `{resource}` and `{site_id}` are placeholders. ### Request Example ```http POST https://api.jwplayer.com/v2/{resource} ``` ### Response Example (Varies based on the specific resource) ``` -------------------------------- ### Get Live Channel Status (Python) Source: https://docs.jwplayer.com/platform/reference/live-channel This Python example utilizes the 'requests' library to make a GET request to the JW Player API for live channel status. It handles potential request errors and prints the status information. ```python import requests channel_id = 'YOUR_CHANNEL_ID' # Replace with your actual channel ID api_url = f"https://cdn.jwplayer.com/live/channels/{channel_id}.json" headers = { 'accept': 'application/json; charset=utf-8' } try: response = requests.get(api_url, headers=headers) response.raise_for_status() # Raise an exception for bad status codes channel_status = response.json() print(f"Channel Status: {channel_status}") except requests.exceptions.RequestException as e: print(f"Error fetching channel status: {e}") ``` -------------------------------- ### Get Ad Schedule (Python) Source: https://docs.jwplayer.com/platform/reference/advertising This Python example shows how to retrieve an advertising schedule using the 'requests' library. It makes a GET request to the API and handles the JSON response. ```python import requests def get_ad_schedule(ad_schedule_id, ad_schedule_extension): url = f"https://cdn.jwplayer.com/v2/advertising/schedules/{ad_schedule_id}.{ad_schedule_extension}" headers = { 'accept': 'application/json' } try: response = requests.get(url, headers=headers) response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) return response.json() except requests.exceptions.RequestException as e: print(f"Error fetching ad schedule: {e}") return None # Example usage: # schedule = get_ad_schedule('your_ad_schedule_id', 'json') # if schedule: # print(schedule) ``` -------------------------------- ### List Media - Java SDK Example Source: https://docs.jwplayer.com/platform/reference/get_v2-sites-site-id-media This Java example demonstrates how to list media using the JW Player Management API. It utilizes the `jwplatform-java` SDK and requires an API key for authentication. The function takes the site ID and a map for query parameters. ```java import com.jwplatform.sdk.JwPlatformClient; import com.jwplatform.sdk.exception.JwPlatformException; import java.util.Map; public class MediaApi { public static String listMedia(String siteId, Map queryParams) throws JwPlatformException { /** * Lists media resources for a given site ID. * * @param siteId The unique ID of the site. * @param queryParams Map of query parameters for filtering and sorting. * * @return String The JSON string of the media resources. * @throws JwPlatformException if an API error occurs. */ JwPlatformClient client = new JwPlatformClient("YOUR_API_KEY"); // Replace with your actual API key return client.getMediaApi().list(siteId, queryParams); } // Example usage: // public static void main(String[] args) { // String siteId = "YOUR_SITE_ID"; // Replace with your site ID // Map queryParams = Map.of( // "q", "title:my_video", // "sort", "created:asc" // ); // try { // String mediaList = listMedia(siteId, queryParams); // System.out.println(mediaList); // } catch (JwPlatformException e) { // System.err.println("Error listing media: " + e.getMessage()); // } // } } ``` -------------------------------- ### API Response Examples: Videos List Source: https://docs.jwplayer.com/platform/reference/manage-your-library-with-the-management-api Illustrates the XML and PHP formats for the /videos/list API call, highlighting attribute usage in XML. ```APIDOC ## GET /videos/list ### Description Retrieves a list of videos. The output format differs between XML and PHP, with XML utilizing attributes for certain data points. ### Method GET ### Endpoint /videos/list ### Parameters None specified for this example. ### Request Example None provided. ### Response #### Success Response (200) - **XML Format**: Uses attributes for 'total' and 'key'. - **PHP Format**: Returns an array, with 'total' derivable from count. #### Response Example (XML) ```xml ok ... ``` #### Response Example (PHP) ```php [ "status" => "ok", "videos" => [ 0 => [ "status" => "ready", "description" => "New video.", "tags" => "new, video", "title" => "New test video", "duration" => "12.0", "link" => "http://www.jwplatform.com", "author" => "JW Platform", "key" => "yYul4DRz", "date" => "1225962900" ], ... ] ] ``` ``` -------------------------------- ### Get an Article Matching Playlist - PHP Example Source: https://docs.jwplayer.com/platform/reference/get_v2-sites-site-id-playlists-playlist-id-article-matching-playlist This PHP code snippet demonstrates how to get an article matching playlist using the JW Platform Management API v2. It employs cURL to make the GET request, requiring `site_id` and `playlist_id`. The API response is decoded from JSON. ```php ``` -------------------------------- ### Example Authenticated API Call Source: https://docs.jwplayer.com/platform/reference/manage-your-library-with-the-management-api This snippet shows a complete, authenticated API call to the JW Platform Management API. It includes all necessary parameters for authentication and authorization, such as api_key, api_nonce, api_timestamp, api_format, and the generated api_signature. ```http http://api.jwplatform.com/v1/videos/list?search=d%C3%A9mo&api_nonce=80684843&api_timestamp=1237387851&api_format=xml&api_signature=600822503e043c017e01ce5c9796f83e7ee169f5&api_key=XOqEAfxj ``` -------------------------------- ### Get Ad Schedule (cURL) Source: https://docs.jwplayer.com/platform/reference/advertising This snippet demonstrates how to retrieve an advertising schedule in JSON format using a cURL request. It includes the necessary GET request, URL, and an example header. ```shell curl --request GET \ --url https://cdn.jwplayer.com/v2/advertising/schedules/ad_schedule_id.json \ --header 'accept: adscheduleid' ``` -------------------------------- ### List App Configurations for a Site (Go) Source: https://docs.jwplayer.com/platform/reference/get_v2-sites-site-id-app-configs This Go code snippet demonstrates how to list all app configurations for a specific JW Player site using the JW Platform Management API. It uses the standard `net/http` package for making HTTP requests and includes parameters for pagination, querying, and sorting. ```go package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "strings" ) const apiUrl = "https://api.jwplayer.com/v2/sites/%s/app_configs/" const apiKey = "YOUR_API_KEY" func listAppConfigs(siteID string, page int, pageLength int, q string, sort string) (map[string]interface{}, error) { urlStr := fmt.Sprintf(apiUrl, siteID) params := url.Values{} params.Add("page", fmt.Sprintf("%d", page)) params.Add("page_length", fmt.Sprintf("%d", pageLength)) if q != "" { params.Add("q", q) } if sort != "" { params.Add("sort", sort) } urlStr += "?" + params.Encode() req, err := http.NewRequest("GET", urlStr, nil) if err != nil { return nil, err } req.Header.Add("Authorization", "Bearer "+apiKey) client := &http.Client{} resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("Error: %d, Body: %s", resp.StatusCode, string(body)) } var result map[string]interface{} if err := json.Unmarshal(body, &result); err != nil { return nil, err } return result, nil } func main() { siteID := "YOUR_SITE_ID" configs, err := listAppConfigs(siteID, 1, 10, "app_name:+my_app", "created:asc") if err != nil { fmt.Println("Error:", err) return } fmt.Println(configs) } ``` -------------------------------- ### GET /v2/sites/{site_id}/media/{media_id}/originals/ Source: https://docs.jwplayer.com/platform/reference/get_v2-sites-site-id-media-media-id-originals Retrieves a list of resources that represent the uploaded files that make up a hosted media. These may be primary (for example a video file or the main audio file) or secondary (for example an additional audio track). ```APIDOC ## GET /v2/sites/{site_id}/media/{media_id}/originals/ ### Description Retrieves a list of resources that represent the uploaded files that make up a hosted media. These may be primary (for example a video file or the main audio file) or secondary (for example an additional audio track). ### Method GET ### Endpoint /v2/sites/{site_id}/media/{media_id}/originals/ ### Parameters #### Path Parameters - **site_id** (string) - Required - Unique alphanumeric ID of the site - **media_id** (string) - Required - Unique alphanumeric ID of the media #### Query Parameters - **page** (integer) - Optional - Sets the page number for pagination. First page is `1`. (Default: 1) - **page_length** (integer) - Optional - Sets the page length (number of items you get in the response) for pagination. If `page_length` is not specified, the default value will be set. (Default: 10) ### Request Example ```json { "example": "Not applicable for GET request" } ``` ### Response #### Success Response (200) - **status** (string) - Original status - **error_message** (string) - Human-readable message explaining an issue uploading or processing an original. This property is only displayed when `"status": "failed"`. - **size** (string) - Size of the original in bytes - **container_format** (string) - File format containing the media compressed by means of standardized audio/video codecs - **md5** (string) - MD5 hash of the asset, stored as 32-character hexadecimal string - **original_type** (string) - Identifies if the uploaded file is a video file (`primary`) or an alternate audio track file (`secondary`) - **metadata** (object) - Metadata associated with the original resource #### Response Example ```json { "example": "{\n \"data\": [\n {\n \"status\": \"ready\",\n \"size\": \"12345678\",\n \"container_format\": \"mp4\",\n \"original_type\": \"primary\",\n \"md5\": \"a1b2c3d4e5f67890a1b2c3d4e5f67890\",\n \"metadata\": {\n \"video_codec\": \"h264\",\n \"audio_codec\": \"aac\",\n \"width\": 1920,\n \"height\": 1080\n }\n }\n ],\n \"pagination\": {\n \"page\": 1,\n \"page_length\": 10,\n \"total_items\": 1,\n \"total_pages\": 1\n }\n}" } ``` ``` -------------------------------- ### JW Player API Query Parameter Examples Source: https://docs.jwplayer.com/platform/reference/get-started-with-the-management-api Provides examples of using the 'q' query parameter for advanced filtering in JW Player API calls. It showcases exact matches, special character handling, non-null value searches, logical operators (AND/OR), range queries, inverse operations, and compound logic. ```HTTP ?q=title: cats ?q=title: "wild cats" ?q=custom_param:"genre:thriller" ?q=title: "\*BEST\*" ?q=title: "\"" ?q=title: "\\" ?q=_exists_:description ?q=title: ( cats OR kittens ) ?q=title: ( cats AND dogs ) ?q=publish_date: [2017-01-01 TO 2017-04-01] ?q=publish_date: [2017-04-01 TO _] ?q=title: NOT dogs ?q=title: NOT "\"" ?q=title: NOT ( cats OR kittens ) ?q=title: NOT ( cats AND dogs ) ?q=publish_date: NOT [2017-01-01 TO 2017-04-01] ?q=( title: NOT dogs AND publish_date: [2017-01-01 TO 2017-04-01] ) OR ( title: ( cats OR kittens ) AND ( publish_date: [2017-04-01 TO *] ) ) ``` -------------------------------- ### Create JW Platform Recommendations Playlist (Go) Source: https://docs.jwplayer.com/platform/reference/post_v2-sites-site-id-playlists-recommendations-playlist This Go code snippet illustrates how to create a recommendations playlist using the JW Platform Management API v2. It covers setting up the request URL, headers including the API key, and marshalling the JSON payload. The code handles the HTTP POST request and checks for a 201 status code. ```go package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" ) func main() { siteID := "YOUR_SITE_ID" apiKey := "YOUR_API_KEY" apiUrl := fmt.Sprintf("https://api.jwplayer.com/v2/sites/%s/playlists/recommendations_playlist/", siteID) payload := map[string]interface{}{ "metadata": map[string]string{ "title": "My Recommendations Playlist", }, } payloadBytes, err := json.Marshal(payload) if err != nil { fmt.Printf("Error marshalling payload: %v\n", err) return } req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(payloadBytes)) if err != nil { fmt.Printf("Error creating request: %v\n", err) return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+apiKey) client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Printf("Error sending request: %v\n", err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Printf("Error reading response body: %v\n", err) return } if res.StatusCode == 201 { fmt.Println("Recommendations playlist created successfully!") fmt.Println(string(body)) } else { fmt.Printf("Error creating playlist: %d\n", res.StatusCode) fmt.Println(string(body)) } } ``` -------------------------------- ### Get Ad Schedule (Node.js) Source: https://docs.jwplayer.com/platform/reference/advertising This Node.js example shows how to make a GET request to fetch an advertising schedule from the JW Player API. It utilizes the 'node-fetch' library for making HTTP requests. ```javascript const fetch = require('node-fetch'); async function getAdSchedule(adScheduleId, adScheduleExtension) { const url = `https://cdn.jwplayer.com/v2/advertising/schedules/${adScheduleId}.${adScheduleExtension}`; try { const response = await fetch(url, { method: 'GET', headers: { 'accept': 'application/json' } }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.error('Error fetching ad schedule:', error); return null; } } // Example usage: // getAdSchedule('your_ad_schedule_id', 'json').then(schedule => { // if (schedule) { // console.log(schedule); // } // }); ``` -------------------------------- ### Update Manual Playlist - Go Example Source: https://docs.jwplayer.com/platform/reference/patch_v2-sites-site-id-playlists-playlist-id-manual-playlist This Go program demonstrates how to update a manual playlist using the JW Platform Management API v2. It uses the standard 'net/http' package and requires your API key and site/playlist IDs. ```go package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" ) func main() { apiKey := "YOUR_API_KEY" siteID := "YOUR_SITE_ID" playlistID := "YOUR_PLAYLIST_ID" url := fmt.Sprintf("https://api.jwplayer.com/v2/sites/%s/playlists/%s/manual_playlist/", siteID, playlistID) payload := map[string]interface{}{ "metadata": map[string]interface{}{ "title": "Updated Go Playlist", "description": "Go updated description", "custom_params": map[string]string{ "go_param": "go_value", }, }, } payloadBytes, err := json.Marshal(payload) if err != nil { fmt.Printf("Error marshaling payload: %v\n", err) return } req, err := http.NewRequest("PATCH", url, bytes.NewBuffer(payloadBytes)) if err != nil { fmt.Printf("Error creating request: %v\n", err) return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "apikey "+apiKey) client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Error sending request: %v\n", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Printf("Error reading response body: %v\n", err) return } if resp.StatusCode == http.StatusOK { fmt.Println("Playlist updated successfully:") fmt.Println(string(body)) } else { fmt.Printf("Error updating playlist: %d\n", resp.StatusCode) fmt.Println(string(body)) } } ``` -------------------------------- ### Retrieve Geo Location Information - cURL Request Example Source: https://docs.jwplayer.com/platform/reference/studio-drm-standalone-geo-location-api Shows how to perform a GET request to the Geo Location API using cURL. This command-line example illustrates setting the HTTP method, the target URL, and the necessary 'X_AUTH_KEY' header for authentication. ```curl curl -X GET https://geo-location.vudrm.tech/ip_lookup/vualto-demo/188.39.163.11 \ -H 'X_AUTH_KEY: {geo_location_api_key}' ``` -------------------------------- ### Player Metadata Configuration (JSON) Source: https://docs.jwplayer.com/platform/reference/migrate-to-management-api-v2 Illustrates player metadata configuration. Key fields have been moved to a 'setup_config' object in v2, enabling support for all player options but removing API validation for those fields. ```json { "name": "Example player", "release_channel": "latest", "aspectratio": "16:9", "responsive": true, "autostart": false, "displaydescription": true, "displaytitle": true, "playback_rate_controls": true, "preload": "metadata", "repeat": false, "stretching": "uniform" } ``` ```json { "metadata": { "name": "Example player", "release_channel": "latest", "setup_config": { "aspectratio": "16:9", "responsive": true, "autostart": false, "displaydescription": true, "displaytitle": true, "playbackRateControls": true, "preload": "metadata", "repeat": false, "stretching": "uniform" } } } ``` -------------------------------- ### Run Studio DRM Wowza API Docker Container Source: https://docs.jwplayer.com/platform/reference/studio-drm-standalone-wowza This command deploys the Studio DRM Wowza API as a Docker container. It configures environment variables for API key, keyfile storage path, and Grand Central/Key Provider URLs, and mounts a local directory for keyfiles. Ensure the Wowza server has the specified keyfiles. ```docker docker run -d --restart always -p 9000:80 \ -e WOWZADRMAPI_APIKEY=93640045-31f1-45c0-aa0d-b5682d7c9ac8 \ -e WOWZADRMAPI_KEYFILESPATH=/mnt/keyfiles \ -e WOWZADRMAPI_GRANDCENTRALURL=https://config.vudrm.tech/v1/clients \ -e WOWZADRMAPI_KEYPROVIDERURL=https://keyprovider.vudrm.tech \ -v [wowza-install-dir]/keys:/mnt/keyfiles \ --name wowza-drm-api vualto/wowza-drm-api:1.0.0 ``` -------------------------------- ### Retrieve Geo Location Information - PHP Request Example Source: https://docs.jwplayer.com/platform/reference/studio-drm-standalone-geo-location-api Illustrates how to make a GET request to the Geo Location API using PHP's HttpRequest class. This example shows setting the URL, method, and the authentication header 'X_AUTH_KEY', and then sending the request. ```php setUrl('https://geo-location.vudrm.tech/ip_lookup/vualto-demo/188.39.163.11'); $request->setMethod(HTTP_METH_GET); $request->setHeaders(array( 'X_AUTH_KEY' => '{geo_location_api_key}' )); try { $response = $request->send(); echo $response->getBody(); } catch (HttpException $ex) { echo $ex; } ?> ``` -------------------------------- ### List App Configurations for a Site (Python) Source: https://docs.jwplayer.com/platform/reference/get_v2-sites-site-id-app-configs This Python code snippet demonstrates how to list all app configurations for a specific JW Player site using the JW Platform Management API. It includes parameters for pagination, querying, and sorting. Ensure you have the `requests` library installed. ```python import requests API_URL = "https://api.jwplayer.com/v2/sites/{site_id}/app_configs/" API_KEY = "YOUR_API_KEY" def list_app_configs(site_id, page=1, page_length=10, q=None, sort=None): headers = { "Authorization": f"Bearer {API_KEY}" } params = { "page": page, "page_length": page_length } if q: params["q"] = q if sort: params["sort"] = sort response = requests.get(API_URL.format(site_id=site_id), headers=headers, params=params) if response.status_code == 200: return response.json() else: print(f"Error: {response.status_code}") return response.json() # Example usage: site_id = "YOUR_SITE_ID" app_configs = list_app_configs(site_id, q="app_name:+my_app", sort="created:asc") print(app_configs) ``` -------------------------------- ### Get a DRM Policy - Java Example Source: https://docs.jwplayer.com/platform/reference/get_v2-sites-site-id-drm-policies-policy-id This Java example shows how to fetch DRM policy details using the JW Platform Management API v2. It requires `site_id` and `policy_id`. The output is a JSON object containing the DRM policy's configuration. ```java import com.jwplayer.api.Client; import com.jwplayer.api.model.drm.DRMPolicy; public class DrmPolicyExample { public static void main(String[] args) { Client client = new Client(System.getenv("JWPLATFORM_API_KEY")); // Get a DRM policy DRMPolicy policy = client.drmPolicies().get("YOUR_SITE_ID", "YOUR_POLICY_ID"); // Print the DRM policy System.out.println(policy.toJson()); } } ``` -------------------------------- ### Get a DRM Policy - PHP Example Source: https://docs.jwplayer.com/platform/reference/get_v2-sites-site-id-drm-policies-policy-id This PHP example demonstrates fetching DRM policy details through the JW Platform Management API v2. It requires `site_id` and `policy_id`. The function returns a JSON object containing the DRM policy's configuration. ```php drmPolicies->get([ 'site_id' => 'YOUR_SITE_ID', 'policy_id' => 'YOUR_POLICY_ID' ]); // Print the DRM policy print(json_encode($policy, JSON_PRETTY_PRINT)); ?> ``` -------------------------------- ### Package Content with JSON Keys Source: https://docs.jwplayer.com/platform/reference/studio-drm-standalone-unified-packager This example demonstrates packaging content with 'mp4split' using encryption keys obtained in JSON format from a CPIX API. It configures settings for PlayReady, Widevine, and HLS (FairPlay), including key IDs, content keys, license server URLs, and DRM-specific data. This method allows for granular control over DRM configurations. ```bash mp4split --license-key=$USP_LICENSE_KEY -o $ismName \ --iss.key=$key_id_hex:$content_key_hex \ --iss.license_server_url="https://playready-license.vudrm.tech/rightsmanager.asmx" \ --widevine.key=$key_id_hex:$content_key_hex \ --widevine.license_server_url="https://widevine-license.vudrm.tech/proxy" \ --widevine.drm_specific_data=$widevine_drm_specific_data \ --hls.client_manifest_version=4 \ --hls.key=:$content_key_hex \ --hls.key_iv=$iv_hex \ --hls.license_server_url=$fairplay_laurl \ --hls.playout=sample_aes_streamingkeydelivery \ video.ismv audio.isma ``` -------------------------------- ### Get a DRM Policy - Node.js Example Source: https://docs.jwplayer.com/platform/reference/get_v2-sites-site-id-drm-policies-policy-id This Node.js example illustrates fetching DRM policy details via the JW Platform Management API v2. It requires `site_id` and `policy_id`. The function returns a JSON object with the DRM policy's configuration. ```javascript const jwplatform = require('jwplatform'); const client = new jwplatform.Client(process.env.JWPLATFORM_API_KEY); // Get a DRM policy client.drmPolicies.get({ siteId: 'YOUR_SITE_ID', policyId: 'YOUR_POLICY_ID' }).then(policy => { console.log(JSON.stringify(policy, null, 2)); }); ``` -------------------------------- ### List Media - Python SDK Example Source: https://docs.jwplayer.com/platform/reference/get_v2-sites-site-id-media This example demonstrates how to list media resources using the JW Player Management API with Python. It requires the `jwplatform` library and an API key for authentication. The function takes a site ID and optional query parameters for filtering and sorting. ```python from jwplatform.client import JwPlatformClient def list_media(site_id, query_params=None): """Lists media resources for a given site ID. Args: site_id (str): The unique ID of the site. query_params (dict, optional): Dictionary of query parameters for filtering and sorting. Defaults to None. Returns: dict: A dictionary containing the media resources. """ client = JwPlatformClient(api_key="YOUR_API_KEY") # Replace with your actual API key response = client.get( f"/v2/sites/{site_id}/media/", query_params=query_params ) return response.json() # Example usage: # site_id = "YOUR_SITE_ID" # Replace with your site ID # media_list = list_media(site_id, query_params={'q': 'title:my_video', 'sort': 'created:asc'}) # print(media_list) ``` -------------------------------- ### Get a DRM Policy - Go Example Source: https://docs.jwplayer.com/platform/reference/get_v2-sites-site-id-drm-policies-policy-id This Go code snippet illustrates how to get DRM policy details using the JW Platform Management API v2. It requires `site_id` and `policy_id`. The output is a JSON object representing the DRM policy configuration. ```go package main import ( "encoding/json" "fmt" "log" "os" "github.com/jwplayer/jwplatform-go-sdk" ) func main() { client := jwplatform.NewClient(os.Getenv("JWPLATFORM_API_KEY")) // Get a DRM policy policy, err := client.DrmPolicies.Get(jwplatform.DrmPoliciesGetParams{ SiteID: "YOUR_SITE_ID", PolicyID: "YOUR_POLICY_ID", }) if err != nil { log.Fatalf("Error getting DRM policy: %v", err) } // Print the DRM policy policyJSON, err := json.MarshalIndent(policy, "", " ") if err != nil { log.Fatalf("Error marshalling DRM policy: %v", err) } fmt.Println(string(policyJSON)) } ``` -------------------------------- ### Initialize Shaka Player and Handle Browser Support Source: https://docs.jwplayer.com/platform/reference/studio-drm-standalone-web-players This JavaScript code snippet initializes the Shaka player, installs necessary polyfills, and checks for browser compatibility. It includes logic to handle FairPlay certificate retrieval for Safari and logs an error if the browser is not supported. Dependencies include the Shaka player library. ```javascript (function() { // Set polyfills required by shaka shaka.polyfill.installAll(); // Check browser is supported and load the player. if (shaka.Player.isBrowserSupported()) { if (isSafari) { // Get the fairplay certificate, once the cert is retrieved then the player will be loaded. getFairplayCertificate(); } else { loadPlayer(); } } else { console.error("This browser does not have the minimum set of APIs needed for shaka!"); } })(); ``` -------------------------------- ### Management API v2 Overview Source: https://docs.jwplayer.com/platform/reference/migrate-to-management-api-v2 An overview of the JW Player Management API v2, detailing improvements in security and adherence to consistent design principles compared to v1. ```APIDOC ## Overview The Platform Management API enables programmatic modification of JW Player products and features. API v2 enhances security through Bearer authentication and adheres to consistent design principles, structuring the API around resources and using standard HTTPS verbs. ``` -------------------------------- ### Get an Article Matching Playlist - Node.js Example Source: https://docs.jwplayer.com/platform/reference/get_v2-sites-site-id-playlists-playlist-id-article-matching-playlist This Node.js code snippet illustrates how to fetch an article matching playlist from the JW Platform Management API v2. It utilizes the `node-fetch` library to make the GET request, requiring `site_id` and `playlist_id`. The response is parsed as JSON. ```javascript import fetch from 'node-fetch'; const siteId = 'YOUR_SITE_ID'; const playlistId = 'YOUR_PLAYLIST_ID'; const apiUrl = `https://api.jwplayer.com/v2/sites/${siteId}/playlists/${playlistId}/article_matching_playlist/`; const headers = { 'accept': 'application/json', 'Authorization': 'Bearer YOUR_API_KEY' }; async function getArticleMatchingPlaylist() { try { const response = await fetch(apiUrl, { method: 'GET', headers: headers }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const playlistData = await response.json(); console.log(playlistData); } catch (error) { console.error('Error fetching article matching playlist:', error); } } getArticleMatchingPlaylist(); ``` -------------------------------- ### Get an Article Matching Playlist - Java Example Source: https://docs.jwplayer.com/platform/reference/get_v2-sites-site-id-playlists-playlist-id-article-matching-playlist This Java code snippet demonstrates retrieving an article matching playlist using the JW Platform Management API v2. It uses Apache HttpClient to send a GET request, requiring `site_id` and `playlist_id`. The JSON response is parsed. ```java import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class GetArticleMatchingPlaylist { public static void main(String[] args) { String siteId = "YOUR_SITE_ID"; String playlistId = "YOUR_PLAYLIST_ID"; String apiUrl = String.format("https://api.jwplayer.com/v2/sites/%s/playlists/%s/article_matching_playlist/", siteId, playlistId); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet request = new HttpGet(apiUrl); request.addHeader("accept", "application/json"); request.addHeader("Authorization", "Bearer YOUR_API_KEY"); try (CloseableHttpResponse response = httpClient.execute(request)) { if (response.getStatusLine().getStatusCode() == 200) { String responseBody = EntityUtils.toString(response.getEntity()); System.out.println(responseBody); // Parse the JSON response using a library like Jackson or Gson } else { System.err.println("HTTP error: " + response.getStatusLine().getStatusCode()); String errorBody = EntityUtils.toString(response.getEntity()); System.err.println("Error body: " + errorBody); } } } catch (IOException e) { e.printStackTrace(); } } } ```