### Image Proxying Examples (HTML and String)
Source: https://www.realtimesportsapi.com/docs/index
Demonstrates how team logos and athlete headshots are automatically proxied through a CDN. Includes examples for both direct HTML image tags and string representations within API responses.
```javascript
// Team logos are proxied
"logo": "https://realtimesportsapi.com/api/images/proxy?url=..."
// Direct image access (no auth required)
```
--------------------------------
### Get Events for a League - cURL Example
Source: https://www.realtimesportsapi.com/docs/index
Fetches all events for a given league and sport. Supports a 'limit' query parameter to control the number of results per page. Authentication is required.
```curl
curl "https://realtimesportsapi.com/api/v1/sports/football/leagues/nfl/events?limit=10" \
-H "Authorization: Bearer YOUR_API_KEY"
```
--------------------------------
### Get All Sports - cURL Example
Source: https://www.realtimesportsapi.com/docs/index
Retrieves a list of all available sports supported by the API. This endpoint requires authentication via a JWT token in the Authorization header.
```curl
curl -X GET "https://realtimesportsapi.com/api/v1/sports" \
-H "Authorization: Bearer YOUR_API_KEY"
```
--------------------------------
### Subscribe to WebSocket Events (JavaScript)
Source: https://www.realtimesportsapi.com/docs/index
JavaScript examples demonstrating how to subscribe to various event types and apply filters for real-time data streams via WebSockets. Includes examples for score updates, play events, status changes, and frequency throttling.
```javascript
// Subscribe to all score updates
ws.send(JSON.stringify({
type: 'subscribe',
event: 'score_update'
}));
// Subscribe to play events for a specific league
ws.send(JSON.stringify({
type: 'subscribe',
event: 'play_event',
filters: {
sport: 'football',
league: 'nfl'
}
}));
// Subscribe to status changes for a specific game
ws.send(JSON.stringify({
type: 'subscribe',
event: 'status_change',
filters: {
sport: 'football',
league: 'nfl',
eventId: '401772982'
}
}));
// Subscribe with frequency throttling (events batched every 30 seconds)
ws.send(JSON.stringify({
type: 'subscribe',
event: 'score_update',
filters: {
sport: 'basketball',
league: 'nba'
},
frequency: '30s' // Options: 'asap', '30s', '1m', '5m', '10m', '30m'
}));
```
--------------------------------
### Get Leagues for a Sport - cURL Example
Source: https://www.realtimesportsapi.com/docs/index
Fetches all leagues associated with a specific sport. The request must include the sport's identifier and be authenticated with a JWT token.
```curl
curl -X GET "https://realtimesportsapi.com/api/v1/sports/football/leagues" \
-H "Authorization: Bearer YOUR_API_KEY"
```
--------------------------------
### Complete Express.js Webhook Endpoint Example
Source: https://www.realtimesportsapi.com/docs/index
A comprehensive example of an Express.js webhook endpoint that verifies signatures and handles various event types from the Realtime Sports API. It includes signature verification, event type routing, and logging of game events. Requires Express.js and the 'crypto' module.
```javascript
const express = require('express');
const crypto = require('crypto');
const app = express();
app.use(express.json());
// Your webhook secret (from webhook creation)
const WEBHOOK_SECRET = 'your-webhook-secret';
function verifySignature(payload, signature) {
const expected = crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(JSON.stringify(payload))
.digest('hex');
const provided = signature.replace('sha256=', '');
return crypto.timingSafeEqual(
Buffer.from(expected),
Buffer.from(provided)
);
}
app.post('/webhook', (req, res) => {
const signature = req.headers['x-webhook-signature'];
const eventType = req.headers['x-webhook-event'];
// Verify signature
if (!verifySignature(req.body, signature)) {
return res.status(401).json({ error: 'Invalid signature' });
}
const { event, timestamp, data } = req.body;
// Handle different event types
switch (event) {
case 'event.live':
console.log(`Game went live: ${data.name}`);
// Notify users, update database, etc.
break;
case 'event.score_change':
console.log(`Score update: ${data.awayTeam.name} ${data.awayTeam.score} - ${data.homeTeam.score} ${data.homeTeam.name}`);
// Update scores in your app
break;
case 'event.status_change':
console.log(`Status changed: ${data.status.type.name}`);
// Update game status
break;
case 'event.play':
console.log(`New play: ${data.play.text}`);
// Display play in your app
break;
case 'event.final':
console.log(`Game ended: Final score ${data.awayTeam.score} - ${data.homeTeam.score}`);
// Show final results
break;
}
// Always return 200 OK
res.status(200).json({ received: true });
});
app.listen(3000, () => {
console.log('Webhook server listening on port 3000');
});
```
--------------------------------
### Get All Sports
Source: https://www.realtimesportsapi.com/docs/index
Retrieves a list of all available sports supported by the API.
```APIDOC
## GET /v1/sports
### Description
Get all available sports.
### Method
GET
### Endpoint
/v1/sports
### Parameters
#### Query Parameters
None
#### Request Body
None
### Request Example
```
curl -X GET "https://realtimesportsapi.com/api/v1/sports" \
-H "Authorization: Bearer YOUR_API_KEY"
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the request was successful.
- **data** (array) - An array of sport objects.
- **id** (string) - The unique identifier for the sport.
- **name** (string) - The name of the sport.
- **slug** (string) - A URL-friendly identifier for the sport.
- **displayName** (string) - The display name of the sport.
#### Response Example
```json
{
"success": true,
"data": [
{
"id": "20",
"name": "Football",
"slug": "football",
"displayName": "Football"
},
{
"id": "40",
"name": "Basketball",
"slug": "basketball",
"displayName": "Basketball"
}
]
}
```
```
--------------------------------
### Get Athletes for a League (Paginated) - cURL Example
Source: https://www.realtimesportsapi.com/docs/index
Fetches a paginated list of all athletes for a given league and sport. Supports 'page' and 'limit' query parameters for pagination. Requires authentication.
```curl
curl "https://realtimesportsapi.com/api/v1/sports/baseball/leagues/mlb/athletes?page=1&limit=25" \
-H "Authorization: Bearer YOUR_API_KEY"
```
--------------------------------
### Get Live Events - cURL Example
Source: https://www.realtimesportsapi.com/docs/index
Retrieves only the currently live events for a specified league and sport. This endpoint requires authentication via a JWT token in the Authorization header.
```curl
curl "https://realtimesportsapi.com/api/v1/sports/football/leagues/nfl/events/live" \
-H "Authorization: Bearer YOUR_API_KEY"
```
--------------------------------
### Get Teams for a League - cURL Example
Source: https://www.realtimesportsapi.com/docs/index
Retrieves all teams within a specified league and sport. This endpoint returns team names, logos, colors, venue information, and standings. Authentication is required.
```curl
curl "https://realtimesportsapi.com/api/v1/sports/baseball/leagues/mlb/teams" \
-H "Authorization: Bearer YOUR_API_KEY"
```
--------------------------------
### Get Specific Season Details - cURL Example
Source: https://www.realtimesportsapi.com/docs/index
Retrieves detailed information for a particular season, identified by its year, within a specified league and sport. Requires authentication.
```curl
curl "https://realtimesportsapi.com/api/v1/sports/baseball/leagues/mlb/seasons/2025" \
-H "Authorization: Bearer YOUR_API_KEY"
```
--------------------------------
### Rate Limit Headers Example
Source: https://www.realtimesportsapi.com/docs/index
Illustrates the rate limit headers returned in API responses. These headers provide information about the request limit, remaining requests, and when the limit will reset.
```http
X-RateLimit-Limit: 50000
X-RateLimit-Remaining: 49995
X-RateLimit-Reset: 1642636800000 // Unix timestamp
```
--------------------------------
### Get Live NFL Games (JavaScript)
Source: https://www.realtimesportsapi.com/docs/index
Fetches live NFL games using the API. It makes a GET request to the live events endpoint and logs the data if successful. Requires an API key.
```JavaScript
const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://realtimesportsapi.com/api/v1';
// Get live NFL games
async function getLiveNFLGames() {
const response = await fetch(
`${BASE_URL}/sports/football/leagues/nfl/events/live`,
{ headers: { 'Authorization': `Bearer ${API_KEY}` } }
);
const data = await response.json();
if (data.success) {
console.log('Live games:', data.data);
}
}
getLiveNFLGames();
```
--------------------------------
### Get Seasons for a League (Paginated) - cURL Example
Source: https://www.realtimesportsapi.com/docs/index
Fetches a paginated list of historical seasons for a specified league and sport. This endpoint supports 'page' and 'limit' query parameters for managing results. Authentication is required.
```curl
curl "https://realtimesportsapi.com/api/v1/sports/football/leagues/nfl/seasons?limit=5" \
-H "Authorization: Bearer YOUR_API_KEY"
```
--------------------------------
### Get Play-by-Play for an Event
Source: https://www.realtimesportsapi.com/docs/index
Retrieves play-by-play data for a specific event, paginated.
```APIDOC
## GET /sports/{sport}/leagues/{league}/events/{eventId}/plays
### Description
Get play-by-play (paginated) for a specific event.
### Method
GET
### Endpoint
/sports/{sport}/leagues/{league}/events/{eventId}/plays
### Parameters
#### Path Parameters
- **sport** (string) - Required - The slug or ID of the sport (e.g., "football").
- **league** (string) - Required - The slug or ID of the league (e.g., "nfl").
- **eventId** (string) - Required - The unique identifier of the event.
#### Query Parameters
- **page** (integer) - Optional - Page number for pagination. Defaults to 1.
- **limit** (integer) - Optional - Results per page. Defaults to 25.
#### Request Body
None
### Request Example
```
curl "https://realtimesportsapi.com/api/v1/sports/football/leagues/nfl/events/12345/plays?limit=10" \
-H "Authorization: Bearer YOUR_API_KEY"
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the request was successful.
- **data** (array) - An array of play objects.
- **playId** (string) - Unique identifier for the play.
- **sequence** (integer) - The sequence number of the play within the game.
- **description** (string) - A textual description of the play.
- **clock** (string) - The game clock time when the play occurred.
- **period** (object) - Information about the game period.
- **scoringPlay** (boolean) - Indicates if this play resulted in a score.
- **penalty** (boolean) - Indicates if a penalty occurred during this play.
#### Response Example
```json
{
"success": true,
"data": [
{
"playId": "p1",
"sequence": 1,
"description": "Kickoff by Ravens. Ball caught by Chiefs at their own 25-yard line.",
"clock": "15:00",
"period": {"number": 1, "type": "1st Quarter"},
"scoringPlay": false,
"penalty": false
},
{
"playId": "p2",
"sequence": 2,
"description": "Mahomes pass complete to Kelce for 15 yards for a first down.",
"clock": "14:45",
"period": {"number": 1, "type": "1st Quarter"},
"scoringPlay": false,
"penalty": false
}
// ... more plays
]
}
```
```
--------------------------------
### Get Live Events
Source: https://www.realtimesportsapi.com/docs/index
Retrieves a list of all currently live events for a specified league and sport.
```APIDOC
## GET /sports/{sport}/leagues/{league}/events/live
### Description
Get currently live events only.
### Method
GET
### Endpoint
/sports/{sport}/leagues/{league}/events/live
### Parameters
#### Path Parameters
- **sport** (string) - Required - The slug or ID of the sport (e.g., "football").
- **league** (string) - Required - The slug or ID of the league (e.g., "nfl").
#### Query Parameters
None
#### Request Body
None
### Request Example
```
curl "https://realtimesportsapi.com/api/v1/sports/football/leagues/nfl/events/live" \
-H "Authorization: Bearer YOUR_API_KEY"
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the request was successful.
- **data** (array) - An array of live event objects. The structure is the same as the `/events` endpoint, but only includes events with a status of "inProgress".
#### Response Example
```json
{
"success": true,
"data": [
{
"id": "67890",
"name": "Green Bay Packers vs. Chicago Bears",
"startTime": "2024-12-22T17:00:00Z",
"status": "inProgress",
"sport": {"id": "20", "slug": "football"},
"league": {"id": "28", "slug": "nfl"},
"homeTeam": {"name": "Green Bay Packers", "abbreviation": "GB"},
"awayTeam": {"name": "Chicago Bears", "abbreviation": "CHI"}
}
// ... more live events
]
}
```
```
--------------------------------
### Get Events by League
Source: https://www.realtimesportsapi.com/docs/index
Retrieves a paginated list of all events for a specified league and sport.
```APIDOC
## GET /sports/{sport}/leagues/{league}/events
### Description
Get all events for a league.
### Method
GET
### Endpoint
/sports/{sport}/leagues/{league}/events
### Parameters
#### Path Parameters
- **sport** (string) - Required - The slug or ID of the sport (e.g., "football").
- **league** (string) - Required - The slug or ID of the league (e.g., "nfl").
#### Query Parameters
- **limit** (integer) - Optional - Results per page. Defaults to 50.
#### Request Body
None
### Request Example
```
curl "https://realtimesportsapi.com/api/v1/sports/football/leagues/nfl/events?limit=10" \
-H "Authorization: Bearer YOUR_API_KEY"
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the request was successful.
- **data** (array) - An array of event objects.
- **id** (string) - The unique identifier for the event.
- **name** (string) - The name of the event (e.g., "Team A vs. Team B").
- **startTime** (string) - The scheduled start time of the event.
- **status** (string) - The current status of the event (e.g., "scheduled", "inProgress", "completed").
- **sport** (object) - Information about the sport.
- **league** (object) - Information about the league.
- **homeTeam** (object) - Information about the home team.
- **awayTeam** (object) - Information about the away team.
#### Response Example
```json
{
"success": true,
"data": [
{
"id": "12345",
"name": "Kansas City Chiefs vs. Baltimore Ravens",
"startTime": "2024-12-22T13:00:00Z",
"status": "scheduled",
"sport": {"id": "20", "slug": "football"},
"league": {"id": "28", "slug": "nfl"},
"homeTeam": {"name": "Kansas City Chiefs", "abbreviation": "KC"},
"awayTeam": {"name": "Baltimore Ravens", "abbreviation": "BAL"}
}
// ... more events
]
}
```
```
--------------------------------
### Get Plays with Pagination using Real-Time Sports API
Source: https://www.realtimesportsapi.com/docs/index
Fetches plays for a specific NFL game with pagination support. It demonstrates how to retrieve the number of plays on the current page, the total number of plays, and the total number of pages available.
```python
plays_response = api.get_plays('football', 'nfl', '401772982', page=1)
print(f"Page 1: {len(plays_response['data'])} plays")
print(f"Total: {plays_response['meta']['pagination']['total']} plays")
print(f"Total pages: {plays_response['meta']['pagination']['totalPages']}")
```
--------------------------------
### Get Leagues by Sport
Source: https://www.realtimesportsapi.com/docs/index
Retrieves a list of all leagues associated with a specific sport.
```APIDOC
## GET /v1/sports/{sport}/leagues
### Description
Get all leagues for a specific sport.
### Method
GET
### Endpoint
/v1/sports/{sport}/leagues
### Parameters
#### Path Parameters
- **sport** (string) - Required - The slug or ID of the sport (e.g., "football").
#### Query Parameters
None
#### Request Body
None
### Request Example
```
curl -X GET "https://realtimesportsapi.com/api/v1/sports/football/leagues" \
-H "Authorization: Bearer YOUR_API_KEY"
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the request was successful.
- **data** (array) - An array of league objects.
- **id** (string) - The unique identifier for the league.
- **name** (string) - The name of the league.
- **slug** (string) - A URL-friendly identifier for the league.
- **abbreviation** (string) - The abbreviation for the league.
- **currentSeason** (integer) - The current season year for the league (if applicable).
#### Response Example
```json
{
"success": true,
"data": [
{
"id": "28",
"name": "National Football League",
"slug": "nfl",
"abbreviation": "NFL",
"currentSeason": 2025
},
{
"id": "35",
"name": "NCAA Football",
"slug": "college-football",
"abbreviation": "NCAA"
}
]
}
```
```
--------------------------------
### Get Teams by League
Source: https://www.realtimesportsapi.com/docs/index
Retrieves a list of all teams within a specified league and sport.
```APIDOC
## GET /sports/{sport}/leagues/{league}/teams
### Description
Get all teams for a league.
### Method
GET
### Endpoint
/sports/{sport}/leagues/{league}/teams
### Parameters
#### Path Parameters
- **sport** (string) - Required - The slug or ID of the sport (e.g., "baseball").
- **league** (string) - Required - The slug or ID of the league (e.g., "mlb").
#### Query Parameters
None
#### Request Body
None
### Request Example
```
curl "https://realtimesportsapi.com/api/v1/sports/baseball/leagues/mlb/teams" \
-H "Authorization: Bearer YOUR_API_KEY"
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the request was successful.
- **data** (array) - An array of team objects.
- **name** (string) - The name of the team.
- **abbreviation** (string) - The abbreviation of the team.
- **slug** (string) - A URL-friendly identifier for the team.
- **logos** (object) - Logo URLs for the team.
- **default** (string) - URL for the default logo.
- **dark** (string) - URL for the dark theme logo.
- **colors** (object) - Team color hex codes.
- **primary** (string) - Primary team color.
- **secondary** (string) - Secondary team color.
- **tertiary** (string) - Tertiary team color.
- **venue** (object) - Information about the team's venue.
- **name** (string) - Name of the venue.
- **capacity** (integer) - Capacity of the venue.
- **record** (object) - Team's win-loss record.
- **standings** (object) - Team's standing in the league.
#### Response Example
(Response structure will vary based on the sport and league, but will include team names, logos, colors, and venue information.)
```json
{
"success": true,
"data": [
{
"name": "New York Yankees",
"abbreviation": "NYY",
"slug": "ny-yankees",
"logos": {
"default": "https://example.com/logos/yankees_default.png",
"dark": "https://example.com/logos/yankees_dark.png"
},
"colors": {
"primary": "#003087",
"secondary": "#E4002B"
},
"venue": {
"name": "Yankee Stadium",
"capacity": 46537
},
"record": {
"wins": 99,
"losses": 63
},
"standings": {
"rank": 1
}
}
// ... more teams
]
}
```
```
--------------------------------
### Get All Plays for an Event (JavaScript)
Source: https://www.realtimesportsapi.com/docs/index
Retrieves all plays for a given event ID by paginating through the results. It repeatedly calls the getPlays function until all pages are fetched. Requires an API key.
```JavaScript
const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://realtimesportsapi.com/api/v1';
// Get plays with pagination
async function getPlays(eventId, page = 1) {
const response = await fetch(
`${BASE_URL}/sports/football/leagues/nfl/events/${eventId}/plays?page=${page}&limit=25`,
{ headers: { 'Authorization': `Bearer ${API_KEY}` } }
);
const data = await response.json();
console.log(`Page ${page}: ${data.data.length} plays`);
console.log(`Total: ${data.meta.pagination.total} plays`);
return data;
}
// Get all plays (all pages)
async function getAllPlays(eventId) {
const allPlays = [];
let page = 1;
let hasMore = true;
while (hasMore) {
const response = await getPlays(eventId, page);
allPlays.push(...response.data);
hasMore = response.meta.pagination.hasNextPage;
page++;
}
return allPlays;
}
// Usage
getAllPlays('401772982').then(plays => {
console.log(`Fetched ${plays.length} total plays`);
});
```
--------------------------------
### Get All Teams for a League
Source: https://www.realtimesportsapi.com/docs/index
Retrieve a list of all teams participating in a specified sports league.
```APIDOC
## GET /sports/{sport}/leagues/{league}/teams
### Description
Get all teams for a league.
### Method
GET
### Endpoint
/sports/{sport}/leagues/{league}/teams
### Parameters
#### Path Parameters
- **sport** (string) - Required - The type of sport (e.g., "baseball").
- **league** (string) - Required - The league identifier (e.g., "mlb").
#### Query Parameters
None
#### Request Body
None
### Request Example
```bash
curl "https://realtimesportsapi.com/api/v1/sports/baseball/leagues/mlb/teams" \
-H "Authorization: Bearer YOUR_API_KEY"
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the request was successful.
- **data** (array) - An array of team objects.
- **name** (string) - Full name of the team.
- **abbreviation** (string) - Team abbreviation.
- **colors** (array) - Primary and secondary colors of the team (hex format).
- **logos** (object) - URLs for team logos.
- **venue** (object) - Information about the team's home venue.
- **records** (object) - Team's win-loss record.
- **standings** (object) - Team's position in the league standings.
#### Response Example
(Response structure not fully detailed, but includes team names, abbreviations, colors, logos, venue, records, and standings.)
```
--------------------------------
### Get Plays for an Event
Source: https://www.realtimesportsapi.com/docs/index
Retrieve a paginated list of plays that occurred during a specific sports event.
```APIDOC
## GET /sports/{sport}/leagues/{league}/events/{eventId}/plays
### Description
Get plays for an event (paginated - games can have 200+ plays).
### Method
GET
### Endpoint
/sports/{sport}/leagues/{league}/events/{eventId}/plays
### Parameters
#### Path Parameters
- **sport** (string) - Required - The type of sport (e.g., "football").
- **league** (string) - Required - The league identifier (e.g., "nfl").
- **eventId** (string) - Required - The unique identifier of the event.
#### Query Parameters
- **page** (integer) - Optional - Page number for pagination. Defaults to 1.
- **limit** (integer) - Optional - Number of plays per page. Defaults to 25, maximum is 100.
#### Request Body
None
### Request Example
```bash
curl "https://realtimesportsapi.com/api/v1/sports/football/leagues/nfl/events/401772982/plays?page=1&limit=25" \
-H "Authorization: Bearer YOUR_API_KEY"
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the request was successful.
- **data** (array) - An array of play objects.
- **id** (string) - Unique identifier for the play.
- **text** (string) - Description of the play (e.g., "B.Nix pass to P.Bryant for 12 yards").
- **type** (object) - Type of play.
- **id** (string) - Identifier for the play type.
- **text** (string) - Description of the play type (e.g., "Pass Reception").
- **period** (integer) - The period in which the play occurred.
- **clock** (object) - Game clock information for the play.
- **displayValue** (string) - Formatted display value of the clock.
- **situation** (object) - Game situation at the time of the play.
- **down** (integer) - Current down.
- **distance** (integer) - Yards to go for a first down.
- **yardLine** (integer) - The yard line on the field.
- **downDistanceText** (string) - Textual representation of the down and distance.
- **yardsGained** (integer) - Yards gained or lost on the play.
- **athletes** (array) - List of athletes involved in the play.
- **type** (string) - Role of the athlete in the play (e.g., "passer", "receiver").
- **order** (integer) - Order of involvement.
- **meta** (object) - Metadata for pagination.
- **pagination** (object)
- **page** (integer) - Current page number.
- **pageSize** (integer) - Number of items per page.
- **total** (integer) - Total number of items available.
- **totalPages** (integer) - Total number of pages.
- **hasNextPage** (boolean) - Indicates if there is a next page.
#### Response Example
```json
{
"success": true,
"data": [
{
"id": "40177298265",
"text": "B.Nix pass to P.Bryant for 12 yards",
"type": { "id": "24", "text": "Pass Reception" },
"period": 1,
"clock": { "displayValue": "14:56" },
"situation": {
"down": 1,
"distance": 10,
"yardLine": 26,
"downDistanceText": "1st & 10 at DEN 26"
},
"yardsGained": 12,
"athletes": [
{ "type": "passer", "order": 1 },
{ "type": "receiver", "order": 2 }
]
}
],
"meta": {
"pagination": {
"page": 1,
"pageSize": 25,
"total": 213,
"totalPages": 9,
"hasNextPage": true
}
}
}
```
```
--------------------------------
### Get Athletes by League
Source: https://www.realtimesportsapi.com/docs/index
Retrieves a paginated list of all athletes within a specified league and sport.
```APIDOC
## GET /sports/{sport}/leagues/{league}/athletes
### Description
Get all athletes for a league (paginated).
### Method
GET
### Endpoint
/sports/{sport}/leagues/{league}/athletes
### Parameters
#### Path Parameters
- **sport** (string) - Required - The slug or ID of the sport (e.g., "baseball").
- **league** (string) - Required - The slug or ID of the league (e.g., "mlb").
#### Query Parameters
- **page** (integer) - Optional - Page number for pagination. Defaults to 1.
- **limit** (integer) - Optional - Number of results per page. Defaults to 25.
#### Request Body
None
### Request Example
```
curl "https://realtimesportsapi.com/api/v1/sports/baseball/leagues/mlb/athletes?page=1&limit=25" \
-H "Authorization: Bearer YOUR_API_KEY"
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the request was successful.
- **data** (array) - An array of athlete objects.
- **id** (string) - The unique identifier for the athlete.
- **fullName** (string) - The full name of the athlete.
- **position** (string) - The athlete's position.
- **jerseyNumber** (string) - The athlete's jersey number.
- **team** (object) - Information about the athlete's current team.
- **name** (string) - Name of the team.
- **abbreviation** (string) - Abbreviation of the team.
- **headshot** (string) - URL for the athlete's headshot image.
- **age** (integer) - The age of the athlete.
- **statsAvailable** (boolean) - Indicates if stats are available for the athlete.
#### Response Example
```json
{
"success": true,
"data": [
{
"id": "30836",
"fullName": "Aaron Judge",
"position": "Outfielder",
"jerseyNumber": "99",
"team": {
"name": "New York Yankees",
"abbreviation": "NYY"
},
"headshot": "https://example.com/headshots/aaronjudge.jpg",
"age": 31,
"statsAvailable": true
}
// ... more athletes
]
}
```
```
--------------------------------
### Get Season Details by Year
Source: https://www.realtimesportsapi.com/docs/index
Retrieves detailed information for a specific season identified by its year.
```APIDOC
## GET /sports/{sport}/leagues/{league}/seasons/{year}
### Description
Get details for a specific season.
### Method
GET
### Endpoint
/sports/{sport}/leagues/{league}/seasons/{year}
### Parameters
#### Path Parameters
- **sport** (string) - Required - The slug or ID of the sport (e.g., "baseball").
- **league** (string) - Required - The slug or ID of the league (e.g., "mlb").
- **year** (integer) - Required - The year of the season.
#### Query Parameters
None
#### Request Body
None
### Request Example
```
curl "https://realtimesportsapi.com/api/v1/sports/baseball/leagues/mlb/seasons/2025" \
-H "Authorization: Bearer YOUR_API_KEY"
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the request was successful.
- **data** (object) - An object containing the season details.
- **year** (integer) - The year of the season.
- **displayName** (string) - The display name of the season.
- **seasonType** (string) - The current type of the season (e.g., "preseason", "regular", "postseason", "offseason").
- **startDate** (string) - The start date of the season.
- **endDate** (string) - The end date of the season.
- **seasonTypes** (array) - An array of objects detailing different season types and their dates.
- **type** (string) - The type of season segment.
- **startDate** (string) - Start date for this season type.
- **endDate** (string) - End date for this season type.
#### Response Example
```json
{
"success": true,
"data": {
"year": 2025,
"displayName": "2025 MLB Season",
"seasonType": "regular",
"startDate": "2025-03-27",
"endDate": "2025-09-28",
"seasonTypes": [
{
"type": "preseason",
"startDate": "2025-02-22",
"endDate": "2025-03-25"
},
{
"type": "regular",
"startDate": "2025-03-27",
"endDate": "2025-09-28"
},
{
"type": "postseason",
"startDate": "2025-09-30",
"endDate": "2025-10-29"
}
]
}
}
```
```
--------------------------------
### Webhook Payload Example for Realtime Sports API
Source: https://www.realtimesportsapi.com/docs/index
Illustrates the structure of a webhook payload sent by the Realtime Sports API for event notifications, such as score changes. It includes common headers and a JSON payload detailing the event, timestamp, and relevant game data.
```json
// Headers
X-Webhook-Signature: sha256=abc123... // HMAC SHA256 signature
X-Webhook-Event: event.score_change // Event type
Content-Type: application/json
User-Agent: RealtimeSportsAPI/1.0
// Payload
{
"event": "event.score_change",
"timestamp": "2024-01-15T20:30:00.000Z",
"data": {
"eventId": "401772982",
"sport": "football",
"league": "nfl",
"homeTeam": {
"id": "2",
"name": "Kansas City Chiefs",
"score": 24
},
"awayTeam": {
"id": "3",
"name": "Buffalo Bills",
"score": 17
},
"status": {
"type": {
"id": "1",
"name": "STATUS_IN_PROGRESS",
"state": "in",
"completed": false
},
"period": 3,
"clock": {
"value": 1200,
"displayValue": "20:00"
}
}
}
}
```
--------------------------------
### Get NFL Event Plays with Pagination
Source: https://www.realtimesportsapi.com/docs/index
Fetches plays for a specific NFL event, supporting pagination. You can specify the page number and the number of plays per page (limit). Requires an API key.
```cURL
curl "https://realtimesportsapi.com/api/v1/sports/football/leagues/nfl/events/401772982/plays?page=1&limit=25" \
-H "Authorization: Bearer YOUR_API_KEY"
```
--------------------------------
### Get Live NFL Games with Real-Time Sports API
Source: https://www.realtimesportsapi.com/docs/index
Retrieves live NFL (American Football) games and prints the scores for each game. This function requires the 'api' object and specifies 'football' as the sport and 'nfl' as the league.
```python
nfl_games = api.get_live_games('football', 'nfl')
for game in nfl_games:
print(f"{game['name']}: {game['awayTeam']['score']} - {game['homeTeam']['score']}")
```
--------------------------------
### Discover Sports and Leagues (JavaScript)
Source: https://www.realtimesportsapi.com/docs/index
Demonstrates how to discover available sports and leagues using the API. It fetches all sports and then specifically the football leagues. Requires an API key.
```JavaScript
const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://realtimesportsapi.com/api/v1';
// Discover sports and leagues
async function discoverAPI() {
// Get all sports
const sports = await fetch(`${BASE_URL}/sports`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
}).then(r => r.json());
console.log('Sports:', sports.data);
// Get football leagues
const leagues = await fetch(`${BASE_URL}/sports/football/leagues`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
}).then(r => r.json());
console.log('Leagues:', leagues.data);
}
discoverAPI();
```
--------------------------------
### Python Client Library
Source: https://www.realtimesportsapi.com/docs/index
This section provides a Python client library for interacting with the Realtime Sports API. It includes methods for fetching sports, leagues, live games, and plays.
```APIDOC
## Python Client Library
### Description
A Python client library to interact with the Realtime Sports API.
### Usage
```python
import requests
API_KEY = 'YOUR_API_KEY'
BASE_URL = 'https://realtimesportsapi.com/api/v1'
class RealtimeSportsAPI:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = BASE_URL
self.headers = {'Authorization': f'Bearer {api_key}'}
def get_sports(self):
"""Get all available sports"""
response = requests.get(f'{self.base_url}/sports', headers=self.headers)
return response.json()['data']
def get_leagues(self, sport):
"""Get leagues for a sport"""
response = requests.get(
f'{self.base_url}/sports/{sport}/leagues',
headers=self.headers
)
return response.json()['data']
def get_live_games(self, sport, league):
"""Get live games for a league"""
response = requests.get(
f'{self.base_url}/sports/{sport}/leagues/{league}/events/live',
headers=self.headers
)
return response.json()['data']
def get_plays(self, sport, league, event_id, page=1, limit=25):
"""Get plays for an event (paginated)"""
response = requests.get(
f'{self.base_url}/sports/{sport}/leagues/{league}/events/{event_id}/plays',
params={'page': page, 'limit': limit},
headers=self.headers
)
return response.json()
# Usage
api = RealtimeSportsAPI(API_KEY)
sports = api.get_sports()
print(sports)
leagues = api.get_leagues('nfl')
print(leagues)
live_games = api.get_live_games('nfl', 'NFL')
print(live_games)
# Assuming you have an event_id from live_games
# plays = api.get_plays('nfl', 'NFL', 'some_event_id')
# print(plays)
```
### Endpoints Covered
#### GET /sports
##### Description
Get a list of all available sports.
##### Response Example (200 OK)
```json
{
"data": [
{
"id": "nfl",
"name": "National Football League"
},
{
"id": "nba",
"name": "National Basketball Association"
}
]
}
```
#### GET /sports/{sport}/leagues
##### Description
Get a list of leagues for a specific sport.
##### Parameters
* **sport** (string) - Required - The ID of the sport (e.g., `nfl`).
##### Response Example (200 OK)
```json
{
"data": [
{
"id": "NFL",
"name": "NFL"
},
{
"id": "NCAA_FOOTBALL",
"name": "NCAA Football"
}
]
}
```
#### GET /sports/{sport}/leagues/{league}/events/live
##### Description
Get a list of live games for a specific league.
##### Parameters
* **sport** (string) - Required - The ID of the sport (e.g., `nfl`).
* **league** (string) - Required - The ID of the league (e.g., `NFL`).
##### Response Example (200 OK)
```json
{
"data": [
{
"id": "game_123",
"name": "Team A vs Team B",
"status": "live"
}
]
}
```
#### GET /sports/{sport}/leagues/{league}/events/{event_id}/plays
##### Description
Get a list of plays for a specific event, with pagination.
##### Parameters
* **sport** (string) - Required - The ID of the sport (e.g., `nfl`).
* **league** (string) - Required - The ID of the league (e.g., `NFL`).
* **event_id** (string) - Required - The ID of the event.
* **page** (integer) - Optional - The page number for pagination (default: 1).
* **limit** (integer) - Optional - The number of items per page (default: 25).
##### Response Example (200 OK)
```json
{
"data": [
{
"id": "play_abc",
"text": "Touchdown!"
}
],
"pagination": {
"currentPage": 1,
"totalPages": 5,
"totalItems": 100
}
}
```
```
--------------------------------
### Establish WebSocket Connection (JavaScript)
Source: https://www.realtimesportsapi.com/docs/index
JavaScript code to establish a WebSocket connection to the real-time data server using the obtained authentication token. It includes handlers for connection events.
```javascript
const ws = new WebSocket(`${data.url}?token=${data.token}`);
ws.onopen = () => {
console.log('WebSocket connected');
};
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
console.log('Received:', message);
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
ws.onclose = () => {
console.log('WebSocket disconnected');
};
```
--------------------------------
### Get Single Athlete by ID - cURL Example
Source: https://www.realtimesportsapi.com/docs/index
Retrieves details for a specific athlete using their unique ID within a league and sport. The response includes name, position, team affiliation, and stats. Authentication is mandatory.
```curl
curl "https://realtimesportsapi.com/api/v1/sports/baseball/leagues/mlb/athletes/30836" \
-H "Authorization: Bearer YOUR_API_KEY"
```