Sportsort GraphQL API Documentation

Welcome to the Sportsort GraphQL API! This guide will help you get started with your new API key, test your access, and make your first queries to our hockey data.

Getting Started

After purchasing an API key, you'll receive it via email. Your API key allows you to make a specific number of requests per day based on your subscription plan.

Quick Start Example

Here's a simple example of how to query our API using your key:

JavaScript using fetch

async function fetchNHLData() {
  const response = await fetch('https://api.sportsort.co/api/graphql', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_KEY'
    },
    body: JSON.stringify({
      query: `
        {
          todaysGames {
            HomeTeam {
              Name
            }
            AwayTeam {
              Name
            }
            DateTime
          }
        }
      `
    })
  });

  const data = await response.json();
  console.log(data);
}

fetchNHLData();

Authentication

Your API key must be included in the Authorization header of all requests using the Bearer token format:

Authorization: Bearer YOUR_API_KEY

If you don't include a valid API key, you'll receive an authentication error:

{
  "errors": [
    {
      "message": "API key is required",
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR"
      }
    }
  ],
  "data": null
}

Testing Your API Key

1. Using cURL

You can test your API key from the command line using cURL:

curl -X POST https://api.sportsort.co/api/graphql \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{"query":"{ todaysGames { HomeTeam { Name } AwayTeam { Name } } }"}'

2. Using GraphQL Playground

You can also use GraphQL Playground to explore our API:

  1. Visit https://api.sportsort.co/api/graphql in your browser
  2. Click on the "HTTP HEADERS" section at the bottom
  3. Add your authentication header:
    {
      "Authorization": "Bearer YOUR_API_KEY"
    }
  4. Try a query in the main editor area

3. Using Postman

If you prefer Postman for API testing:

  1. Create a new POST request to https://api.sportsort.co/api/graphql
  2. Add an Authorization header with your API key
  3. Set the Content-Type to application/json
  4. In the request body, use raw JSON format:
    {
      "query": "{ todaysGames { HomeTeam { Name } AwayTeam { Name } } }"
    }

Using the API with Different Languages

Python Example

Python using requests

import requests

url = 'https://api.sportsort.co/api/graphql'
headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_KEY'
}

query = """
{
  todaysGames {
    HomeTeam {
      Name
    }
    AwayTeam {
      Name
    }
    DateTime
    Status
  }
}
"""

response = requests.post(url, json={'query': query}, headers=headers)
print(response.json())

Node.js Example with Apollo Client

Node.js using Apollo Client

const { ApolloClient, InMemoryCache, createHttpLink, gql } = require('@apollo/client');
const { setContext } = require('@apollo/client/link/context');

// Create the HTTP link
const httpLink = createHttpLink({
  uri: 'https://api.sportsort.co/api/graphql',
});

// Add the authorization header
const authLink = setContext((_, { headers }) => {
  return {
    headers: {
      ...headers,
      authorization: 'Bearer YOUR_API_KEY',
    }
  };
});

// Create the Apollo Client
const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

// Make a query
client.query({
  query: gql`
    {
      upcomingGames {
        HomeTeam {
          Name
        }
        AwayTeam {
          Name
        }
        DateTime
        Status
      }
    }
  `
})
.then(result => console.log(result))
.catch(error => console.error(error));

Tutorial: Building a Simple NHL Schedule Viewer

Let's build a simple web app that shows today's NHL games:

1. HTML Structure

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>NHL Games Today</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
  <div class="container mt-5">
    <h1>NHL Games Today</h1>
    <div id="games-container" class="row mt-4">
      <p>Loading games...</p>
    </div>
  </div>

  <script src="app.js"></script>
</body>
</html>

2. JavaScript Implementation

JavaScript app.js

const API_KEY = 'YOUR_API_KEY';
const API_URL = 'https://api.sportsort.co/api/graphql';

async function fetchTodaysGames() {
  try {
    const response = await fetch(API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${API_KEY}`
      },
      body: JSON.stringify({
        query: `
          {
            todaysGames {
              GameID
              DateTime
              Status
              HomeTeam {
                Name
              }
              AwayTeam {
                Name
              }
              HomeTeamScore
              AwayTeamScore
              IsClosed
            }
          }
        `
      })
    });

    const result = await response.json();
    
    if (result.errors) {
      throw new Error(result.errors[0].message);
    }
    
    displayGames(result.data.todaysGames);
  } catch (error) {
    document.getElementById('games-container').innerHTML = `
      <div class="alert alert-danger">
        Error: ${error.message}
      </div>
    `;
  }
}

function displayGames(games) {
  const container = document.getElementById('games-container');
  
  if (!games || games.length === 0) {
    container.innerHTML = '<p>No games scheduled for today.</p>';
    return;
  }
  
  const gamesHTML = games.map(game => {
    const gameTime = new Date(game.DateTime).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
    const isLive = game.Status === 'InProgress';
    const isCompleted = game.IsClosed;
    
    let statusDisplay = `<span class="badge bg-primary">Scheduled: ${gameTime}</span>`;
    if (isLive) {
      statusDisplay = '<span class="badge bg-danger">LIVE</span>';
    } else if (isCompleted) {
      statusDisplay = '<span class="badge bg-secondary">Final</span>';
    }
    
    return `
      <div class="col-md-6 mb-4">
        <div class="card">
          <div class="card-header d-flex justify-content-between align-items-center">
            ${statusDisplay}
            <span>Game #${game.GameID}</span>
          </div>
          <div class="card-body">
            <div class="row align-items-center">
              <div class="col-5 text-end">
                <h5>${game.AwayTeam.Name}</h5>
                ${isLive || isCompleted ? `<h3>${game.AwayTeamScore}</h3>` : ''}
              </div>
              <div class="col-2 text-center">
                <h4>@</h4>
              </div>
              <div class="col-5 text-start">
                <h5>${game.HomeTeam.Name}</h5>
                ${isLive || isCompleted ? `<h3>${game.HomeTeamScore}</h3>` : ''}
              </div>
            </div>
          </div>
        </div>
      </div>
    `;
  }).join('');
  
  container.innerHTML = gamesHTML;
}

// Load games when the page loads
document.addEventListener('DOMContentLoaded', fetchTodaysGames);

Available Queries

Our API offers several useful queries:

Get All Games

{
  games {
    GameID
    DateTime
    HomeTeam {
      Name
    }
    AwayTeam {
      Name
    }
  }
}

Get Today's Games

{
  todaysGames {
    GameID
    DateTime
    Status
    HomeTeam {
      Name
    }
    AwayTeam {
      Name
    }
    HomeTeamScore
    AwayTeamScore
  }
}

Get Games by Date Range

{
  gamesByDateRange(
    startDate: "2023-10-10", 
    endDate: "2023-10-20",
    team: "Toronto Maple Leafs"
  ) {
    GameID
    DateTime
    HomeTeam {
      Name
    }
    AwayTeam {
      Name
    }
  }
}

Get Weekly Game Count

{
  weeklyGameCount(weekNumber: 5, year: 2023) {
    teamName
    gameCount
    homeGames {
      opponent
      gameDate
    }
    awayGames {
      opponent
      gameDate
    }
  }
}

Rate Limiting

Your API access is rate-limited based on your subscription plan:

Plan Daily Request Limit
Free Plan 100 requests per day
Basic Plan 1,000 requests per day
Pro Plan 10,000 requests per day
Unlimited Plan No request limit

If you exceed your rate limit, you'll receive an error response:

{
  "errors": [
    {
      "message": "Rate limit exceeded for your plan",
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR"
      }
    }
  ],
  "data": null
}

Need Help?

If you encounter any issues or have questions about using the API:

  1. Check this documentation for examples and guidance
  2. Make sure you're correctly passing your API key in the Authorization header
  3. Verify that your query syntax is correct using the schema explorer
  4. Contact our support team at support@sportsort.co

Happy coding with the Sportsort GraphQL API!