### POST /scrobble/start - Example (JavaScript) Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/scrobble.md JavaScript example for starting a watching session. ```javascript async function startWatching(token, itemInfo) { const response = await fetch( 'https://api.simkl.com/scrobble/start', { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', 'simkl-api-key': CLIENT_ID }, body: JSON.stringify({ show: itemInfo.show, season: itemInfo.season, episode: itemInfo.episode, progress: 0, metadata: { player: 'Web Player', device: 'Browser' } }) } ); const session = await response.json(); return session.id; // Save for later updates } // Usage const sessionId = await startWatching(token, { show: { ids: { simkl: 1 }, title: 'Breaking Bad', year: 2008 }, season: 1, episode: 5 }); ``` -------------------------------- ### Example: Get Full TV Show Information Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/content-discovery.md Example GET request to retrieve all available information for a TV show. ```http GET https://api.simkl.com/tv/17465?extended=full&client_id=*** ``` -------------------------------- ### Full Playback Session Workflow Example Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/scrobble.md JavaScript example illustrating the complete lifecycle of a playback session, from starting to watching, pausing, stopping, and resuming. ```javascript // 1. User starts watching episode const session = await startWatching(token, { show: { ids: { simkl: 1 }, title: 'Breaking Bad', year: 2008 }, season: 1, episode: 5 }); // 2. Track progress as video plays setInterval(async () => { const currentProgress = videoPlayer.currentTime / videoPlayer.duration * 100; if (currentProgress > 5) { // Ignore first 5% to avoid spam await pauseWatching(token, { show: { ids: { simkl: 1 } }, season: 1, episode: 5, progress: currentProgress }); } }, 30000); // Update every 30 seconds // 3. User stops playing videoPlayer.on('ended', async () => { const finalProgress = videoPlayer.currentTime / videoPlayer.duration * 100; await stopWatching(token, { show: { ids: { simkl: 1 } }, season: 1, episode: 5, progress: finalProgress }); // If >80%, will auto-mark as watched }); // 4. Or user explicitly pauses videoPlayer.on('pause', async () => { const progress = videoPlayer.currentTime / videoPlayer.duration * 100; await pauseWatching(token, {...}); }); // 5. User can resume later const sessions = await getPlaybackSessions(token, 'show'); if (sessions.length > 0) { const session = sessions[0]; videoPlayer.currentTime = session.progress / 100 * videoPlayer.duration; } ``` -------------------------------- ### Example for GET /tv/airing?{date}{?sort,client_id} Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/content-discovery.md JavaScript example demonstrating how to fetch TV shows airing today using the API. ```javascript // Get shows airing today const today = new Date().toISOString().split('T')[0]; // YYYY-MM-DD const response = await fetch( `https://api.simkl.com/tv/airing?date=${today}&client_id=${CLIENT_ID}` ); ``` -------------------------------- ### Scrobble Start Response Body Source: https://github.com/simkl/api/blob/master/_autodocs/endpoints.md Example JSON response body for starting a playback session. ```json { "id": "5e6d8a6c7b7b7b7b7b7b7b7b", "progress": 0, "expires_at": "2023-05-31T10:00:00Z" } ``` -------------------------------- ### Examples for GET /tv/premieres/{param} Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/content-discovery.md Examples of API requests to fetch latest TV show premieres, including options for country and show type. ```bash # Latest US premieres GET /tv/premieres/US?client_id=*** # Latest UK premieres (new shows only) GET /tv/premieres/GB?type=new&client_id=*** # All countries GET /tv/premieres/all?client_id=*** ``` -------------------------------- ### Example for GET /anime/{id} Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/content-discovery.md Example JSON response for retrieving detailed information about an anime, including anime-specific fields. ```json { "title": "Neon Genesis Evangelion", "year": 1995, "type": "anime", "anime_type": "tv", "ids": { "simkl": 5000, "slug": "neon-genesis-evangelion", "mal": 30, "anidb": 22, "anilist": 30 } } ``` -------------------------------- ### Scrobble Start Request Body Source: https://github.com/simkl/api/blob/master/_autodocs/endpoints.md Example JSON request body for starting a playback session. ```json { "show": { "title": "Breaking Bad", "ids": { "simkl": 1, "imdb": "tt0903747" } }, "season": 1, "episode": 1, "progress": 0 } ``` -------------------------------- ### Example: Get TV Show by Simkl ID Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/content-discovery.md Example GET request to retrieve a TV show using its Simkl ID. ```http GET https://api.simkl.com/tv/17465?client_id=*** ``` -------------------------------- ### Example: Get Specific TV Show Fields Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/content-discovery.md Example GET request to retrieve only specific fields for a TV show. ```http GET https://api.simkl.com/tv/17465?extended=title,slug,overview,genres&client_id=*** ``` -------------------------------- ### POST /scrobble/start - Handling Show vs Movie (Python) Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/scrobble.md Python example demonstrating how to handle starting sessions for shows versus movies. ```python def start_watching(token, item_type, item_data, progress=0): """Start watching show or movie""" if item_type == 'show': body = { 'show': { 'ids': item_data['ids'], 'title': item_data['title'], 'year': item_data['year'] }, 'season': item_data['season'], 'episode': item_data['episode'], 'progress': progress } elif item_type == 'movie': body = { 'movie': { 'ids': item_data['ids'], 'title': item_data['title'], 'year': item_data['year'] }, 'progress': progress } response = requests.post( 'https://api.simkl.com/scrobble/start', json=body, headers=get_auth_headers(token) ) return response.json() ``` -------------------------------- ### Pagination Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/search.md Example GET request demonstrating pagination parameters. ```http GET /search/show?q=office&page=2&limit=25&client_id=*** ``` -------------------------------- ### Pagination Parameter Example Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/content-discovery.md Example of using 'page' and 'limit' parameters in a GET request for pagination. ```http GET /tv/genres/drama/all/all/all/all/trending?page=2&limit=25&client_id=*** ``` -------------------------------- ### POST /users/settings Request Body Example Source: https://github.com/simkl/api/blob/master/_autodocs/endpoints.md Example JSON request body for getting or updating user account settings. ```json { "user": { "email": "user@example.com" }, "sharing": { "tv": true, "anime": true, "movies": false } } ``` -------------------------------- ### Example API Calls for Recently Watched Background Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/users.md Examples of GET requests to retrieve different types of background images for the last watched item. ```bash # Get last watched show poster GET /users/12345/recently-watched-background/12345?image=poster&client_id=*** # Get last watched item fanart GET /users/12345/recently-watched-background/12345?image=fanart&client_id=*** # Get last watched episode screenshot GET /users/12345/recently-watched-background/12345?image=episode&client_id=*** ``` -------------------------------- ### Media Server Plugin Integration Example Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/scrobble.md A Python class demonstrating how to integrate Simkl scrobbling into a media server plugin, handling playback start, update, and stop events. ```python class ScrobbleManager: def __init__(self, token, client_id): self.token = token self.client_id = client_id self.sessions = {} # Track local sessions self.update_interval = 30 # seconds def on_playback_start(self, item): """Called when media starts playing""" response = requests.post( 'https://api.simkl.com/scrobble/start', json={ item['type']: {'ids': {'simkl': item['id']}}, 'progress': 0 }, headers=self._headers() ) self.sessions[item['id']] = response.json()['id'] def on_playback_update(self, item, progress): """Called periodically during playback""" requests.post( 'https://api.simkl.com/scrobble/pause', json={ item['type']: {'ids': {'simkl': item['id']}}, 'progress': progress }, headers=self._headers() ) def on_playback_stop(self, item, progress): """Called when playback stops""" requests.post( 'https://api.simkl.com/scrobble/stop', json={ item['type']: {'ids': {'simkl': item['id']}}, 'progress': progress }, headers=self._headers() ) del self.sessions[item['id']] def _headers(self): return { 'Authorization': f'Bearer {self.token}', 'Content-Type': 'application/json', 'simkl-api-key': self.client_id } ``` -------------------------------- ### Pagination Query Parameters Source: https://github.com/simkl/api/blob/master/_autodocs/configuration.md Example of how to use pagination parameters in a GET request. ```bash GET /sync/all-items/show/watching?page=2&limit=50 ``` -------------------------------- ### Examples for GET /tv/genres/{genre}/{type}/{country}/{network}/{year}/{sort} Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/content-discovery.md Examples of API requests to fetch TV shows with different parameters like genre, type, country, network, year, and sorting. ```bash # All drama shows GET /tv/genres/drama/all/all/all/all/trending?client_id=*** # New comedy shows in US GET /tv/genres/comedy/new/US/all/all/newest?client_id=*** # Top rated shows on HBO from 2020 GET /tv/genres/all/all/US/HBO/2020/rating?client_id=*** # Page through results GET /tv/genres/drama/all/all/all/all/trending?page=2&limit=25&client_id=*** ``` -------------------------------- ### Web Player Integration Example Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/scrobble.md A JavaScript class demonstrating how to integrate Simkl scrobbling into a web player, handling playback start and progress updates. ```javascript class WebScrobbler { constructor(token, clientId) { this.token = token; this.clientId = clientId; this.sessionId = null; this.lastUpdate = 0; } async startWatching(show, season, episode) { const response = await fetch( 'https://api.simkl.com/scrobble/start', { method: 'POST', headers: this._headers(), body: JSON.stringify({ show, season, episode, progress: 0 }) } ); const data = await response.json(); this.sessionId = data.id; } setupProgressTracking(videoElement) { setInterval(() => { const progress = (videoElement.currentTime / videoElement.duration) * 100; const now = Date.now(); // Update every 30 seconds if (now - this.lastUpdate > 30000) { this._updateProgress(progress); this.lastUpdate = now; } }, 1000); } async _updateProgress(progress) { await fetch('https://api.simkl.com/scrobble/pause', { method: 'POST', headers: this._headers(), body: JSON.stringify({ progress }) }); } _headers() { return { 'Authorization': `Bearer ${this.token}`, 'Content-Type': 'application/json', 'simkl-api-key': this.clientId }; } } ``` -------------------------------- ### POST /scrobble/start - Response (201 Created) Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/scrobble.md Example JSON response for a successful start session request. ```json { "id": "5e6d8a6c7b7b7b7b7b7b7b7b", "progress": 0, "expires_at": "2023-06-07T10:00:00Z" } ``` -------------------------------- ### Get or update user account settings Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/users.md Example of how to get and update user settings using Python. ```Python def get_user_settings(token): """Get user account settings""" response = requests.post( 'https://api.simkl.com/users/settings', headers=get_auth_headers(token) ) return response.json() def update_user_settings(token, settings): """Update user settings""" response = requests.post( 'https://api.simkl.com/users/settings', json=settings, headers=get_auth_headers(token) ) return response.json() # Update bio settings = get_user_settings(token) settings['user']['bio'] = 'New bio text' updated = update_user_settings(token, settings) ``` ```Python def update_bio(token, new_bio): """Update user bio""" update_user_settings(token, { 'user': {'bio': new_bio} }) def update_language(token, language_code): """Update language preference""" update_user_settings(token, { 'user': {'language': language_code} }) def disable_movie_sharing(token): """Hide movies from public profile""" update_user_settings(token, { 'sharing': {'movies': False} }) def enable_email_notifications(token): """Turn on email notifications""" update_user_settings(token, { 'notifications': {'email': True} }) ``` -------------------------------- ### POST /scrobble/start - Request Body (Show) Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/scrobble.md Example JSON request body for starting a show playback session. ```json { "show": { "title": "Breaking Bad", "year": 2008, "ids": {"simkl": 1} }, "season": 1, "episode": 5, "progress": 0 } ``` -------------------------------- ### Example: Get TV Show by IMDB ID Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/content-discovery.md Example GET request to retrieve a TV show using its IMDB ID. ```http GET https://api.simkl.com/tv/tt0944947?client_id=*** ``` -------------------------------- ### Get rating information for an item by ID. Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/ratings.md Examples for GET /ratings. ```bash # Get all ratings for show ID 1 GET /ratings?simkl=1&client_id=*** # Get specific fields only GET /ratings?simkl=1&fields=simkl,imdb,tmdb&client_id=*** # For anime GET /ratings?simkl=5000&fields=simkl,mal,anilist&client_id=*** ``` -------------------------------- ### Extended Information Example Source: https://github.com/simkl/api/blob/master/_autodocs/configuration.md Example GET request using the 'extended' parameter to retrieve full information for a TV show. ```bash GET /tv/17465?extended=full&client_id=*** ``` -------------------------------- ### First Request Examples Source: https://github.com/simkl/api/blob/master/_autodocs/README.md Examples of making API requests, one without authentication and one requiring authentication. ```bash # Get TV show details (no auth required) curl -X GET "https://api.simkl.com/tv/1?client_id=YOUR_CLIENT_ID" \ -H "Content-Type: application/json" # Get user's watched items (auth required) curl -X GET "https://api.simkl.com/sync/all-items/show/watching" \ -H "Content-Type: application/json" \ -H "simkl-api-key: YOUR_CLIENT_ID" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` -------------------------------- ### Image Proxy Examples Source: https://github.com/simkl/api/blob/master/_autodocs/configuration.md Examples of using the wsrv.nl proxy for different image types. ```bash Poster: https://wsrv.nl/?url=https://simkl.in/posters/74/74415673dcdc9cdd_w.webp Fanart: https://wsrv.nl/?url=https://simkl.in/fanart/74/74415673dcdc9cdd_w.webp Episode: https://wsrv.nl/?url=https://simkl.in/episodes/74/74415673dcdc9cdd.jpg Avatar: https://wsrv.nl/?url=https://simkl.in/avatars/u/username.jpg ``` -------------------------------- ### GET /tv/{id} Example Source: https://github.com/simkl/api/blob/master/_autodocs/endpoints.md Get detailed information about a TV show. ```json { "title": "Game of Thrones", "year": 2011, "type": "show", "ids": { "simkl": 17465, "slug": "game-of-thrones", "tvdb": "121361", "imdb": "tt0944947" }, "rank": 6, "poster": "57/5742576cd8f59fcb0", "fanart": "65/651708e80d87bb93", "first_aired": "2011-04-18T01:00:00Z", "runtime": 55, "certification": "TV-MA", "overview": "Seven noble families...", "genres": ["Drama", "Fantasy", "Adventure"], "country": "US", "total_episodes": 67, "status": "ended", "network": "HBO", "ratings": { "simkl": {"rating": 9.1, "votes": 1270}, "imdb": {"rating": 9.5, "votes": 1234933} } } ``` -------------------------------- ### Get In Progress Python Example Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/sync.md Python function to retrieve all shows a user is currently watching. ```python def get_in_progress(token): """Get all shows user is currently watching""" response = requests.get( 'https://api.simkl.com/sync/playback/show', headers=get_auth_headers(token) ) return response.json() sessions = get_in_progress(token) for session in sessions: print(f"{session['show']['title']} S{session['season']}E{session['episode']}") print(f" Progress: {session['progress']}%") ``` -------------------------------- ### POST /scrobble/pause - Example (Python) Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/scrobble.md Python example for pausing a watching session. ```python def pause_watching(token, show_id, season, episode, progress): """Pause current playback""" response = requests.post( 'https://api.simkl.com/scrobble/pause', json={ 'show': {'ids': {'simkl': show_id}}, 'season': season, 'episode': episode, 'progress': progress }, headers=get_auth_headers(token) ) return response.json() ``` -------------------------------- ### Attribution Link Example Source: https://github.com/simkl/api/blob/master/_autodocs/configuration.md HTML examples for displaying Simkl attribution links. ```html Powered by Simkl Breaking Bad on Simkl ``` -------------------------------- ### PIN Flow - Step 1: Get device code Source: https://github.com/simkl/api/blob/master/_autodocs/configuration.md Example GET request to obtain a device code for PIN-based authentication. ```http GET https://api.simkl.com/oauth/pin?client_id={client_id} ``` -------------------------------- ### POST /scrobble/start - Request Body (Movie) Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/scrobble.md Example JSON request body for starting a movie playback session. ```json { "movie": { "title": "Inception", "year": 2010, "ids": {"simkl": 100} }, "progress": 0 } ``` -------------------------------- ### GET /sync/activities Response (200 OK) Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/sync.md Example JSON response for the GET /sync/activities endpoint, showing last activity timestamps for various media types. ```json { "all": "2023-05-31T10:00:00Z", "shows": { "last_watch_at": "2023-05-31T09:00:00Z", "last_updated_at": "2023-05-31T09:00:00Z" }, "movies": { "last_watch_at": "2023-05-31T08:00:00Z", "last_updated_at": "2023-05-31T08:00:00Z" }, "anime": { "last_watch_at": "2023-05-31T07:00:00Z", "last_updated_at": "2023-05-31T07:00:00Z" }, "lists": "2023-05-30T15:00:00Z", "ratings": "2023-05-30T14:00:00Z" } ``` -------------------------------- ### Error Handling Example Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/authentication.md An example function demonstrating how to handle authentication errors, including state mismatch and invalid codes. ```javascript async function authenticateUser(code, state) { try { // Verify state if (state !== sessionStorage.getItem('oauth_state')) { throw new Error('State mismatch - possible CSRF attack'); } const token = await exchangeCode(code); saveToken(token); return token; } catch (error) { if (error.message.includes('grant_error')) { console.error('Invalid code, user must re-authorize'); redirectToAuth(); } else { console.error('Authentication failed:', error); showError('Authentication failed. Please try again.'); } throw error; } } ``` -------------------------------- ### Get Top Rated Python Example Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/sync.md Python function to retrieve all items rated 10/10. ```python def get_top_rated(token, rating=10): """Get all items rated 10/10""" response = requests.post( f'https://api.simkl.com/sync/ratings/show/{rating}', headers=get_auth_headers(token) ) return response.json() # Get perfect scores perfect_shows = get_top_rated(token, rating=10) ``` -------------------------------- ### PIN Flow - Get Device Code Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/authentication.md JavaScript example to initiate the PIN authentication flow by requesting a device code and user code from the API. ```javascript // Step 1: Get device code const getDeviceCode = async (clientId) => { const response = await fetch( `https://api.simkl.com/oauth/pin?client_id=${clientId}` ); return response.json(); }; // Step 2: Display to user const { user_code, verification_url, expires_in, interval, device_code } = await getDeviceCode('YOUR_CLIENT_ID'); console.log(`Enter this code on your device: ${user_code}`); console.log(`Visit: ${verification_url}`); console.log(`Code expires in ${expires_in} seconds`); // Step 3: Begin polling (see next endpoint) ``` -------------------------------- ### Example Headers Source: https://github.com/simkl/api/blob/master/_autodocs/configuration.md Example of required and conditional headers for API requests. ```http GET /sync/all-items/show/watching HTTP/1.1 Host: api.simkl.com Content-Type: application/json simkl-api-key: c7be48f1559a6d794w1925237c626326c7bsdfsa559a6d794w1925137c626352 Authorization: Bearer b5be48f1529a2d794f1925237c626326c7dddfsa559a6d794w1925137c622329 ``` -------------------------------- ### PIN Flow - Step 1: Get device code response Source: https://github.com/simkl/api/blob/master/_autodocs/configuration.md Example response containing the device code and verification URL. ```json { "user_code": "ABC12", "verification_url": "https://simkl.com/pin/", "expires_in": 3600, "interval": 3 } ``` -------------------------------- ### Image URL Example Source: https://github.com/simkl/api/blob/master/_autodocs/endpoints.md An example of a constructed image URL. ```text https://wsrv.nl/?url=https://simkl.in/posters/74/74415673dcdc9cdd_w.webp ``` -------------------------------- ### Example Polling Loop Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/authentication.md A JavaScript example demonstrating how to poll for authorization status, including handling success, errors, and timeouts. ```javascript const pollForAuthorization = async (userCode, clientId, interval, expiresIn) => { const startTime = Date.now(); const expirationTime = startTime + (expiresIn * 1000); while (Date.now() < expirationTime) { try { const response = await fetch( `https://api.simkl.com/oauth/pin/${userCode}?client_id=${clientId}` ); const data = await response.json(); if (response.status === 200 && data.access_token) { // SUCCESS - User authorized console.log('Authorization successful!'); return data.access_token; } if (data.error === 'access_denied') { throw new Error('User denied authorization'); } if (data.error === 'expired_code') { throw new Error('Code expired, request new one'); } // authorization_pending - keep polling console.log(`Waiting ${interval}s before next poll...`); await sleep(interval * 1000); } catch (error) { console.error('Poll failed:', error); throw error; } } throw new Error('Authorization timeout'); }; async function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // Usage const pinData = await fetch(`https://api.simkl.com/oauth/pin?client_id=${clientId}`) .then(r => r.json()); try { const token = await pollForAuthorization( pinData.user_code, clientId, pinData.interval, pinData.expires_in ); console.log('Access token:', token); } catch (error) { console.error(error); } ``` -------------------------------- ### Exponential Backoff Example Source: https://github.com/simkl/api/blob/master/_autodocs/configuration.md Python example demonstrating exponential backoff for handling rate limit responses. ```python import time def api_request_with_retry(url, max_retries=5): for attempt in range(max_retries): response = requests.get(url, headers=headers) if response.status_code == 429: wait_time = 2 ** attempt # 1, 2, 4, 8, 16 seconds print(f"Rate limited, waiting {wait_time}s") time.sleep(wait_time) continue return response raise Exception("Max retries exceeded") ``` -------------------------------- ### Get Active Playback Sessions Response (200 OK) Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/sync.md Example response for active playback sessions. ```json [ { "id": "5e6d8a6c7b7b7b7b7b7b7b7b", "show": { "title": "Breaking Bad", "ids": {"simkl": 1} }, "season": 1, "episode": 5, "progress": 45, "paused_at": "2023-05-31T10:00:00Z" } ] ``` -------------------------------- ### Check-in Example Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/scrobble.md TypeScript example for checking into an item (like a social media post) with an optional message. This creates an activity entry. ```typescript async function checkin( token: string, item: { type: 'show' | 'movie', id: number }, message?: string ) { const body: any = { [item.type]: { ids: { simkl: item.id } }, progress: 50 }; if (message) body.message = message; const response = await fetch( 'https://api.simkl.com/scrobble/checkin', { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', 'simkl-api-key': CLIENT_ID }, body: JSON.stringify(body) } ); return response.json(); } // Usage checkin(token, { type: 'show', id: 1 }, 'This show is amazing!'); ``` -------------------------------- ### Authentication Header Example Source: https://github.com/simkl/api/blob/master/_autodocs/endpoints.md Example of how to include the Authorization header with a bearer token for authenticated requests. ```http Authorization: Bearer {access_token} ``` -------------------------------- ### Add or update ratings for items (Python Example) Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/sync.md Example of how to rate a show using the `/sync/ratings` endpoint. ```python def rate_show(token, show_id, rating): """Rate a show (1-10)""" assert 1 <= rating <= 10 response = requests.post( 'https://api.simkl.com/sync/ratings', json={ 'shows': [{ 'ids': {'simkl': show_id}, 'rating': rating }] }, headers=get_auth_headers(token) ) return response.json() ``` -------------------------------- ### cURL - Get TV show details Source: https://github.com/simkl/api/blob/master/_autodocs/configuration.md Example cURL command to fetch details of a specific TV show. ```bash # Get TV show details curl -X GET "https://api.simkl.com/tv/17465?client_id=YOUR_CLIENT_ID" \ -H "Content-Type: application/json" ``` -------------------------------- ### Details Response Example Source: https://github.com/simkl/api/blob/master/_autodocs/types.md Example of a details response. ```json { "title": "Breaking Bad", "year": 2008, "type": "show", "ids": {...} } ``` -------------------------------- ### Sync Request Objects - Minimal Example Source: https://github.com/simkl/api/blob/master/_autodocs/types.md Minimal Example for Sync Request Objects. ```json { "shows": [ { "title": "Breaking Bad", "year": 2008, "ids": {"simkl": 1}, "seasons": [ { "number": 1, "episodes": [ {"number": 1}, {"number": 2} ] } ] } ] } ``` -------------------------------- ### Simkl API Key Header Example Source: https://github.com/simkl/api/blob/master/_autodocs/endpoints.md Example of how to include the simkl-api-key header required for all requests. ```http simkl-api-key: {client_id} ``` -------------------------------- ### Fanart Image Example Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/content-discovery.md Example of a full URL for movie fanart. ```http https://wsrv.nl/?url=https://simkl.in/fanart/65/651708e80d87bb93_w.webp ``` -------------------------------- ### User Privacy Settings Example Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/users.md An example JSON object illustrating user settings for privacy and sharing preferences. ```json { "sharing": { "tv": false, // Hide TV watch history "movies": false, // Hide movie watch history "anime": false // Hide anime watch history }, "privacy": { "show_ratings": false, // Hide ratings from profile "show_stats": false, // Hide statistics "allow_messages": false // Disable direct messages } } ``` -------------------------------- ### Response (200 OK) for GET /tv/airing?{date}{?sort,client_id} Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/content-discovery.md Example JSON response for a successful request to retrieve TV shows currently airing on a specific date. ```json [ { "title": "The Office", "year": 2005, "type": "show", "ids": { "simkl": 2, "slug": "the-office", "tvdb": "84912", "imdb": "tt0386676" } } ] ``` -------------------------------- ### Poster Image Example Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/content-discovery.md Example of a full URL for a movie poster. ```http https://wsrv.nl/?url=https://simkl.in/posters/57/5742576cd8f59fcb0_w.webp ``` -------------------------------- ### GET /tv/episodes/{id} Example Source: https://github.com/simkl/api/blob/master/_autodocs/endpoints.md Get all episodes of a TV show. ```json [ { "season": 1, "episode": 1, "title": "Pilot", "ids": { "simkl": 1, "tvdb": "349232", "imdb": "tt0959621" }, "number": 1, "year": 2008, "aired": "2008-01-20", "rating": 9.2, "votes": 2340, "overview": "A high school chemistry teacher..." } ] ``` -------------------------------- ### Add items to watched/watching history (JavaScript Example) Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/sync.md Example of how to mark shows, movies, and anime as watched using the `/sync/history` endpoint. ```javascript async function markAsWatched(token, items) { const response = await fetch( 'https://api.simkl.com/sync/history', { method: 'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', 'simkl-api-key': CLIENT_ID }, body: JSON.stringify(items) } ); return response.json(); } // Mark show episodes as watched markAsWatched(token, { shows: [{ ids: { simkl: 1 }, seasons: [{ number: 1, episodes: [{ number: 1 }, { number: 2 }] }] }] }); // Mark movie as watched markAsWatched(token, { movies: [{ ids: { simkl: 100 } }] }); ``` -------------------------------- ### Get rating information for an item by ID. Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/ratings.md Example in Python for GET /ratings. ```python def display_ratings(item_id): """Display all available ratings""" response = requests.get( 'https://api.simkl.com/ratings', params={ 'simkl': item_id, 'client_id': CLIENT_ID } ) ratings = response.json() print(f"Simkl: {ratings['simkl']}/10 ({ratings['simkl_votes']} votes)") print(f"IMDB: {ratings['imdb']}/10 ({ratings['imdb_votes']} votes)") if 'mal' in ratings: print(f"MAL: {ratings['mal']}/10 ({ratings['mal_votes']} votes)") ``` -------------------------------- ### Get rating information for an item by ID. Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/ratings.md Example in JavaScript for GET /ratings. ```javascript async function getItemRatings(itemId) { const response = await fetch( `https://api.simkl.com/ratings?simkl=${itemId}&client_id=${CLIENT_ID}` ); const ratings = await response.json(); return { simkl: ratings.simkl, imdb: ratings.imdb, averageRating: (ratings.simkl + ratings.imdb) / 2 }; } // Usage const ratings = await getItemRatings(1); console.log(`Simkl: ${ratings.simkl}★, IMDB: ${ratings.imdb}★`); ``` -------------------------------- ### POST /users/{user_id}/stats Response Example Source: https://github.com/simkl/api/blob/master/_autodocs/endpoints.md Example JSON response for user watch statistics. ```json { "shows": { "watched": 150, "completed": 45, "episodes_watched": 1250 }, "movies": { "watched": 320 }, "anime": { "watched": 75, "episodes_watched": 1840 } } ``` -------------------------------- ### Get rating information for an item by ID. Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/ratings.md Example JSON response for GET /ratings. ```json { "simkl": 9.1, "simkl_votes": 1270, "imdb": 9.5, "imdb_votes": 1234933, "tmdb": 8.8, "tmdb_votes": 5432, "anilist": 87, "anilist_votes": 45000, "anidb": 7.8, "mal": 8.9, "mal_votes": 150000 } ``` -------------------------------- ### Get ratings for all items in user's watchlist with specific status. Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/ratings.md Example in Python for GET /ratings/{type}. ```python def get_user_ratings_for_status(status='completed'): """Get all rated items with specific watchlist status""" items = [] page = 1 while True: response = requests.get( f'https://api.simkl.com/ratings/show', params={ 'user_watchlist': status, 'page': page, 'limit': 50, 'client_id': CLIENT_ID } ) data = response.json() if not data: break items.extend(data) page += 1 return items # Get all completed shows I've rated completed_shows = get_user_ratings_for_status('completed') for show in completed_shows: print(f"{show['show']['title']}: {show['rating']}/10") ``` -------------------------------- ### Storing the Access Token Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/authentication.md Examples of how to store the obtained access token using different approaches: database, session, and file. ```python # Database approach (recommended for web apps) user.access_token = token # Store in encrypted field db.session.commit() # Session approach (for stateless servers) session['simkl_token'] = token # Encrypted by web framework # File approach (for CLI/scripts) config = {'token': token} with open('~/.simkl/config', 'w') as f: json.dump(config, f) os.chmod('~/.simkl/config', 0o600) # Restrict permissions ``` -------------------------------- ### Get ratings for all items in user's watchlist with specific status. Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/ratings.md Example JSON response for GET /ratings/{type}. ```json [ { "type": "show", "show": { "title": "Breaking Bad", "year": 2008, "ids": { "simkl": 1, "slug": "breaking-bad", "tvdb": "81189", "imdb": "tt0903747" } }, "rating": 9, "rated_at": "2023-05-31T10:00:00Z", "ratings": { "simkl": 9.1, "imdb": 9.5 } } ] ``` -------------------------------- ### POST /scrobble/start - Metadata Object Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/scrobble.md Example JSON object for additional metadata. ```json { "media_type": "show", "player": "Plex", "device": "Samsung TV", "client_version": "1.0.0" } ``` -------------------------------- ### Example Movie Genre Filter Request Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/content-discovery.md Example of a GET request to filter movies by genre, country, year, and sort order. ```http GET /movies/thriller/all/US/2023/rating?client_id=*** ``` -------------------------------- ### Example (Python) Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/sync.md Python function to retrieve all shows of a specific status from the user's watchlist, handling pagination. ```python def get_user_shows(token, status='watching'): """Get all shows with specific status""" items = [] page = 1 while True: response = requests.get( f'https://api.simkl.com/sync/all-items/show/{status}', params={'page': page, 'limit': 50}, headers=get_auth_headers(token) ) data = response.json() if not data: break items.extend(data) page += 1 return items # Usage watching = get_user_shows(token, 'watching') completed = get_user_shows(token, 'completed') planning = get_user_shows(token, 'planning') ``` -------------------------------- ### GET /sync/all-items/{type}/{status} Response (200 OK) Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/sync.md Example JSON response for the GET /sync/all-items endpoint, showing a show with its status and watch details. ```json [ { "type": "show", "show": { "title": "Breaking Bad", "year": 2008, "ids": { "simkl": 1, "slug": "breaking-bad", "tvdb": "81189", "imdb": "tt0903747" } }, "seasons": [ { "number": 1, "episodes": [ { "number": 1, "watched_at": "2023-05-31T09:00:00Z" } ] } ], "status": "watching", "last_watched_at": "2023-05-31T09:00:00Z" } ] ``` -------------------------------- ### Update Frequency Example Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/scrobble.md Demonstrates how to update playback progress at reasonable intervals to avoid API spam. ```python # DON'T - updates too frequently while playing: update_progress() # Every millisecond - API spam! # DO - update at reasonable intervals last_update = time.time() while playing: if time.time() - last_update > 30: # Every 30 seconds update_progress() last_update = time.time() ``` -------------------------------- ### OAuth 2.0 Step 1: Redirect User to Authorization Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/authentication.md JavaScript example for initiating the OAuth 2.0 authorization flow by redirecting the user. ```javascript // Step 1: Redirect user to authorization const authUrl = new URL('https://simkl.com/oauth/authorize'); authUrl.searchParams.set('response_type', 'code'); authUrl.searchParams.set('client_id', 'your-client-id'); authUrl.searchParams.set('redirect_uri', 'https://yourapp.com/oauth/callback'); authUrl.searchParams.set('state', generateRandomState()); window.location.href = authUrl.toString(); // Step 2: In your callback endpoint, exchange code for token // See POST /oauth/token below ``` -------------------------------- ### Search anime Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/search.md Example GET request to search for anime by title. ```http GET /search/anime?q=evangelion&client_id=*** ``` -------------------------------- ### Search movies Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/search.md Example GET request to search for movies by title. ```http GET /search/movie?q=inception&client_id=*** ``` -------------------------------- ### By TVDB ID Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/search.md Example GET request to search by TVDB ID. ```http GET /search/id?tvdb=81189&client_id=*** ``` -------------------------------- ### By IMDB ID Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/search.md Example GET request to search by IMDB ID. ```http GET /search/id?imdb=tt0903747&client_id=*** ``` -------------------------------- ### Get Movie Details Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/content-discovery.md Example JSON response for a movie details request. ```json { "title": "Inception", "year": 2010, "type": "movie", "ids": { "simkl": 100, "slug": "inception", "imdb": "tt1375666", "tmdb": 27205 }, "rank": 20, "poster": "10/101205673dcdc9cdd", "fanart": "20/201205673dcdc9cdd", "released": "2010-07-16T00:00:00Z", "runtime": 148, "overview": "A skilled thief who steals corporate secrets...", "genres": ["Action", "Adventure", "Sci-Fi"], "country": "US", "certification": "PG-13", "ratings": { "simkl": { "rating": 8.7, "votes": 1200 }, "imdb": { "rating": 8.8, "votes": 2500000 } } } ``` -------------------------------- ### OAuth 2.0 - Step 2: Receive authorization code Source: https://github.com/simkl/api/blob/master/_autodocs/configuration.md Example of the redirect URI with the authorization code. ```url {redirect_uri}?code=d7be48f1559a...&state={state} ``` -------------------------------- ### Search TV shows Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/search.md Example GET request to search for TV shows by title. ```http GET /search/show?q=breaking%20bad&client_id=*** ``` -------------------------------- ### Handle Network Failures Example Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/scrobble.md Shows how to implement retries with exponential backoff for network requests and save progress locally on failure. ```python def safe_update_progress(token, progress): """Update with retry on failure""" max_retries = 3 for attempt in range(max_retries): try: response = requests.post( 'https://api.simkl.com/scrobble/pause', json=progress_data, headers=get_auth_headers(token), timeout=5 ) return response.json() except (ConnectionError, Timeout): if attempt < max_retries - 1: time.sleep(2 ** attempt) # Exponential backoff continue # Save locally and retry next session save_pending_progress(progress_data) raise ``` -------------------------------- ### By MyAnimeList ID (anime) Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/search.md Example GET request to search by MyAnimeList ID for an anime. ```http GET /search/id?mal=5&client_id=*** ``` -------------------------------- ### OAuth 2.0 - Step 1: Redirect to authorization Source: https://github.com/simkl/api/blob/master/_autodocs/configuration.md Example URL to redirect users for OAuth 2.0 authorization. ```url https://simkl.com/oauth/authorize?response_type=code&client_id={client_id}&redirect_uri={redirect_uri} ``` -------------------------------- ### By TMDB ID (movie) Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/search.md Example GET request to search by TMDB ID for a movie. ```http GET /search/id?tmdb=15172&client_id=*** ``` -------------------------------- ### PIN Flow - Step 3: Receive token Source: https://github.com/simkl/api/blob/master/_autodocs/configuration.md Example response containing the access token after user authorization. ```json { "access_token": "b5be48f1529a2d794f1925237c626326c7dddfsa559a6d794w1925137c622329", "token_type": "bearer", "expires_in": 3600 } ``` -------------------------------- ### Get User Ratings Response (200 OK) Source: https://github.com/simkl/api/blob/master/_autodocs/api-reference/sync.md Example response for user ratings of a specific value. ```json [ { "type": "show", "show": { "title": "Breaking Bad", "year": 2008, "ids": {"simkl": 1} }, "rating": 10, "rated_at": "2023-05-31T10:00:00Z" } ] ```