- What is the API for sports events and how does it help create a championship table widget
- Which sports league APIs to choose and where to get data for the championship table
- How to get the championship table through the API: examples of requests and parameters
- How to create a championship table widget with auto-refresh on the website using JavaScript
- How to connect the championship table widget via API in WordPress and other CMS
- How to configure caching and update frequency for the championship table through the API
- Limitations and limits of the sports statistics API when creating a championship table widget
What is the API for sports events and how does it help create a championship table widget
The sports events API is a programming interface that allows you to obtain structured data about matches, tournaments, teams, scores, and odds in real-time as closely as possible. Instead of manually updating results or parsing websites, you request ready-made JSON data and automatically build any interface based on it: from a simple block with a tournament table to a complex analytical dashboard.
On the platform api-sport.ru popular sports are combined in one API: football, hockey, basketball, tennis, table tennis, esports, and other disciplines that are constantly being added. For each sport, endpoints with matches, tournaments, and seasons are available. This allows you to form a championship table for any league: local championship, international tournament, or amateur tournament, if it is represented in the database.
Thanks to the fact that the match responses contain not only the score but also additional fields (for example, estado, minutoDelPartidoActual, extended statistics and odds oddsBase), you can build a championship table widget with auto-updating and additional metrics: team form, live indicator, highlighting matches in play. In upcoming updates, the service plans to add WebSocket and AI tools, which will allow updating the table in push notification mode without periodic requests and automatically highlighting key events (winning streaks, important head-to-head meetings) directly in your widget’s interface.
Which sports league APIs to choose and where to get data for the championship table
The first step in creating a championship table widget is selecting the sport and the desired tournament. The API provides a universal endpoint /v2/deporte, that returns a list of all available disciplines. For each discipline, it specifies slug (for example, fútbol, hockey sobre hielo, baloncesto), which is then used in the path of all requests. This allows for uniform handling of different sports without changing the architecture of your code.
After selecting the desired sport, you receive a list of countries and regions through the endpoint /v2/{sportSlug}/categorías. The response includes categories with their identifiers and the field torneosPredeterminados — recommended tournaments by interface languages. This is a convenient starting point: you can immediately take popular leagues (for example, national championships and major international tournaments) and show them to the user as options in the widget settings.
To move from a category to a specific championship, use the method /v2/{sportSlug}/categorías/{categoryId}. It returns a list of tournaments and available seasons. Knowing the tournament ID and season ID, you can further request matches and based on them calculate the tournament table. An example request to get categories for football:
curl -X GET 'https://api.api-sport.ru/v2/football/categories' \ -H 'Authorization: YOUR_API_KEY'
Based on this data, you can give the user a choice: from which tournament to build the championship table, which seasons are available, and also provide support for multiple leagues in one widget (for example, tab switching: national championship, country cup, international tournament).
How to get the championship table through the API: examples of requests and parameters
The provided documentation focuses on matches, tournaments, and seasons. A typical and flexible way to form the championship table is to request a list of matches for the selected tournament and season, and then calculate points and goal difference on your side. For this, you need the tournament and season IDs, which can be obtained through the endpoints. /v2/{sportSlug}/torneo/{tournamentId} и /v2/{sportSlug}/torneo/{tournamentId}/temporadas.
Next, you request a list of tournament matches filtered by season. For a football championship, this may look like:
curl -X GET \ 'https://api.api-sport.ru/v2/football/matches?tournament_id=7&season_id=72514&status=finished' \ -H 'Authorization: YOUR_API_KEY'
In the response, you receive an array partidos, where for each match there are teams homeTeam и awayTeam, as well as the score in the object puntajeLocal и puntajeVisitante. Based on this data, it is not difficult to calculate wins, draws, losses, points earned, goal difference, and form the table. Below is a simplified example in JavaScript that aggregates results into the standings structure:
function buildStandings(matches) {
const table = new Map();
for (const match of matches) {
const home = match.homeTeam.name;
const away = match.awayTeam.name;
const hs = match.homeScore.current;
const as = match.awayScore.current;
if (!table.has(home)) table.set(home, { team: home, played: 0, win: 0, draw: 0, lose: 0, gf: 0, ga: 0, pts: 0 });
if (!table.has(away)) table.set(away, { team: away, played: 0, win: 0, draw: 0, lose: 0, gf: 0, ga: 0, pts: 0 });
const h = table.get(home);
const a = table.get(away);
h.played++; a.played++;
h.gf += hs; h.ga += as;
a.gf += as; a.ga += hs;
if (hs > as) { h.win++; a.lose++; h.pts += 3; }
else if (hs < as) { a.win++; h.lose++; a.pts += 3; }
else { h.draw++; a.draw++; h.pts++; a.pts++; }
}
return Array.from(table.values()).sort((x, y) => y.pts - x.pts || (y.gf - y.ga) - (x.gf - x.ga));
}
The API key for making such requests is issued in tu cuenta personal en api-sport.ru. For production solutions, it is recommended to call the API from your server, where the key is stored in a secure environment, and the frontend accesses your proxy endpoint. This way, you can flexibly manage the request frequency and caching without exposing the key in the browser.
How to create a championship table widget with auto-refresh on the website using JavaScript
The auto-updating championship table widget is built on a simple scheme: periodically request your server endpoint (which in turn calls the sports events API), recalculate the table, and update the DOM. This approach scales well, and with the transition to WebSocket, which is planned on the API side, you will be able to replace polling with push notifications and update the table without unnecessary requests.
The minimal HTML markup for the widget can look like this: a container with a header and an empty <tbody>, where JavaScript will insert rows with teams, points, and goal difference. Next, you will implement the data loading and rendering function. Below is an example of a simple implementation in pure JavaScript, where the frontend calls your backend at the address /api/standings:
<div id='standings-widget'>
<h3>Таблица чемпионата</h3>
<table>
<thead>
<tr>
<th>#</th>
<th>Команда</th>
<th>И</th>
<th>О</th>
<th>Мячи</th>
</tr>
</thead>
<tbody id='standings-body'></tbody>
</table>
</div>
async function loadStandings() {
const res = await fetch('/api/standings'); // ваш бэкенд обращается к https://api.api-sport.ru
const data = await res.json(); // ожидаем массив строк таблицы
const tbody = document.getElementById('standings-body');
tbody.innerHTML = '';
data.forEach((row, index) => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${index + 1}</td>
<td>${row.team}</td>
<td>${row.played}</td>
<td>${row.pts}</td>
<td>${row.gf}:${row.ga}</td>`;
tbody.appendChild(tr);
});
}
// Первичная загрузка и автообновление каждые 60 секунд
loadStandings();
setInterval(loadStandings, 60000);
On your server side, this function can implement the algorithm from the previous section: request matches from the API, calculate the table, and return the already prepared structure. This pattern allows you to easily add new features (for example, displaying the average total, the last 5 matches, current odds from the field oddsBase) without changes to the client code: the frontend will continue to receive an array of objects with the necessary fields, and you will only expand it on your side.
How to connect the championship table widget via API in WordPress and other CMS
In WordPress and popular CMS, it is most convenient to connect the championship table through your own shortcode or widget, which outputs the HTML container and connects JavaScript for data loading. The sports events API, in this case, remains «behind the scenes» — your server code (PHP, Node.js, or another stack) accesses it, and a ready-made JSON response is output to the page, which is rendered into the table.
In WordPress, you can create a simple shortcode that inserts the table markup and connects the auto-update script. The server part of the shortcode can call your internal REST endpoint, which, in turn, uses data from api-sport.ru. An example of a minimal implementation of a shortcode in PHP:
function api_sport_standings_shortcode( $atts ) {
$atts = shortcode_atts([
'league' => '7', // ID турнира
'season' => '72514', // ID сезона
], $atts, 'api_sport_standings' );
ob_start();
?>
<div id='standings-widget' data-league='<?php echo esc_attr( $atts['league'] ); ?>' data-season='<?php echo esc_attr( $atts['season'] ); ?>'>
<h3>Таблица чемпионата</h3>
<table>
<thead>
<tr>
<th>#</th><th>Команда</th><th>И</th><th>О</th><th>Мячи</th>
</tr>
</thead>
<tbody id='standings-body'></tbody>
</table>
</div>
<?php
return ob_get_clean();
}
add_shortcode( 'api_sport_standings', 'api_sport_standings_shortcode' );
Next, you register the script that makes an AJAX call to your REST route (for example, /wp-json/api-sport/v1/standings). This route in PHP requests matches from the sports events API for the required sport and tournament, calculates the table, and returns JSON. A similar scheme can be implemented in other CMS and frameworks: in 1C-Bitrix, Drupal, Laravel, Django. The key principles are the same: the API key is stored on the server, data is cached, and the frontend receives clean and lightweight JSON for visualization.
How to configure caching and update frequency for the championship table through the API
Proper caching is a critical element when working with any external API. The championship table does not need to be updated every second: points change only when matches finish or live events occur. Therefore, the optimal strategy is to store the calculated table in server cache and refresh it only when necessary. This reduces the load on both your server and the sports events API, as well as protects against exceeding limits.
For WordPress, it is convenient to use the Transients API or object cache: you save the ready table (an array with teams and statistics) for 30-60 seconds for live mode and for several minutes outside of match windows. In other stacks, you can use Redis, Memcached, or file cache. The typical algorithm is: upon a frontend request, you first check the cache; if the data exists and is not outdated, you simply return it. If the cache is empty or expired, you make a request to https://api.api-sport.ru, recalculate the table, and update the cache.
The update frequency is useful to adapt to the context: during tours and live matches, it makes sense to update data more frequently (for example, every 30-60 seconds), while during breaks between tours — less frequently (once every 5-10 minutes). With the future introduction of WebSocket on the API side, you will be able to restructure the logic: the cache will be invalidated by event (for example, score change or match completion), rather than by timer. This will make the championship table widget more accurate and simultaneously even less resource-intensive.
Limitations and limits of the sports statistics API when creating a championship table widget
When designing the widget, it is important to consider the limits and restrictions of the API. In practice, this means: do not request unnecessary data, use filters, and handle errors correctly. The endpoint /v2/{sportSlug}/partidos allows filtering matches by torneo_id, temporada_id, equipo_id, date, and status. This helps avoid loading the entire event feed for the sport and only getting what is needed for calculating a specific championship table.
It is also important to monitor the number of requests and distribute the load: for each page with a widget, there is no need to directly call the external API. It is much more efficient when all widgets read data from your internal cache, which is periodically synchronized with the sports events API. This approach minimizes the risk of hitting request limits and ensures stable website operation even during peak traffic.
Be sure to implement error handling and edge cases: API unavailability, network timeouts, exceeding limits, invalid key. Below is an example of a simplified request to your backend with careful error handling on the frontend:
async function safeLoadStandings() {
try {
const res = await fetch('/api/standings');
if (!res.ok) {
console.error('Ошибка API, статус:', res.status);
return;
}
const data = await res.json();
// далее рендер таблицы
} catch (e) {
console.error('Сетевая ошибка при загрузке таблицы чемпионата:', e);
}
}
Detailed information about rates, limits, and usage recommendations is usually available in the documentation and personal account. When designing the championship table widget based on the API, allow for performance and stability: use caching, compressed responses, reasonable update frequency, and consider expanding functionality (connecting bookmaker odds, live statistics, future WebSocket channels, and AI suggestions).




