---
title: "Code Samples"
canonical_url: "https://docs.sportradar.com/resources/audiovisual/docs/readme/live-channel-online-live-channel-retail-flex/audiovisual-api/code-samples"
markdown_url: "https://docs.sportradar.com/resources/audiovisual/docs/readme/live-channel-online-live-channel-retail-flex/audiovisual-api/code-samples.md"
last_updated: "2026-10-02T08:58:45Z"
---

# Code Samples

> **Tip**
>
> In the code samples below, remember to replace `YOUR_API_KEY` with your API key and `END_USER_IP_ADDRESS` with the IP address of the end user who will watch the stream.

## Get a list of events with available streams

The code samples below are examples showing how to call the `GET /events` endpoint to get a list of events with available streams by filtering the stream status with "On Air Broadcast" (`stream_status=av:stream_status:2`).

They also show how to find the right stream IDs for the following streams:

- **LCO Live standard streams:** search for streams with product `av:product:2` (LCO), content variant `av:content_variant:1` (Standard feed) and distribution `av:distribution:1` (Live).
- **LCO Live 4Sight stream:** search for streams with product `av:product:2` (LCO), content variant `av:content_variant:2` (4Sight Streaming feed) and distribution `av:distribution:1` (Live).
- **LCP VOD clip:** search for streams with product `av:product:8` (Live Channel Promotion Premium) and distribution `av:distribution:3` (VOD).

These stream IDs can then be used to get a stream URL (see code samples in the next section).

> **Warning**
>
> **Important:** the data provided by this endpoint is cached for 1 minute. Therefore, there is no need to call this endpoint more than once per minute.

> **Tip**
>
> **Tip**: Some other query string parameters can be used in the request. Please see the documentation of this endpoint for more details.

**PHP**

```php
<?php
try {
    $token = "YOUR_API_KEY";
    $baseUrl = "https://av-api.betradar.com";
    $streamStatus = "av:stream_status:2";
    $streamIds = [
        'lco_live_standard' => [],
        'lco_live_4sight' => [],
        'lcp_vod_clip' => []
    ];

    $response = file_get_contents("$baseUrl/events?stream_status=$streamStatus", false, stream_context_create([
        "http" => [
            "header" => "Authorization: Bearer $token"
        ]
    ]));

    if ($response === false) {
        throw new Exception("Failed to fetch data from API.");
    }

    $response = json_decode($response, true);
    if ($response === null) {
        throw new Exception("Failed to decode JSON response.");
    }

    foreach ($response as $event) {
        foreach ($event['contents'] as $content) {
            $contentVariantId = $content['content_variant']['id'] ?? null;
            foreach ($content['streams'] as $stream) {
                $productId = $stream['product']['id'] ?? null;
                $distributionId = $stream['distribution']['id'] ?? null;

                if ($contentVariantId === 'av:content_variant:1' && $productId === 'av:product:2' && $distributionId === 'av:distribution:1') {
                    $streamIds['lco_live_standard'] = $stream['id'];
                }

                if ($contentVariantId === 'av:content_variant:2' && $productId === 'av:product:2' && $distributionId === 'av:distribution:1') {
                    $streamIds['lco_live_4sight'] = $stream['id'];
                }

                if ($productId === 'av:product:8' && $distributionId === 'av:distribution:3') {
                    $streamIds['lcp_vod_clip'] = $stream['id'];
                }
            }
        }
    }

    return $streamIds;
} catch (Exception $e) {
    return ['error' => $e->getMessage()];
}
?>
```

**Python**

```python
import requests

token = "YOUR_API_KEY"
base_url = "https://av-api.betradar.com"
headers = {"Authorization": f"Bearer {token}"}
streamStatus = "av:stream_status:2"
url = f"{base_url}/events?stream_status={streamStatus}"
response = requests.get(url, headers=headers)

# Basic error handling consistent with PHP sample
if response.status_code != 200:
    stream_ids = {"error": "Failed to fetch data from API."}
else:
    try:
        data = response.json()
    except Exception:
        data = None
    if data is None:
        stream_ids = {"error": "Failed to decode JSON response."}
    else:
        stream_ids = {
            'lco_live_standard': [],
            'lco_live_4sight': [],
            'lcp_vod_clip': []
        }
        for event in data:
            for content in event.get('contents', []):
                for stream in content.get('streams', []):
                    content_variant_id = (content.get('content_variant') or {}).get('id')
                    product_id = (stream.get('product') or {}).get('id')
                    distribution_id = (stream.get('distribution') or {}).get('id')
                    if content_variant_id == 'av:content_variant:1' and product_id == 'av:product:2' and distribution_id == 'av:distribution:1':
                        stream_ids['lco_live_standard'] = stream.get('id')
                    if content_variant_id == 'av:content_variant:2' and product_id == 'av:product:2' and distribution_id == 'av:distribution:1':
                        stream_ids['lco_live_4sight'] = stream.get('id')
                    if product_id == 'av:product:8' and distribution_id == 'av:distribution:3':
                        stream_ids['lcp_vod_clip'] = stream.get('id')

        return stream_ids
```

**Go**

```go
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

type Stream struct {
	ID           string                 `json:"id"`
	Distribution map[string]interface{} `json:"distribution"`
	Product      map[string]interface{} `json:"product"`
}

type Content struct {
	ContentVariant map[string]interface{} `json:"content_variant"`
	Streams        []Stream               `json:"streams"`
}

type Event struct {
	Contents []Content `json:"contents"`
}

func main() {
	token := "YOUR_API_KEY"
	baseUrl := "https://av-api.betradar.com"

	streamStatus := "av:stream_status:2"
	url := baseUrl + "/events?stream_status=" + streamStatus
	req, _ := http.NewRequest("GET", url, nil)
	req.Header.Add("Authorization", "Bearer "+token)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(map[string]string{"error": "Failed to fetch data from API."})
		return
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)

	var events []Event
	err = json.Unmarshal(body, &events)
	if err != nil {
		fmt.Println(map[string]string{"error": "Failed to decode JSON response."})
		return
	}

	streamIds := map[string]interface{}{
		"lco_live_standard": nil,
		"lco_live_4sight":   nil,
		"lcp_vod_clip":      nil,
	}

	for _, event := range events {
		for _, content := range event.Contents {
			contentVariantId, _ := content.ContentVariant["id"].(string)
			for _, stream := range content.Streams {
        productId, _ := stream.Product["id"].(string)
				distributionId, _ := stream.Distribution["id"].(string)
				if contentVariantId == "av:content_variant:1" && productId == "av:product:2" && distributionId == "av:distribution:1" {
					streamIds["lco_live_standard"] = stream.ID
				}
				if contentVariantId == "av:content_variant:2" && productId == "av:product:2" && distributionId == "av:distribution:1" {
					streamIds["lco_live_4sight"] = stream.ID
				}
				if productId == "av:product:8" && distributionId == "av:distribution:3" {
					streamIds["lcp_vod_clip"] = stream.ID
				}
			}
		}
	}

	fmt.Println(streamIds)
}
```

**Java**

```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Events {
    public static Object run() {
        try {
            String token = "YOUR_API_KEY";
            String baseUrl = "https://av-api.betradar.com";
            String streamStatus = "av:stream_status:2";

            Map<String, Object> streamIds = new HashMap<>();
            streamIds.put("lco_live_standard", new Object());
            streamIds.put("lco_live_4sight", new Object());
            streamIds.put("lcp_vod_clip", new Object());

            URL url = new URL(baseUrl + "/events?stream_status=" + streamStatus);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Authorization", "Bearer " + token);
            connection.setRequestMethod("GET");

            if (connection.getResponseCode() != 200) {
                throw new Exception("Failed to fetch data from API.");
            }

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder responseBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                responseBuilder.append(line);
            }
            reader.close();

            ObjectMapper mapper = new ObjectMapper();
            List<Map<String, Object>> response = mapper.readValue(
                responseBuilder.toString(),
                new TypeReference<List<Map<String, Object>>>() {}
            );

            if (response == null) {
                throw new Exception("Failed to decode JSON response.");
            }

            for (Map<String, Object> event : response) {
                List<Map<String, Object>> contents = (List<Map<String, Object>>) event.get("contents");
                for (Map<String, Object> content : contents) {
                    Map<String, Object> contentVariant = (Map<String, Object>) content.get("content_variant");
                    String contentVariantId = contentVariant != null ? (String) contentVariant.get("id") : null;

                    List<Map<String, Object>> streams = (List<Map<String, Object>>) content.get("streams");
                    for (Map<String, Object> stream : streams) {
                        Map<String, Object> product = (Map<String, Object>) stream.get("product");
                        Map<String, Object> distribution = (Map<String, Object>) stream.get("distribution");

                        String productId = product != null ? (String) product.get("id") : null;
                        String distributionId = distribution != null ? (String) distribution.get("id") : null;

                        if ("av:content_variant:1".equals(contentVariantId)
                                && "av:product:2".equals(productId)
                                && "av:distribution:1".equals(distributionId)) {
                            streamIds.put("lco_live_standard", stream.get("id"));
                        }

                        if ("av:content_variant:2".equals(contentVariantId)
                                && "av:product:2".equals(productId)
                                && "av:distribution:1".equals(distributionId)) {
                            streamIds.put("lco_live_4sight", stream.get("id"));
                        }

                        if ("av:product:8".equals(productId)
                                && "av:distribution:3".equals(distributionId)) {
                            streamIds.put("lcp_vod_clip", stream.get("id"));
                        }
                    }
                }
            }

            return streamIds;
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return error;
        }
    }
}
```

**Node.js**

```javascript
const token = "YOUR_API_KEY";
const baseUrl = "https://av-api.betradar.com";

const streamStatus = "av:stream_status:2";
const url = `${baseUrl}/events?stream_status=${streamStatus}`;
fetch(url, {
  headers: {
    "Authorization": `Bearer ${token}`
  }
})
  .then(res => {
    if (!res.ok) throw new Error("Failed to fetch data from API.");
    return res.json();
  })
  .then(data => {
    const streamIds = {
      lco_live_standard: null,
      lco_live_4sight: null,
      lcp_vod_clip: null
    };
    for (const event of data) {
      for (const content of event.contents || []) {
        for (const stream of content.streams || []) {
          const contentVariantId = content.content_variant?.id;
          const productId = stream.product?.id;
          const distributionId = stream.distribution?.id;
          if (contentVariantId === 'av:content_variant:1' && productId === 'av:product:2' && distributionId === 'av:distribution:1') {
            streamIds.lco_live_standard = stream.id;
          }
          if (contentVariantId === 'av:content_variant:2' && productId === 'av:product:2' && distributionId === 'av:distribution:1') {
            streamIds.lco_live_4sight = stream.id;
          }
          if (productId === 'av:product:8' && distributionId === 'av:distribution:3') {
            streamIds.lcp_vod_clip = stream.id;
          }
        }
      }
    }
    return streamIds;
  })
  .catch(err => ({ error: err.message }));
```

**Ruby**

```ruby
require "net/http"
require "uri"
require "json"

token = "YOUR_API_KEY"
base_url = "https://av-api.betradar.com"

stream_status = "av:stream_status:2"
url = "#{base_url}/events?stream_status=#{stream_status}"
uri = URI(url)
req = Net::HTTP::Get.new(uri)
req["Authorization"] = "Bearer #{token}"

res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
  http.request(req)
end

data = JSON.parse(res.body)

stream_ids = {
  lco_live_standard: nil,
  lco_live_4sight: nil,
  lcp_vod_clip: nil
}

data.each do |event|
  (event["contents"] || []).each do |content|
    (content["streams"] || []).each do |stream|
      content_variant_id = content["content_variant"] && content["content_variant"]["id"]
      product_id = stream["product"] && stream["product"]["id"]
      distribution_id = stream["distribution"] && stream["distribution"]["id"]
      if content_variant_id == 'av:content_variant:1' && product_id == 'av:product:2' && distribution_id == 'av:distribution:1'
        stream_ids[:lco_live_standard] = stream["id"]
      end
      if content_variant_id == 'av:content_variant:2' && product_id == 'av:product:2' && distribution_id == 'av:distribution:1'
        stream_ids[:lco_live_4sight] = stream["id"]
      end
      if product_id == 'av:product:8' && distribution_id == 'av:distribution:3'
        stream_ids[:lcp_vod_clip] = stream["id"]
      end
    end
  end
end

puts stream_ids
```

**C#**

```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;

class Program {
    static async Task Main() {
        var token = "YOUR_API_KEY";
        var baseUrl = "https://av-api.betradar.com";

        var streamStatus = "av:stream_status:2";
        var url = $"{baseUrl}/events?stream_status={streamStatus}";
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

        try {
            var response = await client.GetAsync(url);
            if (!response.IsSuccessStatusCode) {
                Console.WriteLine(JsonSerializer.Serialize(new { error = "Failed to fetch data from API." }));
                return;
            }

            var body = await response.Content.ReadAsStringAsync();
            var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
            List<EventItem> events;
            try {
                events = JsonSerializer.Deserialize<List<EventItem>>(body, options);
            } catch {
                Console.WriteLine(JsonSerializer.Serialize(new { error = "Failed to decode JSON response." }));
                return;
            }

            var streamIds = new Dictionary<string, string> {
                { "lco_live_standard", null },
                { "lco_live_4sight", null },
                { "lcp_vod_clip", null }
            };

            foreach (var ev in events ?? new List<EventItem>()) {
                foreach (var content in ev.Contents ?? new List<Content>()) {
                    string contentVariantId = null;
                    if (content.ContentVariant != null && content.ContentVariant.TryGetValue("id", out var cvIdObj)) {
                        contentVariantId = cvIdObj?.ToString();
                    }
                    foreach (var stream in content.Streams ?? new List<Stream>()) {
                        string productId = null;
                        string distributionId = null;
                        if (stream.Product != null && stream.Product.TryGetValue("id", out var prodIdObj)) {
                            productId = prodIdObj?.ToString();
                        }
                        if (stream.Distribution != null && stream.Distribution.TryGetValue("id", out var distIdObj)) {
                            distributionId = distIdObj?.ToString();
                        }

                        if (contentVariantId == "av:content_variant:1" && productId == "av:product:2" && distributionId == "av:distribution:1") {
                            streamIds["lco_live_standard"] = stream.Id;
                        }
                        if (contentVariantId == "av:content_variant:2" && productId == "av:product:2" && distributionId == "av:distribution:1") {
                            streamIds["lco_live_4sight"] = stream.Id;
                        }
                        if (productId == "av:product:8" && distributionId == "av:distribution:3") {
                            streamIds["lcp_vod_clip"] = stream.Id;
                        }
                    }
                }
            }

            Console.WriteLine(JsonSerializer.Serialize(streamIds));
        } catch (Exception e) {
            Console.WriteLine(JsonSerializer.Serialize(new { error = e.Message }));
        }
    }
}
```

## Get the stream URL of a stream

The code samples below are examples showing how to call the `GET /streams/<stream_id>/<stream_type>` endpoint in order to get the URL of a stream, knowing its stream ID. The requested stream type in these examples is HLS manifest. When requesting this endpoint, the "client side ID" must be passed in the query string parameter `csid`.

> **Tip**
>
> **Tip**: Some other query string parameters can be used in the request. Please see the documentation of this endpoint for more details.

**PHP**

```php
<?php
$token = "YOUR_API_KEY";
$ip = "END_USER_IP_ADDRESS";
$baseUrl = "https://av-api.betradar.com";
$streamId = "av:stream:123";
$csid = "actual_csid";

try {
    $response = file_get_contents("$baseUrl/streams/$streamId/hls-manifest?csid=$csid", false, stream_context_create([
        "http" => [
             "header" => "Authorization: Bearer $token\r\nX-Real-IP: $ip"
        ]
    ]));

    if ($response === false) {
        throw new Exception("Failed to fetch data from API.");
    }

    $response = json_decode($response, true);
    if ($response === null) {
        throw new Exception("Failed to decode JSON response.");
    }
    
    return $response['url'] ?? null;
} catch (Exception $e) {
    return ['error' => $e->getMessage()];
}
?>
```

**Python**

```python
import requests

def get_hls_url():
    token = "YOUR_API_KEY"
    ip = "END_USER_IP_ADDRESS"
    base_url = "https://av-api.betradar.com"
    streamId = "av:stream:123"
    csid = "actual_csid"

    url = f"{base_url}/streams/{streamId}/hls-manifest?csid={csid}"
    headers = {
        "Authorization": f"Bearer {token}",
        "X-Real-IP": ip
    }

    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        result = response.json()
        return result.get('url')
    except requests.RequestException:
        return {"error": "Failed to fetch data from API."}
    except ValueError:
        return {"error": "Failed to decode JSON response."}
```

**Go**

```go
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

func getHLSURL() interface{} {
	token := "YOUR_API_KEY"
	ip := "END_USER_IP_ADDRESS"
	baseUrl := "https://av-api.betradar.com"

	streamId := "av:stream:123"
	csid := "actual_csid"
	url := baseUrl + "/streams/" + streamId + "/hls-manifest?csid=" + csid
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return map[string]string{"error": "Failed to create request."}
	}

	req.Header.Add("Authorization", "Bearer "+token)
	req.Header.Add("X-Real-IP", ip)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return map[string]string{"error": "Failed to fetch data from API."}
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return map[string]string{"error": fmt.Sprintf("API returned status code %d", resp.StatusCode)}
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return map[string]string{"error": "Failed to read response body."}
	}

	var result map[string]interface{}
	if err := json.Unmarshal(body, &result); err != nil {
		return map[string]string{"error": "Failed to decode JSON response."}
	}

	if urlValue, ok := result["url"]; ok {
		return urlValue
	}
	return map[string]string{"error": "No URL found in response."}
}

func main() {
	url := getHLSURL()
	fmt.Println(url)
}
```

**Java**

```java
import java.net.http.*;
import java.net.URI;
import com.fasterxml.jackson.databind.*;
import java.util.Map;
import java.util.HashMap;

public class StreamExample {
    public static void main(String[] args) throws Exception {
        String token = "YOUR_API_KEY";
        String ip = "END_USER_IP_ADDRESS";
        String baseUrl = "https://av-api.betradar.com";

        String streamId = "av:stream:123";
        String csid = "actual_csid";
        String url = baseUrl + "/streams/" + streamId + "/hls-manifest?csid=" + csid;
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                                         .uri(URI.create(url))
                                         .header("Authorization", "Bearer " + token)
                                         .header("X-Real-IP", ip)
                                         .GET()
                                         .build();
        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() != 200) {
                System.out.println(Map.of("error", "Failed to fetch data from API."));
                return;
            }

            ObjectMapper mapper = new ObjectMapper();
            Map<?, ?> result = mapper.readValue(response.body(), Map.class);

            if (result.containsKey("url")) {
                System.out.println(result.get("url"));
            } else {
                System.out.println(Map.of("error", "No URL found in response."));
            }
        } catch (Exception e) {
            System.out.println(Map.of("error", e.getMessage()));
        }
    }
}
```

**Node.js**

```javascript
async function run() {
    const token = "YOUR_API_KEY";
    const ip = "END_USER_IP_ADDRESS";
    const baseUrl = "https://av-api.betradar.com";
    const streamId = "av:stream:123";
    const csid = "actual_csid";

    try {
        const response = await fetch(
            `${baseUrl}/streams/${streamId}/hls-manifest?csid=${csid}`,
            {
                headers: {
                    "Authorization": `Bearer ${token}`,
                    "X-Real-IP": ip
                }
            }
        );

        if (!response.ok) {
            throw new Error("Failed to fetch data from API.");
        }

        const data = await response.json();
        if (data === null) {
            throw new Error("Failed to decode JSON response.");
        }

        return data.url ?? null;
    } catch (e) {
        return { error: e.message };
    }
}
```

**Ruby**

```ruby
require "net/http"
require "uri"
require "json"

def get_hls_url
  token = "YOUR_API_KEY"
  ip = "END_USER_IP_ADDRESS"
  base_url = "https://av-api.betradar.com"

  stream_id = "av:stream:123"
  csid = "actual_csid"
  url = "#{base_url}/streams/#{stream_id}/hls-manifest?csid=#{csid}"
  uri = URI(url)
  req = Net::HTTP::Get.new(uri)
  req["Authorization"] = "Bearer #{token}"
  req["X-Real-IP"] = ip

  begin
    res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
      http.request(req)
    end

    unless res.is_a?(Net::HTTPSuccess)
      return { error: "Failed to fetch data from API. Status code: #{res.code}" }
    end

    result = JSON.parse(res.body)
    return result["url"] || { error: "No URL found in response." }
  rescue StandardError => e
    return { error: e.message }
  end
end

puts get_hls_url
```

**C#**

```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;

class Program
{
    static async Task Main()
    {
        var token = "YOUR_API_KEY";
        var ip = "END_USER_IP_ADDRESS";
        var baseUrl = "https://av-api.betradar.com";

        var streamId = "av:stream:123";
        var csid = "actual_csid";
        var url = $"{baseUrl}/streams/{streamId}/hls-manifest?csid={csid}";
        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
        client.DefaultRequestHeaders.Add("X-Real-IP", ip);

        try
        {
            var response = await client.GetAsync(url);
            if (!response.IsSuccessStatusCode)
            {
                return new Dictionary<string, string>
                {
                    { "error", $"Failed to fetch data from API. Status code: {response.StatusCode}" }
                };
            }

            var content = await response.Content.ReadAsStringAsync();
            using var doc = JsonDocument.Parse(content);

            if (doc.RootElement.TryGetProperty("url", out var urlProp))
            {
                return new Dictionary<string, string> { { "url", urlProp.GetString() } };
            }
            else
            {
                return new Dictionary<string, string> { { "error", "No URL found in response." } };
            }
        }
        catch (Exception e)
        {
            return new Dictionary<string, string> { { "error", e.Message } };
        }
    }
}
```
