### Example Guide Response Source: https://github.com/iptv-org/api/blob/master/_autodocs/endpoints.md This JSON object represents an Electronic Program Guide (EPG) entry, linking a channel and feed to a specific guide provider. It includes the guide provider's site, ID, name, language, and an array of available guide sources with their host, URL, and format. ```json [ { "channel": "BBCOne.uk", "feed": "EastMidlandsHD", "site": "sky.co.uk", "site_id": "bbcone", "site_name": "BBC One", "lang": "en", "sources": [ { "host": "example.com", "url": "https://example.com/guide.xml", "format": "XML" } ] } ] ``` -------------------------------- ### Java Fetch Channels with OkHttp Source: https://github.com/iptv-org/api/blob/master/_autodocs/integration-guide.md Fetch channel data from the IPTV-ORG API using OkHttp in Java. This example shows how to make an HTTP GET request, handle the response, and deserialize the JSON body into a List of Channel objects using Gson. ```java import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import com.google.gson.Gson; import com.google.gson.reflect. TypeToken; import java.util.List; public class IPTVClient { private static final String BASE_URL = "https://iptv-org.github.io/api"; private static final OkHttpClient HTTP_CLIENT = new OkHttpClient(); private static final Gson GSON = new Gson(); public static List fetchChannels() throws Exception { String url = BASE_URL + "/channels.json"; Request request = new Request.Builder().url(url).build(); try (Response response = HTTP_CLIENT.newCall(request).execute()) { if (!response.isSuccessful()) { throw new RuntimeException("HTTP " + response.code()); } String body = response.body().string(); return GSON.fromJson(body, new TypeToken>(){}.getType()); } } } ``` -------------------------------- ### Example Logo Data Structure Source: https://github.com/iptv-org/api/blob/master/README.md An example of the JSON structure for a single logo entry. This includes channel, feed, usage status, dimensions, format, and URL. ```json [ //... { "channel": "France3.fr", "feed": "ParisIledeFrance", "in_use": true, "tags": ["horizontal", "white"], "width": 1000, "height": 468, "format": "SVG", "url": "https://example.com/logo.svg" }, //... ] ``` -------------------------------- ### Nullable vs. Missing Array Example Source: https://github.com/iptv-org/api/blob/master/_autodocs/data-specifications.md Demonstrates the difference between a field that can be null and a field that is an empty array. ```javascript // Nullable field (can be null) { "website": null } // Missing array (not present at all) // This typically means count is 0, not null { "alt_names": [] } // not { "alt_names": null } ``` -------------------------------- ### cURL Examples Source: https://github.com/iptv-org/api/blob/master/_autodocs/configuration.md Demonstrates fetching API data using cURL, including filtering results with jq, enabling gzip compression, and performing conditional requests using ETags. ```bash # Single endpoint curl -H "User-Agent: MyApp/1.0" \ "https://iptv-org.github.io/api/channels.json" | jq '.[] | select(.country == "US")' # With compression curl -H "Accept-Encoding: gzip" \ "https://iptv-org.github.io/api/feeds.json" | gunzip # With conditional request (using ETag) curl -i -H "If-None-Match: \"abc123\"" \ "https://iptv-org.github.io/api/channels.json" ``` -------------------------------- ### Foreign Key Pattern Examples Source: https://github.com/iptv-org/api/blob/master/_autodocs/data-specifications.md Illustrates foreign key relationships between different data types like Channel and Feed. ```plaintext Channel.id → Feed.channel Feed.channel → Channel.id Feed.id → Stream.feed (if Stream.channel matches Feed.channel) ``` -------------------------------- ### IPTV Guides Data Structure Source: https://github.com/iptv-org/api/blob/master/README.md This JSON structure outlines IPTV guide information. It contains channel and feed IDs, site details, language, and a list of sources for the guide data. ```json [ //... { "channel": "BBCOne.uk", "feed": "EastMidlandsHD", "site": "sky.co.uk", "site_id": "bbcone", "site_name": "BBC One", "lang": "en", "sources": [ { "host": "example.com", "url": "https://example.com/guide.xml", "format": "XML" } ] }, //... ] ``` -------------------------------- ### Cardinality Examples Source: https://github.com/iptv-org/api/blob/master/_autodocs/data-specifications.md Shows the one-to-many (1:N) and many-to-many (N:M) relationships between data types. ```plaintext - 1:N → Channel:Feed (one channel has many feeds) - 1:N → Channel:Stream (one channel has many streams) - 1:N → Channel:Logo (one channel has many logos) - 1:N → Channel:Guide (one channel has many guides) - N:M → Channel:Category (many channels in many categories) - N:M → Feed:Timezone (many feeds broadcast in many timezones) - N:M → Feed:Language (many feeds broadcast many languages) - N:M → Region:Country (many regions contain many countries) ``` -------------------------------- ### Blocklist Data Structure Example Source: https://github.com/iptv-org/api/blob/master/README.md An example of the JSON structure for a blocked channel entry. Each entry specifies the channel ID, the reason for blocking, and a reference to the request or notice. ```json [ //... { "channel": "AnimalPlanetEast.us", "reason": "dmca", "ref": "https://github.com/iptv-org/iptv/issues/1831" }, //... ] ``` -------------------------------- ### Guide Specification Source: https://github.com/iptv-org/api/blob/master/_autodocs/data-specifications.md Defines the schema for guide data, including channel references, feed information, site details, and source URLs for EPG data. ```APIDOC ## GET guides.json ### Description Retrieves a list of guides, each containing information about a TV channel's electronic program guide (EPG) data sources. ### Method GET ### Endpoint /guides.json ### Parameters #### Query Parameters - **channel** (string) - Optional - Filter guides by channel ID. - **feed** (string) - Optional - Filter guides by feed ID. ### Response #### Success Response (200) - **channel** (string | null) - References channel ID. - **feed** (string | null) - References feed ID. - **site** (string) - Required - EPG provider domain name. - **site_id** (string) - Required - Channel ID on the provider. - **site_name** (string) - Required - Channel name on the provider. - **lang** (string) - Required - Guide language code (ISO 639-1). - **sources** (GuideSource[]) - Required - Array of guide data sources. **GuideSource Schema:** - **host** (string) - Required - Source hostname. - **url** (string) - Required - Guide data URL. - **format** (string) - Required - Guide format type ('XML' or 'JSON'). ### Response Example { "example": "[ { "channel": "BBCOne.uk", "feed": "EastMidlands", "site": "sky.com", "site_id": "bbcone", "site_name": "BBC One", "lang": "en", "sources": [ { "host": "epg.example.com", "url": "https://epg.example.com/guide.xml", "format": "XML" } ] } ]" } ``` -------------------------------- ### Guides API Source: https://github.com/iptv-org/api/blob/master/README.md Retrieves electronic program guides (EPG) for various channels. Each guide entry includes channel and feed IDs, site information, language, and a list of available sources. ```APIDOC ## GET /guides.json ### Description Retrieves electronic program guides (EPG) for various channels. ### Endpoint https://iptv-org.github.io/api/guides.json ### Response #### Success Response (200) - **channel** (string or null) - Channel ID - **feed** (string or null) - Feed ID - **site** (string) - Site domain name - **site_id** (string) - Unique channel ID used on the site - **site_name** (string) - Channel name used on the site - **lang** (string) - Language of the guide (ISO 639-1 code) - **sources** (array) - List of available sources of the guide ### Response Example { "example": "[ { \"channel\": \"BBCOne.uk\", \"feed\": \"EastMidlandsHD\", \"site\": \"sky.co.uk\", \"site_id\": \"bbcone\", \"site_name\": \"BBC One\", \"lang\": \"en\", \"sources\": [ { \"host\": \"example.com\", \"url\": \"https://example.com/guide.xml\", \"format\": \"XML\" } ] } ]" ``` -------------------------------- ### Find EPG Sources for a Channel (JavaScript) Source: https://github.com/iptv-org/api/blob/master/_autodocs/quick-start.md Retrieves Electronic Program Guide (EPG) sources for a channel, optionally filtering by language. Requires fetching all guides first. ```javascript async function getGuides(channelId, language = null) { const guides = await fetch('https://iptv-org.github.io/api/guides.json') .then(r => r.json()); return guides.filter(g => g.channel === channelId && (!language || g.lang === language) ); } // Usage const allGuides = await getGuides('BBCOne.uk'); const englishGuides = await getGuides('BBCOne.uk', 'en'); ``` -------------------------------- ### Example Channel Response Source: https://github.com/iptv-org/api/blob/master/_autodocs/endpoints.md This JSON snippet shows an example of a channel object returned by the channels endpoint. It includes details like channel ID, name, country, and categories. ```json [ { "id": "AnhuiTV.cn", "name": "Anhui TV", "alt_names": ["安徽卫视"], "network": "Anhui", "owners": ["China Central Television"], "country": "CN", "categories": ["general"], "is_nsfw": false, "launched": "2016-07-28", "closed": "2020-05-31", "replaced_by": "CCTV1.cn", "website": "http://www.ahtv.cn/" } ] ``` -------------------------------- ### Rust Fetch Channels with Reqwest Source: https://github.com/iptv-org/api/blob/master/_autodocs/integration-guide.md Fetch channel data from the IPTV-ORG API using the Reqwest library in Rust. This example demonstrates making an asynchronous HTTP GET request and deserializing the JSON response into a Vec of Channel structs. ```rust use reqwest::Client; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] struct Channel { id: String, name: String, country: String, categories: Vec, is_nsfw: bool, } #[tokio::main] async fn main() -> Result<(), Box> { let client = Client::new(); let response = client .get("https://iptv-org.github.io/api/channels.json") .send() .await?; let channels: Vec = response.json().await?; println!("Found {} channels", channels.len()); for channel in &channels[..5.min(channels.len())] { println!("{} ({})", channel.name, channel.country); } Ok(()) } ``` -------------------------------- ### Example Feed Data Structure Source: https://github.com/iptv-org/api/blob/master/README.md An example of the JSON structure for a single feed entry. This includes channel, feed ID, name, broadcast details, and format. ```json [ //... { "channel": "France3.fr", "id": "ParisIledeFrance", "name": "Paris Ile-de-France", "alt_names": ["Paris Île-de-France"], "is_main": false, "broadcast_area": ["c/FR"], "timezones": ["Europe/Paris"], "languages": ["fra"], "format": "576i" }, //... ] ``` -------------------------------- ### Guide and GuideSource Data Types Source: https://github.com/iptv-org/api/blob/master/_autodocs/types.md Defines the structure for Electronic Program Guide (EPG) metadata and its associated data sources. Includes channel mapping, site information, language, and source details like host, URL, and format. ```typescript interface Guide { channel?: string | null; feed?: string | null; site: string; site_id: string; site_name: string; lang: string; sources: GuideSource[]; } interface GuideSource { host: string; url: string; format: string; } ``` -------------------------------- ### Guide Source: https://github.com/iptv-org/api/blob/master/_autodocs/types.md Represents Electronic Program Guide (EPG) metadata linking to broadcast guide sources. It includes site information, channel IDs, and an array of guide data sources. ```APIDOC ## Guide ### Description Represents Electronic Program Guide (EPG) metadata linking to broadcast guide sources. It includes site information, channel IDs, and an array of guide data sources. ### Type Definition ```typescript interface Guide { channel?: string | null; feed?: string | null; site: string; site_id: string; site_name: string; lang: string; sources: GuideSource[]; } interface GuideSource { host: string; url: string; format: string; } ``` ### Field Definitions (Guide) | Field | Type | Required | Description | |-------|------|----------|-------------| | channel | string \| null | No | Channel ID for this guide mapping | | feed | string \| null | No | Feed ID for this guide mapping | | site | string | Yes | Domain name of the EPG provider (e.g., "sky.co.uk", "tvguide.com") | | site_id | string | Yes | Channel/program ID as used on the guide site | | site_name | string | Yes | Channel name as displayed on the guide site | | lang | string | Yes | ISO 639-1 language code of the guide (e.g., "en", "fr") | | sources | GuideSource[] | Yes | Array of available guide data sources | ### Field Definitions (GuideSource) | Field | Type | Required | Description | |-------|------|----------|-------------| | host | string | Yes | Hostname of the guide source | | url | string | Yes | Complete URL to access the guide data | | format | string | Yes | Format of guide data: "XML" (XMLTV format) or "JSON" | ### Source `https://iptv-org.github.io/api/guides.json` ``` -------------------------------- ### Channel Data Structure Example Source: https://github.com/iptv-org/api/blob/master/README.md An example of a channel object within the channels.json response. It includes details like ID, name, country, categories, and broadcast dates. ```json [ //... { "id": "AnhuiTV.cn", "name": "Anhui TV", "alt_names": ["安徽卫视"], "network": "Anhui", "owners": ["China Central Television"], "country": "CN", "categories": ["general"], "is_nsfw": false, "launched": "2016-07-28", "closed": "2020-05-31", "replaced_by": "CCTV1.cn", "website": "http://www.ahtv.cn/" }, //... ] ``` -------------------------------- ### Load Channels to SQLite and Query in Python Source: https://github.com/iptv-org/api/blob/master/_autodocs/integration-guide.md Loads channel data fetched from the API into a SQLite database and provides an example of querying channels by country. Assumes a `fetch_channels` function is available. ```python import sqlite3 import json def load_channels_to_sqlite(db_path='iptv.db'): """Load channels into SQLite database""" channels = fetch_channels() conn = sqlite3.connect(db_path) cursor = conn.cursor() # Create table cursor.execute(''' CREATE TABLE IF NOT EXISTS channels ( id TEXT PRIMARY KEY, name TEXT NOT NULL, country TEXT NOT NULL, categories TEXT, is_nsfw BOOLEAN, website TEXT, launched TEXT, closed TEXT ) ''') # Insert data for ch in channels: cursor.execute(''' INSERT OR REPLACE INTO channels (id, name, country, categories, is_nsfw, website, launched, closed) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ''', ( ch['id'], ch['name'], ch['country'], json.dumps(ch.get('categories', [])), ch.get('is_nsfw', False), ch.get('website'), ch.get('launched'), ch.get('closed') )) conn.commit() conn.close() # Query examples def query_channels_by_country(db_path, country_code): conn = sqlite3.connect(db_path) cursor = conn.cursor() cursor.execute('SELECT * FROM channels WHERE country = ?', (country_code,)) return cursor.fetchall() ``` -------------------------------- ### Lazy Load IPTV Endpoints Source: https://github.com/iptv-org/api/blob/master/_autodocs/quick-start.md Load only necessary data initially to improve application startup time. This example shows loading channels first, then fetching feeds only when needed, demonstrating a lazy loading approach. ```javascript // Load only channels const channels = await fetch('...channels.json').then(r => r.json()); // Later, load feeds only if user navigates to details const feeds = await fetch('...feeds.json').then(r => r.json()); ``` -------------------------------- ### Fetch IPTV Channels with Redis Caching Source: https://github.com/iptv-org/api/blob/master/_autodocs/integration-guide.md This Node.js example fetches channel data from the API and caches it in Redis for one hour. It first checks the cache and only fetches from the API if the data is not found. ```javascript import redis from 'redis'; const client = redis.createClient(); async function fetchChannelsWithRedis() { const key = 'iptv:channels'; // Check cache let data = await client.get(key); if (data) { return JSON.parse(data); } // Fetch from API const response = await fetch('https://iptv-org.github.io/api/channels.json'); data = await response.json(); // Cache for 1 hour await client.setEx(key, 3600, JSON.stringify(data)); return data; } ``` -------------------------------- ### Blocklist Endpoint Example Source: https://github.com/iptv-org/api/blob/master/_autodocs/endpoints.md Lists channels that are blocked or removed from the database. The response includes the channel ID, a reason code ('dmca' or 'nsfw'), and a reference URL. ```json [ { "channel": "AnimalPlanetEast.us", "reason": "dmca", "ref": "https://github.com/iptv-org/iptv/issues/1831" } ] ``` -------------------------------- ### Null Safety Access Example Source: https://github.com/iptv-org/api/blob/master/_autodocs/data-specifications.md Shows how to safely access potentially null or undefined properties in JavaScript objects. ```javascript // Safe access for potentially null fields const website = channel.website || 'N/A'; const owner = channel.owners?.[0] ?? 'Unknown'; const date = channel.launched?.split('-')[0] || 'Unknown year'; ``` -------------------------------- ### Build Data Index for Efficient Lookups Source: https://github.com/iptv-org/api/blob/master/_autodocs/quick-start.md Constructs comprehensive lookup tables (indexes) for channels, feeds, streams, logos, and guides by fetching all relevant JSON data. This optimizes subsequent data retrieval operations. ```javascript async function buildIndex() { const [channels, feeds, streams, logos, guides] = await Promise.all([ fetch('https://iptv-org.github.io/api/channels.json').then(r => r.json()), fetch('https://iptv-org.github.io/api/feeds.json').then(r => r.json()), fetch('https://iptv-org.github.io/api/streams.json').then(r => r.json()), fetch('https://iptv-org.github.io/api/logos.json').then(r => r.json()), fetch('https://iptv-org.github.io/api/guides.json').then(r => r.json()) ]); const index = { channelsById: new Map(channels.map(c => [c.id, c])), feedsByChannel: {}, streamsByFeed: {}, logosByChannel: {}, guidesByChannel: {} }; feeds.forEach(f => { if (!index.feedsByChannel[f.channel]) { index.feedsByChannel[f.channel] = []; } index.feedsByChannel[f.channel].push(f); }); streams.forEach(s => { if (s.feed) { if (!index.streamsByFeed[s.feed]) { index.streamsByFeed[s.feed] = []; } index.streamsByFeed[s.feed].push(s); } }); logos.forEach(l => { if (!index.logosByChannel[l.channel]) { index.logosByChannel[l.channel] = []; } index.logosByChannel[l.channel].push(l); }); guides.forEach(g => { if (g.channel) { if (!index.guidesByChannel[g.channel]) { index.guidesByChannel[g.channel] = []; } index.guidesByChannel[g.channel].push(g); } }); return index; } // Usage const index = await buildIndex(); const channel = index.channelsById.get('BBCOne.uk'); const feeds = index.feedsByChannel['BBCOne.uk'] || []; const logos = index.logosByChannel['BBCOne.uk'] || []; ``` -------------------------------- ### Example Language Response Source: https://github.com/iptv-org/api/blob/master/_autodocs/endpoints.md This JSON object represents a supported language, including its display name and its ISO 639-3 three-letter code. ```json [ { "name": "French", "code": "fra" } ] ``` -------------------------------- ### City Data Example Source: https://github.com/iptv-org/api/blob/master/README.md This snippet displays the structure for city data, containing country and subdivision codes, city name, UN/LOCODE, and Wikidata ID. Use this for precise location-based information. ```json [ //... { "country": "CN", "subdivision": "CN-SD", "name": "Yantai", "code": "CNYAT", "wikidata_id": "Q210493" }, //... ] ``` -------------------------------- ### Example Category Response Source: https://github.com/iptv-org/api/blob/master/_autodocs/endpoints.md This JSON object represents a channel category, including a unique identifier, display name, and a short description of the content type. ```json [ { "id": "documentary", "name": "Documentary", "description": "Programming that depicts a person or real-world event" } ] ``` -------------------------------- ### Example Logo Response Source: https://github.com/iptv-org/api/blob/master/_autodocs/endpoints.md This JSON snippet displays a logo object from the logos endpoint, providing metadata for channel and feed logos, including dimensions, format, and usage status. ```json [ { "channel": "France3.fr", "feed": "ParisIledeFrance", "in_use": true, "tags": ["horizontal", "white"], "width": 1000, "height": 468, "format": "SVG", "url": "https://example.com/logo.svg" } ] ``` -------------------------------- ### Use IndexedDB for Large Datasets Source: https://github.com/iptv-org/api/blob/master/_autodocs/quick-start.md Store large IPTV datasets like channels, feeds, and streams in IndexedDB for efficient local querying. This example sets up a Dexie.js database and demonstrates syncing data and querying locally. ```javascript const db = new Dexie('IPTVDatabase'); db.version(1).stores({ channels: 'id', feeds: 'id', streams: 'id' }); async function syncToIndexedDB() { const channels = await fetch('...channels.json').then(r => r.json()); await db.channels.bulkAdd(channels); } // Query locally const usChannels = await db.channels.where('country').equals('US').toArray(); ``` -------------------------------- ### Cities Endpoint Example Source: https://github.com/iptv-org/api/blob/master/_autodocs/endpoints.md Retrieves cities and municipalities with geographic metadata. The response contains country code, an optional subdivision code, city name, UN/LOCODE, and Wikidata ID. ```json [ { "country": "CN", "subdivision": "CN-SD", "name": "Yantai", "code": "CNYAT", "wikidata_id": "Q210493" } ] ``` -------------------------------- ### Example Feed Response Source: https://github.com/iptv-org/api/blob/master/_autodocs/endpoints.md This JSON snippet illustrates a feed object from the feeds endpoint, detailing regional or language-specific variants of a channel, including broadcast area and timezones. ```json [ { "channel": "France3.fr", "id": "ParisIledeFrance", "name": "Paris Ile-de-France", "alt_names": ["Paris Île-de-France"], "is_main": false, "broadcast_area": ["c/FR"], "timezones": ["Europe/Paris"], "languages": ["fra"], "format": "576i" } ] ``` -------------------------------- ### Timezones Endpoint Example Source: https://github.com/iptv-org/api/blob/master/_autodocs/endpoints.md Provides IANA timezones with UTC offsets and associated countries. The response includes the timezone ID, UTC offset, and a list of country codes within that timezone. ```json [ { "id": "Europe/London", "utc_offset": "+00:00", "countries": ["UK", "GG", "IM", "JE"] } ] ``` -------------------------------- ### Country Data Example Source: https://github.com/iptv-org/api/blob/master/README.md This snippet shows the structure of a country object, including its name, ISO code, official languages, and flag emoji. Use this data to identify and categorize countries. ```json [ //... { "name": "Canada", "code": "CA", "languages": ["eng", "fra"], "flag": "🇨🇦" }, //... ] ``` -------------------------------- ### Timezone Data Example Source: https://github.com/iptv-org/api/blob/master/README.md This snippet presents the structure for timezone data, including the timezone ID, UTC offset, and a list of countries within that timezone. Use this for time-sensitive applications and data. ```json [ //... { "id": "Europe/London", "utc_offset": "+00:00", "countries": ["UK", "GG", "IM", "JE"] }, //... ] ``` -------------------------------- ### Example Stream Response Source: https://github.com/iptv-org/api/blob/master/_autodocs/endpoints.md This JSON object represents a single playable stream entry, including channel and feed IDs, stream title, URL, and optional metadata like referrer, user agent, quality, and availability labels. ```json [ { "channel": "France3.fr", "feed": "NordPasdeCalaisHD", "title": "France 3 Nord Pas-de-Calais HD", "url": "http://1111296894.rsc.cdn77.org/LS-ATL-54548-6/index.m3u8", "referrer": "http://example.com/", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", "quality": "720p", "label": "Geo-blocked" } ] ``` -------------------------------- ### Subdivisions Endpoint Example Source: https://github.com/iptv-org/api/blob/master/_autodocs/endpoints.md Fetches country subdivisions like states and provinces. The response includes country code, subdivision name, ISO 3166-2 code, and an optional parent subdivision code. ```json [ { "country": "BD", "name": "Bandarban", "code": "BD-01", "parent": "BD-B" } ] ``` -------------------------------- ### Region Data Example Source: https://github.com/iptv-org/api/blob/master/README.md This snippet shows the format for region data, which includes a region code, its full name, and a list of associated country codes. This is helpful for grouping countries into broader geographical or political areas. ```json [ //... { "code": "MAGHREB", "name": "Maghreb", "countries": ["DZ", "LY", "MA", "MR", "TN"] }, //... ] ``` -------------------------------- ### Fetch All Channels (cURL) Source: https://github.com/iptv-org/api/blob/master/_autodocs/quick-start.md Demonstrates how to fetch all channel data from the API using cURL and display the first 100 lines. ```bash curl https://iptv-org.github.io/api/channels.json | head -100 ``` -------------------------------- ### Fetch All Channels (JavaScript) Source: https://github.com/iptv-org/api/blob/master/_autodocs/quick-start.md Demonstrates how to fetch all channel data from the API using JavaScript's fetch API. ```javascript // Fetch all channels const response = await fetch('https://iptv-org.github.io/api/channels.json'); const channels = await response.json(); console.log(`Total channels: ${channels.length}`); console.log(`First channel:`, channels[0]); ``` -------------------------------- ### Fetch All Channels (Python) Source: https://github.com/iptv-org/api/blob/master/_autodocs/quick-start.md Demonstrates how to fetch all channel data from the API using Python's requests library. ```python import requests response = requests.get('https://iptv-org.github.io/api/channels.json') channels = response.json() print(f"Total channels: {len(channels)}") print(f"First channel: {channels[0]}") ``` -------------------------------- ### Fetch Channels and Streams using HttpClient in C# Source: https://github.com/iptv-org/api/blob/master/_autodocs/integration-guide.md Demonstrates how to use System.Net.HttpClient to fetch channel and stream data from the IPTV API. Requires Channel and Stream classes for deserialization. ```csharp using System; using System.Collections.Generic; using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; class IPTVClient { private static readonly string BASE_URL = "https://iptv-org.github.io/api"; private static readonly HttpClient httpClient = new HttpClient(); public async Task> FetchChannels() { string url = $"{BASE_URL}/channels.json"; HttpResponseMessage response = await httpClient.GetAsync(url); response.EnsureSuccessStatusCode(); string json = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize>(json); } public async Task> FetchStreams() { string url = $"{BASE_URL}/streams.json"; HttpResponseMessage response = await httpClient.GetAsync(url); response.EnsureSuccessStatusCode(); string json = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize>(json); } } public class Channel { public string Id { get; set; } public string Name { get; set; } public string Country { get; set; } public List Categories { get; set; } public bool IsNsfw { get; set; } } ``` -------------------------------- ### Data Flow Overview Source: https://github.com/iptv-org/api/blob/master/_autodocs/README.md Illustrates the static JSON distribution system for the IPTV Org API, from GitHub repositories to consumer applications via GitHub Pages and a global CDN. ```text GitHub Repositories (database, iptv, epg) ↓ JSON files generated/aggregated ↓ GitHub Pages static hosting ↓ Global CDN (Cloudflare) ↓ Consumer applications ``` -------------------------------- ### Go Client with Caching Source: https://github.com/iptv-org/api/blob/master/_autodocs/integration-guide.md Implement a Go client that fetches data from the IPTV-ORG API and caches responses locally to reduce redundant requests. It checks cache validity based on a maximum age. ```go package main import ( "encoding/json" "os" "path/filepath" "time" ) type IPTVClient struct { cacheDir string maxAge time.Duration } func NewIPTVClient(cacheDir string) *IPTVClient { os.MkdirAll(cacheDir, 0755) return &IPTVClient{ cacheDir: cacheDir, maxAge: time.Hour, } } func (c *IPTVClient) cachePath(endpoint string) string { return filepath.Join(c.cacheDir, endpoint+".json") } func (c *IPTVClient) isCacheValid(endpoint string) bool { path := c.cachePath(endpoint) info, err := os.Stat(path) if err != nil { return false } return time.Since(info.ModTime()) < c.maxAge } func (c *IPTVClient) Fetch(endpoint string, v interface{}) error { cachePath := c.cachePath(endpoint) // Check cache if c.isCacheValid(endpoint) { data, _ := os.ReadFile(cachePath) return json.Unmarshal(data, v) } // Fetch from API url := "https://iptv-org.github.io/api/" + endpoint + ".json" resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) os.WriteFile(cachePath, body, 0644) return json.Unmarshal(body, v) } ``` -------------------------------- ### Go Basic HTTP Client for Channels Source: https://github.com/iptv-org/api/blob/master/_autodocs/integration-guide.md A basic Go client to fetch and parse channel data from the iptv-org API using standard net/http and encoding/json packages. Demonstrates essential Go HTTP request handling. ```go package main import ( "encoding/json" "fmt" "io" "net/http" ) type Channel struct { ID string `json:"id"` Name string `json:"name"` Country string `json:"country"` Categories []string `json:"categories"` IsNSFW bool `json:"is_nsfw"` } func FetchChannels() ([]Channel, error) { resp, err := http.Get("https://iptv-org.github.io/api/channels.json") if err != nil { return nil, err } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var channels []Channel if err := json.Unmarshal(body, &channels); err != nil { return nil, err } return channels, nil } func main() { channels, err := FetchChannels() if err != nil { panic(err) } fmt.Printf("Found %d channels\n", len(channels)) for _, ch := range channels[:5] { fmt.Printf("%s (%s)\n", ch.Name, ch.Country) } } ``` -------------------------------- ### Uniqueness Guarantees Examples Source: https://github.com/iptv-org/api/blob/master/_autodocs/data-specifications.md Lists fields that are guaranteed to be unique within their respective data types or globally. ```plaintext - Channel.id (globally unique) - Feed.(channel, id) (unique per channel) - Logo.(channel, feed) (unique per channel+feed) - Country.code (globally unique) - Subdivision.(country, code) (unique per country) - City.code (globally unique) - Category.id (globally unique) - Language.code (globally unique) - Timezone.id (globally unique) - Region.code (globally unique) ``` -------------------------------- ### Python Async/Await IPTV Client Source: https://github.com/iptv-org/api/blob/master/_autodocs/integration-guide.md An asynchronous Python client for fetching IPTV data concurrently using aiohttp. Ideal for high-performance applications requiring parallel requests. ```python import aiohttp import asyncio from typing import List class AsyncIPTVClient: BASE_URL = 'https://iptv-org.github.io/api' async def fetch_endpoint(self, endpoint: str) -> List: """Fetch endpoint asynchronously""" async with aiohttp.ClientSession() as session: url = f'{self.BASE_URL}/{endpoint}.json' async with session.get(url, timeout=10) as response: return await response.json() async def fetch_all(self): """Fetch all endpoints in parallel""" endpoints = [ 'channels', 'feeds', 'streams', 'guides', 'logos', 'categories', 'countries', 'languages' ] tasks = [self.fetch_endpoint(ep) for ep in endpoints] results = await asyncio.gather(*tasks) return dict(zip(endpoints, results)) # Usage async def main(): client = AsyncIPTVClient() data = await client.fetch_all() print(f"Loaded {len(data['channels'])} channels") asyncio.run(main()) ``` -------------------------------- ### Data Indexing Pattern Source: https://github.com/iptv-org/api/blob/master/_autodocs/README.md Illustrates building Maps for efficient O(1) data lookups. It shows creating a map of channels by ID and grouping feeds by channel, enabling quick retrieval of related data. ```javascript // Build Maps for O(1) lookups const channelsById = new Map(channels.map(c => [c.id, c])); const feedsByChannel = new Map(); feeds.forEach(f => { if (!feedsByChannel.has(f.channel)) feedsByChannel.set(f.channel, []); feedsByChannel.get(f.channel).push(f); }); // Efficient access const channel = channelsById.get('BBCOne.uk'); const feeds = feedsByChannel.get('BBCOne.uk') || []; ``` -------------------------------- ### Get Geographic Data (JavaScript) Source: https://github.com/iptv-org/api/blob/master/_autodocs/quick-start.md Fetches country, subdivision, city, and region data concurrently. Useful for building location hierarchies. ```javascript async function getGeographicData() { const [countries, subdivisions, cities, regions] = await Promise.all([ fetch('https://iptv-org.github.io/api/countries.json').then(r => r.json()), fetch('https://iptv-org.github.io/api/subdivisions.json').then(r => r.json()), fetch('https://iptv-org.github.io/api/cities.json').then(r => r.json()), fetch('https://iptv-org.github.io/api/regions.json').then(r => r.json()) ]); return { countries, subdivisions, cities, regions }; } // Usage: Build a location tree const geo = await getGeographicData(); const usSubdivisions = geo.subdivisions.filter(s => s.country === 'US'); const californiaCities = geo.cities.filter(c => c.subdivision === 'US-CA'); ``` -------------------------------- ### Build Data Index for Efficient Lookups Source: https://github.com/iptv-org/api/blob/master/_autodocs/README.md Fetches channels and feeds, then constructs a Map to group feeds by channel for quick access. Useful for relating different data types. ```javascript const channels = await fetch('.../channels.json').then(r => r.json()); const feeds = await fetch('.../feeds.json').then(r => r.json()); const feedsByChannel = new Map(); feeds.forEach(f => { if (!feedsByChannel.has(f.channel)) { feedsByChannel.set(f.channel, []); } feedsByChannel.get(f.channel).push(f); }); const channelFeeds = feedsByChannel.get('BBCOne.uk'); ``` -------------------------------- ### Get Geographic Hierarchy Source: https://github.com/iptv-org/api/blob/master/_autodocs/README.md Fetches country and subdivision data, then filters subdivisions to find those belonging to a specific country and creates a Map for efficient lookup. ```javascript const countries = await fetch('.../countries.json').then(r => r.json()); const subdivisions = await fetch('.../subdivisions.json').then(r => r.json()); const usSubdivisions = subdivisions.filter(s => s.country === 'US'); const states = new Map(usSubdivisions.map(s => [s.code, s])); ``` -------------------------------- ### Example Country Response Source: https://github.com/iptv-org/api/blob/master/_autodocs/endpoints.md This JSON object represents a country, including its name, ISO 3166-1 alpha-2 code, an array of official language codes, and its flag emoji. ```json [ { "name": "Canada", "code": "CA", "languages": ["eng", "fra"], "flag": "🇨🇦" } ] ``` -------------------------------- ### Python Class-Based IPTV Client Source: https://github.com/iptv-org/api/blob/master/_autodocs/integration-guide.md A synchronous Python client for fetching IPTV data using the requests library. Useful for straightforward API interactions. ```python import requests from typing import List, Dict, Any class IPTVClient: BASE_URL = 'https://iptv-org.github.io/api' TIMEOUT = 10 def __init__(self): self.session = requests.Session() self._cache = {} def fetch_endpoint(self, endpoint: str) -> List[Dict[str, Any]]: """Fetch a single endpoint""" if endpoint in self._cache: return self._cache[endpoint] url = f'{self.BASE_URL}/{endpoint}.json' response = self.session.get(url, timeout=self.TIMEOUT) response.raise_for_status() data = response.json() self._cache[endpoint] = data return data def get_channels(self) -> List[Dict]: return self.fetch_endpoint('channels') def get_streams(self) -> List[Dict]: return self.fetch_endpoint('streams') def get_countries(self) -> List[Dict]: return self.fetch_endpoint('countries') def find_channels_by_country(self, country_code: str) -> List[Dict]: """Find all channels in a country""" channels = self.get_channels() return [c for c in channels if c['country'] == country_code] def find_streams_for_channel(self, channel_id: str) -> List[Dict]: """Find all streams for a channel""" streams = self.get_streams() return [s for s in streams if s.get('channel') == channel_id] # Usage client = IPTVClient() us_channels = client.find_channels_by_country('US') for channel in us_channels: print(channel['name']) ``` -------------------------------- ### Timezone Specification Source: https://github.com/iptv-org/api/blob/master/_autodocs/data-specifications.md Details the structure for timezone data, including IANA timezone identifiers, current UTC offsets, and associated countries. Provides examples for IANA IDs and UTC offsets. ```APIDOC ## Timezone Specification **Endpoint:** `timezones.json` **Type:** `Timezone[]` **Array Element Schema:** | Field | Type | Required | Constraints | Example | Notes | |---|---|---|---|---|---| | id | string | Yes | IANA timezone format, 1-50 chars | "Europe/London" | Timezone identifier | | utc_offset | string | Yes | ±HH:MM format | "+00:00" | Current UTC offset | | countries | string[] | Yes | Array of 1-20 ISO 3166-1 codes | ["GB", "GG", "IM"] | Countries in timezone | **IANA Timezone Examples:** - "UTC" = Coordinated Universal Time - "Europe/London" = London/UK - "America/New_York" = Eastern Time (USA) - "America/Los_Angeles" = Pacific Time (USA) - "Asia/Tokyo" = Japan Standard Time - "Asia/Shanghai" = China Standard Time - "Australia/Sydney" = Australian Eastern Time - "Pacific/Auckland" = New Zealand Standard Time - "Africa/Cairo" = Egypt Standard Time - "Asia/Dubai" = Gulf Standard Time **UTC Offset Examples:** - "+00:00" = UTC - "+01:00" = UTC+1 (e.g., Europe/Paris) - "+05:30" = UTC+5:30 (e.g., Asia/Kolkata) - "-05:00" = UTC-5 (e.g., America/New_York) - "-08:00" = UTC-8 (e.g., America/Los_Angeles) - "+09:00" = UTC+9 (e.g., Asia/Tokyo) **Note on DST:** - `utc_offset` shows **current** offset (includes DST if applicable) - Offsets may vary seasonally - IANA IDs handle DST transitions automatically **Indexes:** - Primary: `id` (unique) - Foreign: `countries[]` → countries.code **Validation Rules:** - `id` must be valid IANA timezone - `utc_offset` must match ±HH:MM format - At least one country per timezone - Each country code must be valid ISO 3166-1 - Case-sensitive: "Europe/London" not "europe/london" **Min/Max Records:** 300-500 IANA timezones **Static Timezones:** The IANA timezone database rarely changes. ``` -------------------------------- ### Batch Load API Endpoints in Parallel Source: https://github.com/iptv-org/api/blob/master/_autodocs/integration-guide.md This JavaScript function demonstrates batch loading by fetching data from multiple API endpoints concurrently using `Promise.all`. It returns an object where keys are endpoint names and values are the fetched data. ```javascript async function loadAllData() { const endpoints = [ 'channels', 'feeds', 'streams', 'guides', 'logos', 'categories', 'countries', 'languages' ]; const baseUrl = 'https://iptv-org.github.io/api/'; // Load all in parallel const results = await Promise.all( endpoints.map(endpoint => fetch(`${baseUrl}${endpoint}.json`).then(r => r.json()) ) ); return Object.fromEntries(endpoints.map((ep, i) => [ep, results[i]])); } ``` -------------------------------- ### Load IPTV Channels into PostgreSQL Source: https://github.com/iptv-org/api/blob/master/_autodocs/integration-guide.md This Node.js script fetches channel data and loads it into a PostgreSQL database, creating the table if it doesn't exist and updating existing entries. ```javascript import { Pool } from 'pg'; const pool = new Pool({ connectionString: process.env.DATABASE_URL }); async function loadChannelsToPostgres() { const channels = await fetch('https://iptv-org.github.io/api/channels.json') .then(r => r.json()); // Create table await pool.query(` CREATE TABLE IF NOT EXISTS channels ( id TEXT PRIMARY KEY, name TEXT NOT NULL, country TEXT NOT NULL, categories TEXT[], is_nsfw BOOLEAN, website TEXT, launched DATE, closed DATE ) `); // Insert data for (const ch of channels) { await pool.query( 'INSERT INTO channels VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT(id) DO UPDATE SET name = $2', [ ch.id, ch.name, ch.country, ch.categories, ch.is_nsfw, ch.website, ch.launched, ch.closed ] ); } } ``` -------------------------------- ### Regions Endpoint Example Source: https://github.com/iptv-org/api/blob/master/_autodocs/endpoints.md Returns supranational geographic regions. The response includes a unique region code, region name, and an array of ISO 3166-1 alpha-2 country codes belonging to the region. ```json [ { "code": "MAGHREB", "name": "Maghreb", "countries": ["DZ", "LY", "MA", "MR", "TN"] } ] ``` -------------------------------- ### Display Channel List Source: https://github.com/iptv-org/api/blob/master/_autodocs/README.md Fetches all channels and logs their names and countries. Assumes the API returns a JSON array of channel objects. ```javascript const channels = await fetch('.../channels.json').then(r => r.json()); channels.forEach(c => console.log(`${c.name} (${c.country})`)); ``` -------------------------------- ### Perform Batch Lookups Source: https://github.com/iptv-org/api/blob/master/_autodocs/quick-start.md Efficiently look up multiple channel IDs at once by first fetching all channels and creating a map for quick lookups. This is useful for reducing the number of individual requests when you need information for several channels. ```javascript async function batchLookup(channelIds) { const channels = await fetch('...channels.json').then(r => r.json()); const map = new Map(channels.map(c => [c.id, c])); return channelIds.map(id => map.get(id)).filter(Boolean); } // Usage const found = await batchLookup(['BBCOne.uk', 'France2.fr', 'Unknown.xx']); ```