Skip to main content

SportRadar Functions

Fetch NFL data from the SportRadar API. Get teams, rosters, and player profiles for sports-focused workflows.

Overview

The SportRadar integration provides four NFL functions:

  • nflGetTeams() - Get all NFL teams
  • nflGetTeamProfile() - Get full team profile with roster
  • nflGetTeamRoster() - Get simplified team roster
  • nflGetPlayerProfile() - Get player profile

Configuration

API Key Setup

The SportRadar API key can be configured in three ways (checked in order):

  1. Entity Argument (camelCase)

    • Set sportradarApiKey as an entity argument
  2. Environment Variable (via Admin Console)

    • Set SPORTRADAR_API_KEY in Admin → Settings → Variables
  3. System Environment Variable

    • Set SPORTRADAR_API_KEY in the deployment environment

API Type

By default, the production API is used. For trial accounts:

  • Entity Argument: Set sportradarApiType to "trial"
  • Environment Variable: Set SPORTRADAR_API_TYPE to "trial"

Getting an API Key

  1. Go to SportRadar Developer Portal
  2. Sign up for an account
  3. Create an application
  4. Select the NFL API
  5. Copy your API key

Functions

nflGetTeams

Get all NFL teams.

Signature:

async function nflGetTeams(): Promise<Array<{
id: string;
name: string;
market: string;
alias: string;
sr_id: string;
}>>

Returns: Array of all NFL teams

Example:

const teams = await nflGetTeams();

print('Found', teams.length, 'NFL teams');

// Find a specific team
const chiefs = teams.find(t => t.alias === 'KC');
print('Chiefs ID:', chiefs.id);

// List all teams
for (const team of teams) {
print(team.market, team.name, '(' + team.alias + ')');
}

nflGetTeamProfile

Get full team profile including roster, venue, and coaches.

Signature:

async function nflGetTeamProfile(
teamId: string
): Promise<{
id: string;
name: string;
market: string;
alias: string;
venue: object;
coaches: object[];
players: object[];
// ... more fields
}>

Parameters:

ParameterTypeDescription
teamIdstringSportRadar team ID

Returns: Full team profile object

Example:

const teamId = '6680d28d-d4d2-49f6-aace-5292d3ec02c2'; // Chiefs

const profile = await nflGetTeamProfile(teamId);

print('Team:', profile.market, profile.name);
print('Venue:', profile.venue?.name);
print('Players on roster:', profile.players?.length);

nflGetTeamRoster

Get simplified team roster (just player data).

Signature:

async function nflGetTeamRoster(
teamId: string
): Promise<Array<{
id: string;
name: string;
firstName: string;
lastName: string;
position: string;
primaryPosition: string;
jersey: string;
status: string;
experience: number;
college: string;
height: number;
weight: number;
birthDate: string;
sr_id: string;
}>>

Parameters:

ParameterTypeDescription
teamIdstringSportRadar team ID

Returns: Array of players with key attributes

Example:

const roster = await nflGetTeamRoster(teamId);

print('Roster size:', roster.length);

// Find quarterbacks
const qbs = roster.filter(p => p.position === 'QB');
for (const qb of qbs) {
print('QB:', qb.name, '#' + qb.jersey);
}

// Find all active players
const active = roster.filter(p => p.status === 'ACT');
print('Active players:', active.length);

nflGetPlayerProfile

Get detailed player profile including career stats.

Signature:

async function nflGetPlayerProfile(
playerId: string
): Promise<{
id: string;
name: string;
first_name: string;
last_name: string;
position: string;
team: object;
seasons: object[];
// ... career data
}>

Parameters:

ParameterTypeDescription
playerIdstringSportRadar player ID

Returns: Full player profile with career data

Example:

const playerId = 'ede260be-5ae6-4a06-887b-e4a130932705'; // Example ID

const player = await nflGetPlayerProfile(playerId);

print('Player:', player.name);
print('Position:', player.position);
print('Team:', player.team?.name);
print('Experience:', player.experience, 'years');

Complete Examples

Example 1: Game Event Enrichment

Enrich incoming game events with player/team data:

Event Condition:

{
"type": "rule",
"field": "message.sport",
"comparison": "equals",
"value": "nfl"
}

Action Script:

// Extract event details from message
const eventType = message.eventType;
const playerId = message.playerId;
const teamAlias = message.teamAlias;

print('Processing', eventType, 'event');

// Get player info if available
let playerInfo = null;
if (playerId) {
try {
playerInfo = await nflGetPlayerProfile(playerId);
print('Player:', playerInfo.name, '-', playerInfo.position);
} catch (e) {
print('Could not fetch player:', e.message);
}
}

// Get team info if available
let teamInfo = null;
if (teamAlias) {
const teams = await nflGetTeams();
const team = teams.find(t => t.alias === teamAlias);
if (team) {
teamInfo = await nflGetTeamProfile(team.id);
print('Team:', teamInfo.market, teamInfo.name);
}
}

// Enrich output for downstream processing
output = {
originalEvent: message,
player: playerInfo ? {
name: playerInfo.name,
position: playerInfo.position,
team: playerInfo.team?.name
} : null,
team: teamInfo ? {
name: teamInfo.market + ' ' + teamInfo.name,
venue: teamInfo.venue?.name
} : null
};

Example 2: Player Lookup for Chatbot

Process user questions about NFL players:

Prompt Template:

User is asking about: {{message.query}}
Player data: {{playerData}}

Based on the player data above, answer the user's question naturally.
If the data doesn't contain the answer, say so politely.

Pre-Prompt Action Script:

// Extract player name from user query
const query = message.query.toLowerCase();

// Get all teams to search rosters
const teams = await nflGetTeams();

let foundPlayer = null;
let searchedTeams = 0;

// Search through team rosters (expensive - optimize in production)
for (const team of teams) {
searchedTeams++;

try {
const roster = await nflGetTeamRoster(team.id);

// Simple name matching
const match = roster.find(p =>
p.name.toLowerCase().includes(query) ||
query.includes(p.name.toLowerCase())
);

if (match) {
// Get full profile
foundPlayer = await nflGetPlayerProfile(match.id);
foundPlayer.teamName = team.market + ' ' + team.name;
print('Found player:', match.name, 'on', team.name);
break;
}

} catch (e) {
print('Error searching', team.name, ':', e.message);
}

// Limit search to avoid timeout
if (searchedTeams >= 10) {
print('Searched 10 teams, stopping');
break;
}
}

// Store for prompt
output = {
playerData: foundPlayer ? JSON.stringify(foundPlayer, null, 2) : 'Player not found'
};

Example 3: Daily Roster Report

Generate a summary of team roster changes:

Action Script:

const teamAlias = message.team || 'KC';

// Find team
const teams = await nflGetTeams();
const team = teams.find(t => t.alias === teamAlias);

if (!team) {
print('Team not found:', teamAlias);
output = { error: 'Team not found' };
} else {
print('Generating roster report for', team.market, team.name);

// Get current roster
const roster = await nflGetTeamRoster(team.id);

// Organize by position
const byPosition = {};
for (const player of roster) {
const pos = player.position || 'Unknown';
if (!byPosition[pos]) byPosition[pos] = [];
byPosition[pos].push(player);
}

// Generate summary
const summary = {
team: team.market + ' ' + team.name,
totalPlayers: roster.length,
activeCount: roster.filter(p => p.status === 'ACT').length,
injuredReserve: roster.filter(p => p.status === 'IR').length,
practiceSquad: roster.filter(p => p.status === 'PUP').length,
positionBreakdown: Object.entries(byPosition).map(([pos, players]) => ({
position: pos,
count: players.length,
players: players.map(p => p.name).slice(0, 3) // Top 3 names
}))
};

print('Report generated. Total players:', summary.totalPlayers);
output = summary;
}

Example 4: Error Handling

Robust SportRadar API usage:

Action Script:

// Check configuration first
if (!SPORTRADAR_API_KEY && typeof sportradarApiKey === 'undefined') {
print('ERROR: SportRadar API key not configured');
output = { success: false, error: 'api_key_not_configured' };
} else {
try {
// Attempt API call
const teams = await nflGetTeams();
print('Successfully fetched', teams.length, 'teams');

output = {
success: true,
teamCount: teams.length,
teams: teams.map(t => ({ alias: t.alias, name: t.market + ' ' + t.name }))
};

} catch (error) {
print('SportRadar API error:', error.message);

// Categorize error
let errorType = 'unknown';
if (error.message.includes('401')) errorType = 'auth_failed';
if (error.message.includes('403')) errorType = 'forbidden';
if (error.message.includes('429')) errorType = 'rate_limited';

output = {
success: false,
error: errorType,
message: error.message
};
}
}

Example 5: Caching with STM

Cache team data to reduce API calls:

Action Script:

const teamAlias = message.teamAlias;
const cacheKey = 'team-' + teamAlias;
const cacheTTL = 60 * 60 * 1000; // 1 hour in ms

// Check cache first
let teamData = await stmRetrieve(['sportradar-cache'], cacheKey + '.json');

if (teamData && Date.now() - teamData.cachedAt < cacheTTL) {
print('Cache hit for', teamAlias);
output = teamData.data;
} else {
print('Cache miss, fetching from API');

// Find and fetch team
const teams = await nflGetTeams();
const team = teams.find(t => t.alias === teamAlias);

if (team) {
const profile = await nflGetTeamProfile(team.id);

// Cache the result
await stmStore(['sportradar-cache'], {
cachedAt: Date.now(),
data: profile
}, cacheKey + '.json');

print('Cached team data for', teamAlias);
output = profile;
} else {
output = { error: 'Team not found' };
}
}

Troubleshooting

"SportRadar API key not configured"

Cause: No API key found in any configuration source

Solution:

  1. Add SPORTRADAR_API_KEY to Admin → Settings → Variables
  2. Or set sportradarApiKey as an entity argument

"SportRadar API error 401"

Cause: Invalid or expired API key

Solution:

  • Verify your API key in the SportRadar developer portal
  • Check if using trial vs production key with correct API type

"SportRadar API error 403"

Cause: API key doesn't have access to this endpoint

Solution:

  • Ensure your SportRadar subscription includes NFL data
  • Check rate limits haven't been exceeded

"teamId is required" or "playerId is required"

Cause: Calling function without required parameter

Solution:

// Get team ID first
const teams = await nflGetTeams();
const team = teams.find(t => t.alias === 'KC');

// Then use the ID
const roster = await nflGetTeamRoster(team.id);

Best Practices

  1. Cache aggressively - Team/roster data doesn't change often

    // Cache for 1 hour using STM
    await stmStore(['cache'], data, 'teams.json');
  2. Limit searches - Don't search all 32 teams if you can narrow it down

    // If you know the team, skip the search
    if (message.teamId) {
    const roster = await nflGetTeamRoster(message.teamId);
    }
  3. Handle missing data - Players move, IDs change

    try {
    const player = await nflGetPlayerProfile(id);
    } catch (e) {
    print('Player not found or API error');
    }
  4. Use simplified roster - nflGetTeamRoster() is lighter than full profile

    // For just player names/positions
    const roster = await nflGetTeamRoster(teamId);

    // Only get full profile when needed
    const detailed = await nflGetTeamProfile(teamId);
  5. Log API calls - For debugging and monitoring

    print('Fetching roster for team:', teamId);
    const roster = await nflGetTeamRoster(teamId);
    print('Fetched', roster.length, 'players');