### Install Go SDK for Sports Odds API Source: https://sportsgameodds.com/docs/basics/setup.mdx Install the official Go SDK using the go get command. This command fetches and installs the SDK for use in your Go projects. ```bash go get github.com/SportsGameOdds/sports-odds-api-go ``` -------------------------------- ### Setup Project with npm Source: https://sportsgameodds.com/docs/examples/live-odds-tracker.mdx Initializes a new Node.js project and installs the necessary `node-fetch` library. Use `node-fetch@2` for CommonJS compatibility. ```bash mkdir odds-tracker && cd odds-tracker npm init -y npm install node-fetch@2 ``` -------------------------------- ### Setup Project for Arbitrage Calculator Source: https://sportsgameodds.com/docs/examples/arbitrage-calculator.mdx Sets up a new project directory, creates a virtual environment, and installs the 'requests' library. Activate the virtual environment before running the script. ```bash mkdir arb-calculator && cd arb-calculator python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install requests ``` -------------------------------- ### Setup Project for Player Props Analyzer Source: https://sportsgameodds.com/docs/examples/player-props-analyzer.mdx Sets up the project directory, creates a virtual environment, and installs the necessary 'requests' library. Activate the virtual environment before running the script. ```bash mkdir props-analyzer && cd props-analyzer python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install requests ``` -------------------------------- ### Setup Project for Parlay Calculator Source: https://sportsgameodds.com/docs/examples/parlay-builder.mdx Sets up a new Node.js project and installs the necessary dependency for making HTTP requests. Ensure you are using Node.js 18+ and have a SportsGameOdds API key. ```bash mkdir parlay-calculator && cd parlay-calculator npm init -y npm install node-fetch@2 ``` -------------------------------- ### Example API Request URL Source: https://sportsgameodds.com/docs/basics/cheat-sheet.mdx This example demonstrates a request to the /events endpoint with specific filters for league, odds availability, and a limit of one result. Replace 'YOUR_API_KEY' with your actual key. ```url https://api.sportsgameodds.com/v2/events?leagueID=NBA,NFL,MLB&oddsAvailable=true&limit=1&apiKey=YOUR_API_KEY ``` -------------------------------- ### Fetching Sports Data (HTTP) Source: https://sportsgameodds.com/docs/basics/setup.mdx This example demonstrates how to fetch a list of available sports using an API key via an HTTP GET request. ```APIDOC ## GET /v2/sports/ ### Description Fetches a list of available sports. ### Method GET ### Endpoint https://api.sportsgameodds.com/v2/sports/ ### Parameters #### Headers - **X-Api-Key** (string) - Required - Your API key for authentication. ### Request Example ```bash curl -X GET \ 'https://api.sportsgameodds.com/v2/sports/' \ -H 'X-Api-Key: YOUR_API_KEY' ``` ### Response #### Success Response (200) - **data** (array) - A list of sports objects. ### Response Example ```json { "data": [ { "id": "1", "name": "American Football" }, { "id": "2", "name": "Basketball" } ] } ``` ``` -------------------------------- ### Fetching Sports Data (SDK - Go) Source: https://sportsgameodds.com/docs/basics/setup.mdx This example shows how to fetch sports data using the Go SDK. ```APIDOC ## Fetch Sports Data (Go SDK) ### Description Uses the sports-odds-api-go SDK to fetch a list of available sports. ### Method SDK Method ### Endpoint N/A (SDK abstraction) ### Parameters #### Constructor Options - **option.WithAPIKeyParam("YOUR_API_KEY")**: Your API key for authentication. #### Method Parameters - **client.Sports.Get(ctx)**: Requires a context. ### Request Example ```go package main import ( "context" "fmt" sportsoddsapi "github.com/SportsGameOdds/sports-odds-api-go" "github.com/SportsGameOdds/sports-odds-api-go/option" ) func main() { client := sportsoddsapi.NewClient( option.WithAPIKeyParam("YOUR_API_KEY"), ) ctx := context.Background() sports, _ := client.Sports.Get(ctx) fmt.Println(sports.Data) } ``` ### Response #### Success Response - **Data** (interface{}) - Contains a list of sports objects. ### Response Example ```json [ { "id": "1", "name": "American Football" }, { "id": "2", "name": "Basketball" } ] ``` ``` -------------------------------- ### Make GET Request with Python Requests Source: https://sportsgameodds.com/docs/basics/setup.mdx This Python example shows how to fetch data from the sports endpoint using the 'requests' library. The API key should be passed in the 'X-Api-Key' header. ```python import requests headers = { 'X-Api-Key': 'YOUR_API_KEY' } url = 'https://api.sportsgameodds.com/v2/sports/' response = requests.get(url, headers=headers) print(response.json()) ``` -------------------------------- ### Make GET Request with Java HTTPClient Source: https://sportsgameodds.com/docs/basics/setup.mdx This Java example shows how to make a GET request to the sports endpoint using HttpClient. The API key should be included in the 'X-Api-Key' header. ```java import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class SportsGameOddsClient { public static void main(String[] args) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.sportsgameodds.com/v2/sports/")) .header("X-Api-Key", "YOUR_API_KEY") .GET() .build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); } } ``` -------------------------------- ### Make GET Request with Ruby Net::HTTP Source: https://sportsgameodds.com/docs/basics/setup.mdx This Ruby example uses the 'net/http' library to make a GET request to the sports endpoint. Include your API key in the 'X-Api-Key' header. ```ruby require 'net/http' require 'json' uri = URI('https://api.sportsgameodds.com/v2/sports/') request = Net::HTTP::Get.new(uri) request['X-Api-Key'] = 'YOUR_API_KEY' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end parsed_response = JSON.parse(response.body) puts parsed_response ``` -------------------------------- ### Install MCP Server for Sports Game Odds Source: https://sportsgameodds.com/docs/info/ai-vibe-coding.mdx Use this command to install the sports-odds-api-mcp package and configure it with your API key. Ensure you replace 'your-api-key-here' with your actual key. ```bash code --add-mcp '{"name":"sports-game-odds","command":"npx","args":["-y","sports-odds-api-mcp@latest"],"env":{"SPORTS_ODDS_API_KEY_HEADER":"your-api-key-here"}}' ``` ```json { "name": "sports-game-odds", "command": "npx", "args": ["-y", "sports-odds-api-mcp@latest"], "env": { "SPORTS_ODDS_API_KEY_HEADER": "your-api-key-here" } } ``` -------------------------------- ### Make GET Request with Javascript Fetch Source: https://sportsgameodds.com/docs/basics/setup.mdx This example demonstrates how to make a GET request to the sports endpoint using the Fetch API in Javascript. Ensure your API key is included in the 'X-Api-Key' header. ```javascript fetch("https://api.sportsgameodds.com/v2/sports/",{method: "GET",headers: { "X-Api-Key": "YOUR_API_KEY" },}) .then((response) => response.json()) .then((data) => console.log(data)) .catch((error) => console.error(error)); ``` -------------------------------- ### Make GET Request with PHP cURL Source: https://sportsgameodds.com/docs/basics/setup.mdx This PHP example demonstrates making a GET request to the sports endpoint using cURL. Ensure your API key is set in the 'X-Api-Key' header. ```php ``` -------------------------------- ### Install Ruby SDK for Sports Odds API Source: https://sportsgameodds.com/docs/basics/setup.mdx Install the official Ruby SDK using the gem command. This is necessary to integrate the SDK into your Ruby applications. ```bash gem install sports-odds-api ``` -------------------------------- ### Install JavaScript SDK for Sports Odds API Source: https://sportsgameodds.com/docs/basics/setup.mdx Install the official JavaScript SDK using npm, yarn, or pnpm. This is the first step to using the SDK in your project. ```bash npm install sports-odds-api # [!code focus] yarn add sports-odds-api # if you're using yarn pnpm add sports-odds-api # if you're using pnpm ``` -------------------------------- ### Start Live Odds Tracking Source: https://sportsgameodds.com/docs/examples/live-odds-tracker.mdx Initializes the odds tracking process by running it immediately and then setting up an interval to poll for updates. ```javascript console.log("Starting NBA Live Odds Tracker..."); console.log(`Polling every ${POLL_INTERVAL / 1000} seconds\n`); // Run immediately, then every 30 seconds trackOdds(); setInterval(trackOdds, POLL_INTERVAL); ``` -------------------------------- ### Fetching Sports Data (SDK - Ruby) Source: https://sportsgameodds.com/docs/basics/setup.mdx This example shows how to fetch sports data using the Ruby SDK. ```APIDOC ## Fetch Sports Data (Ruby SDK) ### Description Uses the sports_odds_api gem to fetch a list of available sports. ### Method SDK Method ### Endpoint N/A (SDK abstraction) ### Parameters #### Constructor Options - **api_key_param** (string) - Required - Your API key for authentication. #### Method Parameters - **client.sports.get**: No parameters required. ### Request Example ```ruby require "sports_odds_api" client = SportsOddsAPI::Client.new( api_key_param: 'YOUR_API_KEY' ) sports = client.sports.get puts sports.data ``` ### Response #### Success Response - **data** (object) - Contains a list of sports objects. ### Response Example ```json { "data": [ { "id": "1", "name": "American Football" }, { "id": "2", "name": "Basketball" } ] } ``` ``` -------------------------------- ### Fetching Sports Data (SDK - Java) Source: https://sportsgameodds.com/docs/basics/setup.mdx This example shows how to fetch sports data using the Java SDK. ```APIDOC ## Fetch Sports Data (Java SDK) ### Description Uses the SportsGameOdds Java SDK to fetch a list of available sports. ### Method SDK Method ### Endpoint N/A (SDK abstraction) ### Parameters #### Builder Options - **apiKeyHeader("YOUR_API_KEY")**: Your API key for authentication. #### Method Parameters - **client.sports().get()**: No parameters required. ### Request Example ```java import com.sportsgameodds.api.client.SportsGameOddsClient; import com.sportsgameodds.api.client.okhttp.SportsGameOddsOkHttpClient; public class Main { public static void main(String[] args) { SportsGameOddsClient client = SportsGameOddsOkHttpClient.builder() .apiKeyHeader("YOUR_API_KEY") .build(); var sports = client.sports().get(); System.out.println(sports.items()); } } ``` ### Response #### Success Response - **items()** (List) - Returns a list of sports objects. ### Response Example ```json [ { "id": "1", "name": "American Football" }, { "id": "2", "name": "Basketball" } ] ``` ``` -------------------------------- ### Run Development Server Source: https://sportsgameodds.com/docs/examples/odds-comparison-dashboard.mdx Command to start the development server for the Next.js application. After running, the dashboard will be accessible at http://localhost:3000. ```bash npm run dev ``` -------------------------------- ### Fetch Teams by Sport ID (Ruby) Source: https://sportsgameodds.com/docs/guides/fetching-teams.mdx This Ruby example shows how to fetch teams for a sport like Basketball. It makes a GET request to the API, including your API key in the headers. ```Ruby require 'net/http' require 'json' uri = URI('https://api.sportsgameodds.com/v2/teams?sportID=BASKETBALL') request = Net::HTTP::Get.new(uri) request['X-Api-Key'] = 'YOUR_TOKEN' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end puts JSON.parse(response.body) ``` -------------------------------- ### Install Python SDK for Sports Odds API Source: https://sportsgameodds.com/docs/basics/setup.mdx Install the official Python SDK using pip. This command is required before you can use the SDK in your Python projects. ```bash pip install sports-odds-api ``` -------------------------------- ### Fetching Sports Data (SDK - Python) Source: https://sportsgameodds.com/docs/basics/setup.mdx This example shows how to fetch sports data using the Python SDK. ```APIDOC ## Fetch Sports Data (Python SDK) ### Description Uses the sports_odds_api SDK to fetch a list of available sports. ### Method SDK Method ### Endpoint N/A (SDK abstraction) ### Parameters #### Constructor Options - **api_key_param** (string) - Required - Your API key for authentication. #### Method Parameters - **client.sports.get()**: No parameters required. ### Request Example ```python from sports_odds_api import SportsGameOdds client = SportsGameOdds( api_key_param='YOUR_API_KEY' ) sports = client.sports.get() print(sports.data) ``` ### Response #### Success Response - **data** (object) - Contains a list of sports objects. ### Response Example ```json { "data": [ { "id": "1", "name": "American Football" }, { "id": "2", "name": "Basketball" } ] } ``` ``` -------------------------------- ### JavaScript/TypeScript SDK Example Source: https://sportsgameodds.com/docs Example of how to use the SportsGameOdds SDK to fetch events with odds available for specified leagues. ```APIDOC ## JavaScript/TypeScript SDK Usage ### Description This snippet demonstrates initializing the SDK client and fetching events with available odds for multiple leagues. ### Method ```javascript import SportsGameOdds from "sports-odds-api"; const client = new SportsGameOdds({ apiKeyHeader: "YOUR_KEY", }); const page = await client.events.get({ leagueID: ["NBA", "NFL"], oddsAvailable: true, }); ``` ### Parameters - `apiKeyHeader` (string): Your API key for authentication. - `leagueID` (array of strings): An array of league IDs to filter events by (e.g., ["NBA", "NFL"]). - `oddsAvailable` (boolean): Filter for events where odds are available. ``` -------------------------------- ### Deploy to Vercel Source: https://sportsgameodds.com/docs/examples/odds-comparison-dashboard.mdx This command-line interface (CLI) command installs the Vercel CLI globally and initiates the deployment process for your project. Ensure you have an environment variable `SPORTSGAMEODDS_KEY` set. ```bash npm install -g vercel vercel ``` -------------------------------- ### Run Arbitrage Calculator Script Source: https://sportsgameodds.com/docs/examples/arbitrage-calculator.mdx Set your API key as an environment variable and then execute the Python script to start scanning for arbitrage opportunities. ```bash export SPORTSGAMEODDS_KEY=your_api_key_here python arb_calculator.py ``` -------------------------------- ### Fetching Sports Data (SDK - TypeScript) Source: https://sportsgameodds.com/docs/basics/setup.mdx This example shows how to fetch sports data using the JavaScript/TypeScript SDK. ```APIDOC ## Fetch Sports Data (TypeScript SDK) ### Description Uses the SportsGameOdds SDK to fetch a list of available sports. ### Method SDK Method ### Endpoint N/A (SDK abstraction) ### Parameters #### Constructor Options - **apiKeyHeader** (string) - Required - Your API key for authentication. #### Method Parameters - **client.sports.get()**: No parameters required. ### Request Example ```javascript import SportsGameOdds from "sports-odds-api"; const client = new SportsGameOdds({ apiKeyHeader: "YOUR_API_KEY", }); const sports = await client.sports.get(); console.log(sports.data); ``` ### Response #### Success Response - **data** (array) - A list of sports objects. ### Response Example ```json [ { "id": "1", "name": "American Football" }, { "id": "2", "name": "Basketball" } ] ``` ``` -------------------------------- ### Error Handling Example Source: https://sportsgameodds.com/docs/info/errors.mdx Implement this pattern to gracefully handle potential API errors in your application. ```javascript try { // Make API request here } catch (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); } ``` -------------------------------- ### Environment Variable Setup and Execution Source: https://sportsgameodds.com/docs/examples/parlay-builder.mdx This snippet shows how to set the necessary API key as an environment variable and then run the Node.js calculator script. Ensure you replace 'your_api_key_here' with your actual SportsGameOdds API key. ```bash export SPORTSGAMEODDS_KEY=your_api_key_here node calculator.js ``` -------------------------------- ### Complete NFL Game Tracker Example Source: https://sportsgameodds.com/docs/guides/realtime-streaming-api.mdx A production-ready JavaScript implementation for tracking NFL games using the Real-Time Streaming API. It handles connection, event subscription, and data updates. ```javascript const axios = require("axios"); const Pusher = require("pusher-js"); const API_KEY = "PUT YOUR API KEY HERE"; const API_BASE_URL = "https://api.sportsgameodds.com/v2"; const LEAGUE_ID = "NFL"; // State variables let events = new Map(); let pusher = null; let channel = null; let connectionState = "disconnected"; let heartbeatInterval = null; const getEventTitle = (event) => { const awayTeam = event.teams?.away?.names?.medium || event.teams?.away?.names?.long || event.teams?.away?.names?.short; const homeTeam = event.teams?.home?.names?.medium || event.teams?.home?.names?.long || event.teams?.home?.names?.short; const gameTime = event.status.startsAt.toLocaleString(); return `${awayTeam} vs ${homeTeam} @ ${gameTime} (${event.eventID})`; }; const startMonitoring = () => { // Heartbeat heartbeatInterval = setInterval(() => { console.log(`💓 Heartbeat...connection: ${connectionState}, events tracked: ${events.size}`); }, 10000); // Connection state changes pusher.connection.bind("state_change", (states) => { connectionState = states.current; console.log(`🔌 Connection state: ${states.previous} → ${states.current}`); }); // Connection errors pusher.connection.bind("error", (error) => { console.error("🚨 Connection error:", error); }); // Connection established pusher.connection.bind("connected", () => { console.log("🎉 Connection established successfully"); }); // Connection disconnected pusher.connection.bind("disconnected", () => { console.log("👋 Connection disconnected"); }); // Failed connection pusher.connection.bind("failed", () => { console.log("💥 Connection failed permanently"); }); }; const connect = async () => { console.log(`🔄 Connecting upcoming events for: ${LEAGUE_ID}...`); connectionState = "connecting"; try { // Get stream metadata console.log("📡 Fetching stream configuration..."); const response = await axios.get(`${API_BASE_URL}/stream/events`, { headers: { "x-api-key": API_KEY }, params: { feed: "events:upcoming", leagueID: LEAGUE_ID, }, }); console.log("✅ Stream configuration received"); const { data: initialEvents, pusherKey, pusherOptions, channel: channelName } = response.data; console.log(`📊 Stream config...channel: ${channelName}, pusherKey: ${pusherKey}, initialEvents: ${initialEvents.length}`); initialEvents.forEach((event) => { events.set(event.eventID, event); console.log(`⏳ Initial Event: ${getEventTitle(event)}`); }); console.log("🔌 Initializing WebSocket connection..."); pusher = new Pusher(pusherKey, pusherOptions); startMonitoring(); // Subscribe to channel with error handling console.log(`📺 Subscribing to channel: ${channelName}`); channel = pusher.subscribe(channelName); channel.bind("pusher:subscription_succeeded", () => { console.log(`✅ Successfully subscribed to channel: ${channelName}`); connectionState = "subscribed"; }); channel.bind("data", async (changedEvents) => { console.log(`🔔 Received change notification for ${changedEvents.length} event(s)`); const eventIDs = changedEvents.map((e) => e.eventID).join(","); if (!eventIDs) return; console.log(`🔍 Fetching full data for events: ${eventIDs}`); const response = await axios .get(`${API_BASE_URL}/events`, { headers: { "x-api-key": API_KEY }, params: { eventIDs }, }) .catch(({ data }) => data); if (!response?.data?.length) return; console.log(`📦 Received ${response.data.length} updated events`); response.data.forEach((current) => { const prev = events.get(current.eventID); if (!prev) { console.log(`🆕 New Event: ${getEventTitle(current)}`); return; } else if (!prev.status.started && current.status.started) { console.log(`🏈 Event started: ${getEventTitle(current)}`); return; } else { console.log(`🔄 Event updated: ${getEventTitle(current)}`); } events.set(current.eventID, current); }); }); } catch (error) { console.error("❌ Connection failed:", error); connectionState = "failed"; } }; connect(); ``` -------------------------------- ### Example OddID Structure and Description Source: https://sportsgameodds.com/docs/data-types/odds.mdx Illustrates various oddIDs and their corresponding betting descriptions. Useful for understanding how different combinations map to specific bets. ```plaintext points-home-game-ml-home ``` ```plaintext points-away-game-sp-away ``` ```plaintext points-all-game-ou-over ``` ```plaintext points-home-1h-ml-home ``` ```plaintext assists-LEBRON_JAMES_NBA-game-ou-over ``` -------------------------------- ### Make Your First API Request Source: https://sportsgameodds.com/docs/basics.mdx Use this cURL command to fetch event data. Replace YOUR_API_KEY_GOES_HERE with your actual API key. You can specify multiple league IDs. ```bash curl -X GET "https://api.sportsgameodds.com/v2/events?leagueID=NBA,NFL,MLB&oddsAvailable=true&apiKey=YOUR_API_KEY_GOES_HERE" ``` -------------------------------- ### Create Next.js Project Source: https://sportsgameodds.com/docs/examples/odds-comparison-dashboard.mdx Sets up a new Next.js project with TypeScript, ESLint, Tailwind CSS, and the App Router. This is the initial step for building the dashboard. ```bash npx create-next-app@latest odds-dashboard cd odds-dashboard npm install ``` -------------------------------- ### Run Player Props Analyzer Script Source: https://sportsgameodds.com/docs/examples/player-props-analyzer.mdx Instructions on how to run the Player Props Analyzer script from the command line, including setting API keys and event IDs. ```bash export SPORTSGAMEODDS_KEY=your_api_key_here python analyzer.py ``` ```bash export SPORTSGAMEODDS_KEY=your_api_key_here export EVENT_ID=abc123 python analyzer.py ``` -------------------------------- ### Fetch Sports Data with Go SDK Source: https://sportsgameodds.com/docs/basics/setup.mdx Initialize the Go SDK client with your API key and fetch sports data. Use `option.WithAPIKeyParam` for authentication. ```go package main import ( "context" "fmt" sportsoddsapi "github.com/SportsGameOdds/sports-odds-api-go" "github.com/SportsGameOdds/sports-odds-api-go/option" ) func main() { client := sportsoddsapi.NewClient( option.WithAPIKeyParam("YOUR_API_KEY"), ) // Fetch sports data ctx := context.Background() // [!code focus] sports, _ := client.Sports.Get(ctx) // [!code focus] fmt.Println(sports.Data) // [!code focus] } ``` -------------------------------- ### Deploy to Netlify Source: https://sportsgameodds.com/docs/examples/odds-comparison-dashboard.mdx This command builds your Next.js project and deploys it to Netlify. Remember to add your API key as an environment variable in the Netlify settings. ```bash npm run build netlify deploy --prod --dir=.next ``` -------------------------------- ### OddID Format Source: https://sportsgameodds.com/docs/info/ai-vibe-coding.mdx Defines the structure and provides examples for `oddID`, which uniquely identifies specific betting markets and outcomes. ```APIDOC ## OddID Format Each `oddID` uniquely identifies a specific side/outcome on a betting market. **Format:** `{statID}-{statEntityID}-{periodID}-{betTypeID}-{sideID}` **Examples:** | oddID | Description | | ----------------------------------------- | --------------------------------------------------- | | `points-home-game-ml-home` | Moneyline bet on the home team to win the full game | | `points-away-1h-sp-away` | Spread bet on the away team to win the first half | | `points-all-game-ou-over` | Over bet on total points for the full game | | `assists-LEBRON_JAMES_1_NBA-game-ou-over` | Over bet on LeBron James assists for the full game | ``` -------------------------------- ### Initialize Odds Tracker Script Source: https://sportsgameodds.com/docs/examples/live-odds-tracker.mdx Sets up the main Node.js script for tracking live NBA odds. It includes API key and base URL configuration, polling interval, and state management for previous odds. ```javascript // tracker.js const fetch = require("node-fetch"); const API_KEY = process.env.SPORTSGAMEODDS_KEY; const API_BASE = "https://api.sportsgameodds.com/v2"; const POLL_INTERVAL = 30000; // 30 seconds // Store previous odds for comparison let previousOdds = {}; // Fetch current NBA odds async function fetchNBAOdds() { try { // Use finalized=false to get upcoming games (live=true only works during live games) const response = await fetch(`${API_BASE}/events?leagueID=NBA&finalized=false&oddsAvailable=true`, { headers: { "x-api-key": API_KEY }, }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const data = await response.json(); return data.data; } catch (error) { console.error("Error fetching odds:", error.message); return []; } } // Compare current odds with previous and detect changes function detectLineMovement(events) { const movements = []; events.forEach((event) => { // Get team names from the nested names structure const awayName = event.teams.away.names.long; const homeName = event.teams.home.names.long; const matchup = `${awayName} @ ${homeName}`; // Check each odd for movement Object.entries(event.odds || {}).forEach(([oddID, currentOdd]) => { // Check each bookmaker's odds for this market Object.entries(currentOdd.byBookmaker || {}).forEach(([bookmakerID, currentBookmakerOdds]) => { const key = `${event.eventID}-${oddID}-${bookmakerID}`; const previousBookmakerOdds = previousOdds[key]; if (previousBookmakerOdds) { const currentLine = currentBookmakerOdds.spread || currentBookmakerOdds.overUnder; const previousLine = previousBookmakerOdds.spread || previousBookmakerOdds.overUnder; const lineChanged = previousLine !== currentLine; const priceChanged = previousBookmakerOdds.odds !== currentBookmakerOdds.odds; if (lineChanged || priceChanged) { movements.push({ matchup, eventID: event.eventID, betType: currentOdd.betTypeID, bookmaker: bookmakerID, side: currentOdd.sideID, previous: { line: previousLine, price: previousBookmakerOdds.odds, }, current: { line: currentLine, price: currentBookmakerOdds.odds, }, lineChanged, priceChanged, }); } } // Store current odds for next comparison previousOdds[key] = { spread: currentBookmakerOdds.spread, overUnder: currentBookmakerOdds.overUnder, odds: currentBookmakerOdds.odds, lastUpdatedAt: currentBookmakerOdds.lastUpdatedAt, }; }); }); }); return movements; } // Display line movements in console function displayMovements(movements) { if (movements.length === 0) { console.log("No line movement detected"); return; } console.log(`\n${movements.length} LINE MOVEMENT(S) DETECTED\n`); movements.forEach((movement) => { console.log("----------------------------------------"); console.log(`${movement.matchup}`); console.log(`${movement.betType.toUpperCase()} (${movement.side}) - ${movement.bookmaker}`); if (movement.lineChanged) { console.log(`Line: ${movement.previous.line} -> ${movement.current.line}`); } if (movement.priceChanged) { console.log(`Price: ${movement.previous.price} -> ${movement.current.price}`); } console.log("----------------------------------------\n"); }); } // Main tracking loop async function trackOdds() { console.log(new Date().toLocaleTimeString(), "- Checking for line movement..."); const events = await fetchNBAOdds(); if (events.length === 0) { console.log("No NBA games found\n"); return; } const movements = detectLineMovement(events); displayMovements(movements); } // Start tracking trackOdds(); setInterval(trackOdds, POLL_INTERVAL); ``` -------------------------------- ### Fetch Teams by League ID (Javascript) Source: https://sportsgameodds.com/docs/guides/fetching-teams.mdx Get a list of all teams belonging to a specific league by providing the leagueID. ```javascript await axios.get("/v2/teams", { params: { leagueID: "NBA", }, }); ``` -------------------------------- ### Fetch Player Data Source: https://sportsgameodds.com/docs/endpoints/getPlayers Retrieves a list of players. This endpoint can be used to get all players or filter them by a specific team or event. ```APIDOC ## GET /players ### Description Get a list of Players for a specific Team or Event ### Method GET ### Endpoint https://sportsgameodds.com/docs/endpoints/getPlayers ### Parameters #### Query Parameters - **team** (string) - Optional - Filter players by a specific team. - **event** (string) - Optional - Filter players by a specific event. ``` -------------------------------- ### Fetch Sports Data with Java SDK Source: https://sportsgameodds.com/docs/basics/setup.mdx Initialize the Java SDK client using the builder pattern and your API key. The `apiKeyHeader` option is used for authentication. ```java import com.sportsgameodds.api.client.SportsGameOddsClient; import com.sportsgameodds.api.client.okhttp.SportsGameOddsOkHttpClient; public class Main { public static void main(String[] args) { SportsGameOddsClient client = SportsGameOddsOkHttpClient.builder() .apiKeyHeader("YOUR_API_KEY") .build(); // Fetch sports data var sports = client.sports().get(); // [!code focus] System.out.println(sports.items()); // [!code focus] } } ``` -------------------------------- ### Fetch Sports Data with Ruby SDK Source: https://sportsgameodds.com/docs/basics/setup.mdx Initialize the Ruby SDK client with your API key and fetch sports data. The `api_key_param` is used for authentication. ```ruby require "sports_odds_api" client = SportsOddsAPI::Client.new( api_key_param: 'YOUR_API_KEY' ) # Fetch sports data sports = client.sports.get # [!code focus] puts sports.data # [!code focus] ``` -------------------------------- ### Connect to Live Events Stream (Python) Source: https://sportsgameodds.com/docs/guides/realtime-streaming-api.mdx Establishes a WebSocket connection to receive live event updates. Requires the 'pusherclient' library and an API key. ```python import requests import pusherclient API_BASE_URL = "https://api.sportsgameodds.com/v2" API_KEY = "API_KEY_GOES_HERE" def handle_update(data): # Process incoming data updates for event in data['events']: print(f"Updated: {event['eventID']}") def connect_to_live_events(): # Get connection details response = requests.get( f"{API_BASE_URL}/stream/events", headers={'x-api-key': API_KEY}, params={'feed': 'events:live'} ) stream_info = response.json() print(f"Connected with {len(stream_info['data'])} initial events") # Connect to Pusher (Note: private channels require custom auth in Python) pusher_key = stream_info['pusherKey'] channel_name = stream_info['channel'] pusher = pusherclient.Pusher(pusher_key) channel = pusher.subscribe(channel_name) channel.bind('data', handle_update) pusher.connection.bind('pusher:connection_established', lambda data: print("Connected to stream")) if __name__ == "__main__": connect_to_live_events() ``` -------------------------------- ### Get API Usage Data Source: https://sportsgameodds.com/docs/endpoints/getUsageData This endpoint allows you to retrieve information about your API key's usage and current rate limits. ```APIDOC ## GET /account/usage - Check API Usage and Limits ### Description Get rate-limits and usage data about your API key. ### Method GET ### Endpoint https://sportsgameodds.com/docs/endpoints/getUsageData ``` -------------------------------- ### Add Environment Variable Source: https://sportsgameodds.com/docs/examples/odds-comparison-dashboard.mdx Create a .env.local file to store your API key securely. This key is used for authenticating with the sports betting odds API. ```bash SPORTSGAMEODDS_KEY=your_api_key_here ``` -------------------------------- ### Fetch Team by Team ID (Ruby) Source: https://sportsgameodds.com/docs/guides/fetching-teams.mdx Get a specific team's data by its teamID. The API key should be set in the request headers. ```ruby require 'net/http' require 'json' uri = URI('https://api.sportsgameodds.com/v2/teams?teamID=LOS_ANGELES_LAKERS_NBA') request = Net::HTTP::Get.new(uri) request['X-Api-Key'] = 'YOUR_TOKEN' response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end puts JSON.parse(response.body) ``` -------------------------------- ### Fetch Sports Data with Python SDK Source: https://sportsgameodds.com/docs/basics/setup.mdx Initialize the Python SDK client using your API key and retrieve sports data. The `api_key_param` is used for authentication. ```python from sports_odds_api import SportsGameOdds client = SportsGameOdds( api_key_param='YOUR_API_KEY' ) # Fetch sports data sports = client.sports.get() # [!code focus] print(sports.data) # [!code focus] ``` -------------------------------- ### Monitor Live Events Source: https://sportsgameodds.com/docs/guides/realtime-streaming-api.mdx Use this endpoint to get a stream of all currently live games across all sports. Ensure your API key has streaming permissions. ```javascript axios.get("https://api.sportsgameodds.com/v2/stream/events", { headers: { 'x-api-key': API_KEY }, params: { feed: 'events:live' } }); ``` -------------------------------- ### Example Team Data Response Source: https://sportsgameodds.com/docs/guides/fetching-teams.mdx This JSON structure represents a typical response when fetching team data. It includes pagination information and a list of team objects. ```json { "nextCursor": "BELMONT_NCAAB", "success": true, "data": [ { "sportID": "BASKETBALL", "names": { "short": "LAL", "medium": "Lakers", "long": "Los Angeles Lakers" }, "leagueID": "NBA", "teamID": "LAKERS_NBA" }, { "sportID": "BASKETBALL", "names": { "short": "BOS", "medium": "Celtics", "long": "Boston Celtics" }, "leagueID": "NBA", "teamID": "CELTICS_NBA" }, { "sportID": "BASKETBALL", "names": { "short": "GSW", "medium": "Warriors", "long": "Golden State Warriors" }, "leagueID": "NBA", "teamID": "WARRIORS_NBA" }, // ... // Up to 30 objects may be returned in this object. If there are more available // then you'll see a nextCursor property you can use to fetch the next // page of related objects. ] } ``` -------------------------------- ### 2nd Half Over/Under Source: https://sportsgameodds.com/docs/data-types/markets/football Get the total over/under points for the second half of the game. Provides over and under values. ```APIDOC ## GET /odds/2ndHalfOverUnder ### Description Retrieves the total over/under points for the second half of a sports game. Provides both the over and under values. ### Method GET ### Endpoint /odds/2ndHalfOverUnder ### Parameters #### Query Parameters - **league** (string) - Required - The league of the game (e.g., CFL, NCAAF, NFL, USFL, XFL). - **statID** (string) - Required - The statistic ID, which is `points`. - **betTypeID** (string) - Required - The bet type ID, which is `ou`. - **periodID** (string) - Required - The period ID, which is `2h`. - **statEntityID** (string) - Required - The stat entity ID, which is `all`. ### Response #### Success Response (200) - **points-all-2h-ou-over** (number) - The over points for the second half. - **points-all-2h-ou-under** (number) - The under points for the second half. #### Response Example { "points-all-2h-ou-over": 43.5, "points-all-2h-ou-under": 43.5 } ``` -------------------------------- ### 1st Half Over/Under Source: https://sportsgameodds.com/docs/data-types/markets/football Get the total over/under points for the first half of the game. Provides over and under values. ```APIDOC ## GET /odds/1stHalfOverUnder ### Description Retrieves the total over/under points for the first half of a sports game. Provides both the over and under values. ### Method GET ### Endpoint /odds/1stHalfOverUnder ### Parameters #### Query Parameters - **league** (string) - Required - The league of the game (e.g., CFL, NCAAF, NFL, USFL, XFL). - **statID** (string) - Required - The statistic ID, which is `points`. - **betTypeID** (string) - Required - The bet type ID, which is `ou`. - **periodID** (string) - Required - The period ID, which is `1h`. - **statEntityID** (string) - Required - The stat entity ID, which is `all`. ### Response #### Success Response (200) - **points-all-1h-ou-over** (number) - The over points for the first half. - **points-all-1h-ou-under** (number) - The under points for the first half. #### Response Example { "points-all-1h-ou-over": 42.5, "points-all-1h-ou-under": 42.5 } ``` -------------------------------- ### Initialize SportsGameOdds Client Source: https://sportsgameodds.com/docs Instantiate the client with your API key. This client is used to make requests to the SportsGameOdds API. ```javascript import SportsGameOdds from "sports-odds-api"; const client = new SportsGameOdds({ apiKeyHeader: "YOUR_KEY", }); ``` -------------------------------- ### Calculate Combined Decimal Odds - JavaScript Source: https://sportsgameodds.com/docs/examples/parlay-builder.mdx Multiply all decimal odds of each leg to get the combined decimal odds for the parlay. This is a core step in calculating the total payout. ```javascript const combinedDecimalOdds = legs.reduce((acc, leg) => acc * leg.decimalOdds, 1); ``` -------------------------------- ### Authentication Source: https://sportsgameodds.com/docs/basics/cheat-sheet.mdx Demonstrates how to authenticate API requests using an API key, either in the header or as a query parameter. ```APIDOC ## Authentication All requests require an API key. You can obtain an API key from the [pricing page](/pricing). ### Using Header Authentication Place your API key in the `x-api-key` header. ```javascript fetch("https://api.sportsgameodds.com/v2/events", { headers: { "x-api-key": "your-api-key-here" }, }); ``` ### Using Query Parameter Authentication Alternatively, place your API key in the `apiKey` query parameter. ```javascript fetch("https://api.sportsgameodds.com/v2/events?apiKey=YOUR_API_KEY_GOES_HERE"); ``` ```