- What is the sports events API and how to use it for live football results
- Which API to choose for live football results for a Telegram bot
- How to get a key and set up access to the live football results API
- Examples of requests to the football match API for a Telegram bot with live scoring
- How to create a Telegram bot with live football results in Python step-by-step guide
- How to set up notifications for goals and scores via a Telegram bot using the football API
- Limitations, caps, and costs of using the live football results API
What is the sports events API and how to use it for live football results
The sports events API allows you to obtain data about football matches directly from the statistics provider’s servers in a structured format. Instead of parsing websites or manually updating scores, you make a request to the REST endpoint and receive up-to-date information about the match in response: status, minute of the match, score by halves, lineups, cards, goals, and much more. The platform api-sport.ru provides a unified interface for different sports, and for football, a complete set of data is available to build a convenient Telegram bot with live results.
Technically, working with the API comes down to sending HTTP requests to the base address of the sport. For football, this path is: https://api.api-sport.ru/v2/football. Then you choose the desired resource, for example, matches, and supplement the request with filtering parameters. In the response, you receive a JSON object that is easily processed in any programming language. In matches, fields such as currentMatchMinute for the current minute, liveEvents with a timeline of events (goals, cards, substitutions), matchStatistics with detailed statistics on shots, possession, and duels, as well as oddsBase with bookmaker odds and highlights with links to video reviews are available.
- Getting a list of matches for today or for a specific date via the endpoint v2/football/matches.
- Accessing detailed information about a match by its identifier via v2/football/matches/{matchId}.
- Loading match events in real-time via v2/football/matches/{matchId}/events.
- Using live data to generate notifications about goals, cards, and halftime endings in Telegram.
With this approach, you can build your products on top of the infrastructure Sports events API, without worrying about data collection and verification. The Telegram bot with live football results becomes just another client to this API: it regularly polls the endpoints, analyzes changes, and sends convenient messages to the user. In the future, you will be able to add other sports, betting odds, and use new platform features, such as WebSocket updates and AI functionality as they become available, without changing the architecture.
Which API to choose for live football results for a Telegram bot
When choosing an API for live football results, it is important to consider three key parameters: data completeness, update speed, and operational stability. For a Telegram bot, it is critical that score changes and match events reach your code with minimal delay, and that the response structure is predictable and stable. The API at https://api.api-sport.ru implements a modern REST architecture, a unified format for different sports, and a detailed match model that includes liveEvents, matchStatistics, team lineups, and bookmaker odds through oddsBase.
Another important criterion for choosing an API for the bot is the convenience of filtering. The endpoint v2/football/matches in the service api-sport.ru supports the status parameter to fetch only live matches, tournament_id with the ability to pass a list of tournaments separated by commas, team_id to get matches for a specific team, as well as filtering by categories (countries) and seasons. This allows you to avoid loading unnecessary data and save requests by forming exactly the set of matches that are of interest to your bot’s users.
- A unified JSON response format for football, hockey, basketball, tennis, table tennis, and esports.
- The presence of the fields currentMatchMinute, liveEvents, and matchStatistics in the match object, necessary for quality live notifications.
- Access to oddsBase with basic betting markets for integration with betting functionality.
- Development plans: WebSocket stream for instant updates and AI tools for analytics and notification personalization.
For the Telegram bot, a flexible REST API becomes the optimal choice, which already covers all basic scenarios: displaying live scores, match event history, statistics, and odds. In the future, you will be able to switch part of the logic to WebSocket when this capability becomes available on the platform, but the architecture of your bot will remain the same: it will still receive structured data from a reliable source and deliver it to users in a readable format.
How to get a key and set up access to the live football results API
To work with live data of football matches via the API, you need a personal access key. It is used for authorizing all requests and allows the system to distribute the load, account for limits, and ensure security. You can obtain the key in the personal account. after registering on the platform. The process is simple: you create an account, confirm your email, add a project, and receive an API key string, which you then pass in the Authorization header for each request to https://api.api-sport.ru.
After obtaining the key, client configuration comes down to adding the required header to your HTTP requests. For football, the basic path will be: v2/football. To, for example, get all matches in the inprogress status, you send a GET request to the resource v2/football/matches with the status parameter and the Authorization header. In practice, it is more convenient to place the key in an environment variable and not store it in the repository code. Below is an example of a basic request in Python using the requests library.
import os
import requests
API_KEY = os.getenv('SPORT_API_KEY', 'ВАШ_API_КЛЮЧ')
BASE_URL = 'https://api.api-sport.ru/v2/football/matches'
headers = {
'Authorization': API_KEY
}
params = {
'status': 'inprogress' # только матчи, идущие прямо сейчас
}
response = requests.get(BASE_URL, headers=headers, params=params)
response.raise_for_status()
data = response.json()
print(data.get('totalMatches'), 'live-матчей найдено')
On the Telegram bot side, this code is usually placed in a separate module so that all logic for working with the external API is centralized. It is important to monitor error handling: with an incorrect or expired key, the server will return status 401, with incorrect request parameters — 400, and with internal problems — 500. Proper handling of these cases will allow the bot to remain stable and informatively report errors without interrupting work for other users.
Examples of requests to the football match API for a Telegram bot with live scoring
Practical work with the API of live football results in the Telegram bot is usually built around several main endpoints. The first basic request is to get a list of matches that are currently ongoing. For this, the resource v2/football/matches is used with the status parameter equal to inprogress. Additionally, you can limit the selection by tournaments through tournament_id, passing one or more tournament identifiers separated by commas, or by a specific team through team_id.
Below is an example of a function in Python that calls the API and returns a list of live matches in a convenient format for subsequent sending to Telegram. Note how the request parameters and match response fields are used: tournament.name, homeTeam.name, awayTeam.name, as well as the homeScore and awayScore objects with the current score.
import requests
API_KEY = 'ВАШ_API_КЛЮЧ'
BASE_URL = 'https://api.api-sport.ru/v2/football/matches'
headers = {
'Authorization': API_KEY
}
def get_live_matches(tournament_ids=None):
params = {
'status': 'inprogress'
}
if tournament_ids:
params['tournament_id'] = ','.join(str(tid) for tid in tournament_ids)
response = requests.get(BASE_URL, headers=headers, params=params)
response.raise_for_status()
data = response.json()
matches = []
for match in data.get('matches', []):
home = match['homeTeam']['name']
away = match['awayTeam']['name']
score = f"{match['homeScore']['current']}:{match['awayScore']['current']}"
minute = match.get('currentMatchMinute')
matches.append({
'id': match['id'],
'title': f'{home} — {away}',
'score': score,
'minute': minute,
'tournament': match['tournament']['name']
})
return matches
When a user selects a specific match, the bot requires more detailed information: lineups, advanced statistics, liveEvents. For this, the resource v2/football/matches/{matchId} is used, and if necessary, a separate endpoint v2/football/matches/{matchId}/events. In the response, you receive a detailed match structure, including liveEvents, where for each event the type (goal, card, etc.), team, players, and score after the event are specified. This data is perfect for forming a compact text summary and timeline, which are sent to the user upon request or on a schedule.
How to create a Telegram bot with live football results in Python step-by-step guide
Creating a Telegram bot with live football results in Python can be divided into several clear steps. First, you register the bot through the official BotFather bot in Telegram and receive an access token. Then you set up the environment: install Python, create a virtual environment, add dependencies such as the python-telegram-bot or aiogram library, as well as requests for working with the sports events API. At this stage, it is important to already have the API key obtained in the personal account., and save it in an environment variable.
Next, you implement the basic framework of the bot: a handler for the start command, a simple command like /live, which will request the API for a list of current matches through the endpoint v2/football/matches and send them to the user. Inside the handler, you call the function to access the API (an example of such a function is provided above), format the text, and send messages through the Telegram API methods. For small projects, long polling mode is sufficient, where the bot periodically polls Telegram servers, but for high-load solutions, webhooks and a separate server can be used.
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
from live_api_client import get_live_matches # ваш модуль работы с API
BOT_TOKEN = 'ВАШ_TELEGRAM_ТОКЕН'
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text('Привет! Я бот live-результатов футбола.')
async def live(update: Update, context: ContextTypes.DEFAULT_TYPE):
matches = get_live_matches()
if not matches:
await update.message.reply_text('Сейчас нет live-матчей.')
return
lines = []
for m in matches:
minute = f"{m['minute']}-я минута" if m['minute'] else 'матч начался'
lines.append(f"{m['title']} — {m['score']} ({minute})")
await update.message.reply_text(''.join(lines))
if __name__ == '__main__':
app = ApplicationBuilder().token(BOT_TOKEN).build()
app.add_handler(CommandHandler('start', start))
app.add_handler(CommandHandler('live', live))
app.run_polling()
Once the basic functionality is up and running, you can gradually develop the bot: add tournament and team selection, keyboards for convenient navigation, and save user subscriptions in a database. The entire logic for obtaining sports data continues to rely on a stable REST API at https://api.api-sport.ru, which allows scaling the solution without changing the principles of operation. As WebSocket and AI capabilities appear on the platform, you will be able to expand the bot with instant push updates and smart match recommendations.
How to set up notifications for goals and scores via a Telegram bot using the football API
For the Telegram bot to send notifications about goals and score changes, you need to implement a loop to track the state of matches. The basic scenario looks like this: the user selects an interesting match, the bot saves its identifier and, for example, marks the subscription in the database. Then, on a schedule or at a small interval (for example, every 15-30 seconds), the bot polls the endpoint v2/football/matches/{matchId} or v2/football/matches/{matchId}/events and compares the new score state and event list with what was saved earlier.
The simplest way is to track changes in the fields homeScore.current and awayScore.current for the match. A more advanced approach is to analyze liveEvents, where for each goal-type event the time, team, player, and score after the episode are specified. Below is an example of a function that checks the match for a new goal and, if detected, returns text for the notification. The storage last_home_score and last_away_score can be implemented in Redis, a database, or in the process memory, depending on the load and architecture.
import requests
API_KEY = 'ВАШ_API_КЛЮЧ'
MATCH_URL = 'https://api.api-sport.ru/v2/football/matches/{match_id}'
headers = {
'Authorization': API_KEY
}
def check_goal(match_id, last_home_score, last_away_score):
url = MATCH_URL.format(match_id=match_id)
response = requests.get(url, headers=headers)
response.raise_for_status()
match = response.json()
home = match['homeTeam']['name']
away = match['awayTeam']['name']
home_score = match['homeScore']['current']
away_score = match['awayScore']['current']
if home_score != last_home_score or away_score != last_away_score:
text = f'Гол! {home} {home_score}:{away_score} {away}'
return text, home_score, away_score
return None, home_score, away_score
In practice, you create a background task scheduler that periodically performs such checks for all active subscriptions and sends notifications to those users who selected a specific match. It is important not to poll the API too frequently to avoid exceeding limits and to combine requests whenever possible: for example, to get several matches in one call to v2/football/matches with the ids parameter when possible. This approach ensures a balance between the timeliness of notifications and economical request usage, and in the future, you will be able to switch to WebSocket updates when they become available in the infrastructure. api-sport.ru.
Limitations, caps, and costs of using the live football results API
Any commercial sports events API uses a limit system to ensure stable service operation for all clients and protect against excessive load. Typically, the number of requests per unit of time and the total traffic volume are taken into account. When designing a Telegram bot with live football results, it is important to immediately plan for economical request usage: request only the necessary data, use filters for the v2/football/matches endpoint, cache results for short periods, and avoid duplicating similar calls when processing multiple users.
The cost of using the API and specific limits depend on the chosen tariff, the set of sports, the depth of statistics, and additional options such as access to oddsBase (bookmaker odds) and extended historical statistics. Current information on prices and conditions is usually published on the official website and in the personal account. For the bot to work correctly, it is recommended to estimate the expected number of active users, the frequency of result updates, and to allow some buffer for limits so that the bot operates correctly during peak times, such as during top football tournaments.
- Use the parameters status, tournament_id, and team_id to avoid loading unnecessary matches.
- Combine multiple match IDs into one request via the ids parameter when permissible.
- Cache responses for a short time if the data does not change every second.
- Handle error codes 400, 401, and 500 to respond promptly to limit breaches or authorization errors.
A well-designed integration with the sports events API allows you to keep costs under control while providing high-quality service for Telegram bot users. By focusing on real limitations and carefully designing the polling frequency of live matches, you can scale the solution without unpleasant surprises, and as the audience grows, simply switch to a more suitable tariff plan according to the API provider’s policy.




