A Python client for the FOGIS API (Svensk Fotboll)
Project description
FOGIS API Client for Python
A comprehensive Python client library for interacting with the FOGIS API (Swedish Football Association). This library provides a simple, intuitive interface for referees and match officials to access match data, report results, manage events, and handle all aspects of match administration through the FOGIS system.
🎯 What is FOGIS?
FOGIS (Fotbollens Organisations- och Informationssystem) is the official system used by the Swedish Football Association (Svensk Fotboll) for managing football matches, referee assignments, and match reporting. This Python client provides programmatic access to FOGIS functionality.
✨ Key Features
- 🔐 Secure Authentication - Support for both username/password and cookie-based authentication
- ⚽ Match Management - Fetch match lists, get match details, and report results
- 📊 Advanced Filtering - Powerful filtering system for matches by date, status, age category, gender, and more
- 🎯 Event Reporting - Report goals, cards, substitutions, and other match events
- 👥 Team & Player Data - Access team rosters, player information, and official details
- 🔄 Real-time Updates - Mark matches as finished and update match status
- 🛡️ Type Safety - Full type hints and TypedDict definitions for better IDE support
- 📝 Comprehensive Logging - Built-in logging with sensitive data filtering
- 🧪 Testing Support - Includes mock server for testing and development
- 🐳 Docker Ready - Full Docker support for containerized deployments
🚀 Quick Start
Installation
# Install from PyPI
pip install fogis-api-client-timmyBird
# Or install with development dependencies
pip install fogis-api-client-timmyBird[dev]
# Or install with mock server support
pip install fogis-api-client-timmyBird[mock-server]
Basic Usage
from fogis_api_client import FogisApiClient, configure_logging
# Configure logging (optional)
configure_logging(level="INFO")
# Initialize the client
client = FogisApiClient(username="your_username", password="your_password")
# Fetch your assigned matches
matches = client.fetch_matches_list_json()
print(f"Found {len(matches)} matches")
# Display upcoming matches
for match in matches[:3]:
print(f"{match['datum']} {match['tid']}: {match['hemmalag']} vs {match['bortalag']}")
Using Filters for Historic Data
from fogis_api_client import FogisApiClient, MatchListFilter
from fogis_api_client.enums import MatchStatus, AgeCategory
from datetime import datetime, timedelta
client = FogisApiClient(username="your_username", password="your_password")
# Create a filter for historic data
filter = MatchListFilter()
last_month = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')
today = datetime.now().strftime('%Y-%m-%d')
# Fetch completed matches from the last month
historic_matches = (filter
.start_date(last_month)
.end_date(today)
.include_statuses([MatchStatus.COMPLETED])
.fetch_filtered_matches(client))
print(f"Found {len(historic_matches)} completed matches in the last month")
📖 Table of Contents
- Installation
- Authentication
- Basic Usage
- Advanced Filtering
- Match Management
- Event Reporting
- Error Handling
- Docker Support
- Development
- API Reference
- Contributing
- License
🔧 Installation
From PyPI (Recommended)
pip install fogis-api-client-timmyBird
From Source
git clone https://github.com/PitchConnect/fogis-api-client-python.git
cd fogis-api-client-python
pip install -e .
Development Installation
git clone https://github.com/PitchConnect/fogis-api-client-python.git
cd fogis-api-client-python
pip install -e ".[dev]"
🔐 Authentication
The FOGIS API Client supports two authentication methods:
1. Username and Password (Recommended for Development)
from fogis_api_client import FogisApiClient
client = FogisApiClient(username="your_username", password="your_password")
# Authentication happens automatically on first API call (lazy login)
2. Cookie-based Authentication (Recommended for Production)
# First, get cookies from a logged-in session
client = FogisApiClient(username="your_username", password="your_password")
cookies = client.login() # Explicitly authenticate and get cookies
# Save cookies securely for later use
# Later, use saved cookies (more secure - no credentials in memory)
client = FogisApiClient(cookies=cookies)
# Validate cookies before use
if client.validate_cookies():
matches = client.fetch_matches_list_json()
else:
print("Cookies expired, need to re-authenticate")
🎯 Basic Usage
Fetching Matches
from fogis_api_client import FogisApiClient, FogisLoginError, FogisAPIRequestError
try:
client = FogisApiClient(username="your_username", password="your_password")
# Get all assigned matches
matches = client.fetch_matches_list_json()
print(f"Found {len(matches)} matches")
# Display match information
for match in matches:
print(f"Match {match['matchid']}: {match['hemmalag']} vs {match['bortalag']}")
print(f"Date: {match['datum']} {match['tid']}")
print(f"Venue: {match['arena']}")
print("---")
except FogisLoginError as e:
print(f"Authentication failed: {e}")
except FogisAPIRequestError as e:
print(f"API request failed: {e}")
Reporting Match Results
# Report a match result
result = {
"matchid": 123456,
"hemmamal": 2, # Home team goals
"bortamal": 1, # Away team goals
"halvtidHemmamal": 1, # Half-time home goals
"halvtidBortamal": 0 # Half-time away goals
}
response = client.report_match_result(result)
if response.get('success'):
print("Match result reported successfully!")
Getting Match Details
# Get detailed information about a specific match
match_id = 123456
match_details = client.get_match(match_id)
players = client.get_team_players(match_details['hemmalagid'])
officials = client.get_match_officials(match_id)
🔍 Advanced Filtering
The FOGIS API Client includes a powerful filtering system for querying matches with specific criteria. See the Filter Documentation for comprehensive examples.
Basic Date Range Filtering
from fogis_api_client import MatchListFilter
from datetime import datetime, timedelta
# Create a filter for the last 7 days
filter = MatchListFilter()
week_ago = (datetime.now() - timedelta(days=7)).strftime('%Y-%m-%d')
today = datetime.now().strftime('%Y-%m-%d')
matches = (filter
.start_date(week_ago)
.end_date(today)
.fetch_filtered_matches(client))
Status and Category Filtering
from fogis_api_client.enums import MatchStatus, AgeCategory, Gender
# Filter for completed youth matches
matches = (MatchListFilter()
.include_statuses([MatchStatus.COMPLETED])
.include_age_categories([AgeCategory.YOUTH])
.include_genders([Gender.MALE])
.fetch_filtered_matches(client))
Complex Filtering Examples
# Get all postponed or cancelled matches from last month
last_month = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')
problematic_matches = (MatchListFilter()
.start_date(last_month)
.end_date(today)
.include_statuses([MatchStatus.POSTPONED, MatchStatus.CANCELLED])
.fetch_filtered_matches(client))
# Exclude veteran matches, include only outdoor football
outdoor_non_veteran = (MatchListFilter()
.exclude_age_categories([AgeCategory.VETERANS])
.include_football_types([FootballType.FOOTBALL])
.fetch_filtered_matches(client))
⚽ Match Management
Getting Match Information
# Get a specific match by ID
match = client.get_match(123456)
print(f"Match: {match['hemmalag']} vs {match['bortalag']}")
print(f"Status: {match['status']}")
# Get match result details
result = client.get_match_result(123456)
print(f"Score: {result['hemmamal']}-{result['bortamal']}")
# Get match officials
officials = client.get_match_officials(123456)
for official in officials:
print(f"{official['roll']}: {official['fornamn']} {official['efternamn']}")
Team and Player Information
# Get team players
team_id = 12345
players = client.get_team_players(team_id)
for player in players:
print(f"#{player['trojnummer']} {player['fornamn']} {player['efternamn']}")
# Get team officials
team_officials = client.get_team_officials(team_id)
Match Status Management
# Mark a match report as finished
response = client.mark_reporting_finished(123456)
if response.get('success'):
print("Match reporting marked as complete")
🎯 Event Reporting
Reporting Goals and Cards
from fogis_api_client import EVENT_TYPES
# Report a goal
goal_event = {
"matchid": 123456,
"handelsekod": 6, # Regular goal (see EVENT_TYPES)
"minut": 25, # 25th minute
"lagid": 12345, # Team ID
"personid": 67890, # Player ID
"resultatHemma": 1,
"resultatBorta": 0
}
response = client.report_match_event(goal_event)
# Report a yellow card
card_event = {
"matchid": 123456,
"handelsekod": 20, # Yellow card
"minut": 42,
"lagid": 12345,
"personid": 67890
}
response = client.report_match_event(card_event)
Available Event Types
from fogis_api_client import EVENT_TYPES
# Print all available event types
for code, details in EVENT_TYPES.items():
print(f"Code {code}: {details['name']} (Goal: {details.get('goal', False)})")
Managing Match Events
# Get all events for a match
events = client.get_match_events(123456)
# Clear all events for a match (use with caution!)
response = client.clear_match_events(123456)
🛡️ Error Handling
The library provides specific exception types for different error scenarios:
from fogis_api_client import (
FogisApiClient,
FogisLoginError,
FogisAPIRequestError,
FogisDataError
)
try:
client = FogisApiClient(username="user", password="pass")
matches = client.fetch_matches_list_json()
except FogisLoginError as e:
# Authentication failed - check credentials
print(f"Login failed: {e}")
except FogisAPIRequestError as e:
# Network or server error
print(f"API request failed: {e}")
except FogisDataError as e:
# Data parsing or validation error
print(f"Data error: {e}")
except Exception as e:
# Unexpected error
print(f"Unexpected error: {e}")
Common Error Scenarios
- FogisLoginError: Invalid credentials, expired session, account locked
- FogisAPIRequestError: Network issues, server downtime, rate limiting
- FogisDataError: Invalid response format, missing required fields
📝 Logging
The library includes comprehensive logging with sensitive data filtering:
from fogis_api_client import configure_logging, get_logger
# Configure logging for the entire library
configure_logging(level="INFO")
# Get a logger for your module
logger = get_logger("my_module")
logger.info("This will be logged")
# Sensitive information is automatically filtered
logger.info("Password: secret123") # Logs as "Password: ********"
Available Log Levels
from fogis_api_client import get_log_levels
levels = get_log_levels()
print(levels) # {'DEBUG': 10, 'INFO': 20, 'WARNING': 30, 'ERROR': 40, 'CRITICAL': 50}
🐳 Docker Support
The library includes comprehensive Docker support for both development and production use.
Production Deployment
-
Create a
.envfile with your credentials:FOGIS_USERNAME=your_fogis_username FOGIS_PASSWORD=your_fogis_password
-
Start the service:
docker compose up -d
-
Access the API gateway at http://localhost:8080
Development Environment
# Start development environment with hot reload
./dev.sh
# Run integration tests in Docker
./run_integration_tests.sh
# Build and test Docker images
./scripts/verify_docker_build.sh
Available Docker Images
- Production: Optimized for deployment
- Development: Includes dev tools and hot reload
- Testing: Configured for running tests
- Mock Server: Standalone mock FOGIS API
Docker Compose Services
services:
fogis-api-client: # Main API client service
mock-server: # Mock FOGIS API for testing
integration-tests: # Test runner service
🧪 Development & Testing
Setting Up Development Environment
# Clone the repository
git clone https://github.com/PitchConnect/fogis-api-client-python.git
cd fogis-api-client-python
# Set up development environment
./scripts/setup_dev_env.sh # On macOS/Linux
# or
.\scripts\setup_dev_env.ps1 # On Windows PowerShell
Running Tests
# Run unit tests
python -m pytest tests/
# Run integration tests with mock server
python scripts/run_integration_tests_with_mock.py
# Run all tests with coverage
python -m pytest --cov=fogis_api_client
# Run specific test file
python -m pytest tests/test_match_list_filter.py -v
Mock Server for Development
The library includes a mock FOGIS API server for development and testing:
# Start mock server
python -m fogis_api_client.cli.mock_server
# Use mock server in your code
client = FogisApiClient(username="test", password="test")
# Point to mock server (automatically detected in test environment)
Pre-commit Hooks
# Install pre-commit hooks
pre-commit install
# Run hooks manually
pre-commit run --all-files
# Update hooks to match CI/CD
./update_precommit_hooks.sh
Code Quality
The project maintains high code quality standards:
- Type hints: Full type annotations throughout
- Linting: flake8, black, isort
- Testing: pytest with comprehensive coverage
- Documentation: Comprehensive docstrings and examples
📚 API Reference
Core Classes
FogisApiClient: Main client class for API interactionsMatchListFilter: Advanced filtering for match queriesEVENT_TYPES: Dictionary of available match event types
Exception Classes
FogisLoginError: Authentication failuresFogisAPIRequestError: API request failuresFogisDataError: Data parsing/validation failures
Type Definitions
MatchDict: Match data structurePlayerDict: Player information structureEventDict: Match event structureOfficialDict: Official information structure
Enums
MatchStatus: Match status values (COMPLETED, CANCELLED, etc.)AgeCategory: Age categories (YOUTH, SENIOR, etc.)Gender: Gender categories (MALE, FEMALE, MIXED)FootballType: Football types (FOOTBALL, FUTSAL)
For detailed API documentation, see:
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
Quick Start for Contributors
- Fork the repository
- Create a feature branch:
git checkout -b feature/your-feature-name - Set up development environment:
./scripts/setup_dev_env.sh - Make your changes and add tests
- Run pre-merge check:
./pre-merge-check.sh - Commit and push your changes
- Create a pull request
Development Guidelines
- Follow PEP 8 style guidelines
- Add type hints to all functions
- Write comprehensive tests
- Update documentation for new features
- Ensure all tests pass before submitting PR
🔧 Troubleshooting
Common Issues and Solutions
Authentication Problems
# Problem: FogisLoginError
# Solution: Check credentials and account status
try:
client = FogisApiClient(username="user", password="pass")
client.login() # Test authentication explicitly
except FogisLoginError as e:
print(f"Check your credentials: {e}")
Network and API Issues
# Problem: FogisAPIRequestError
# Solution: Implement retry logic and check connectivity
import time
from fogis_api_client import FogisAPIRequestError
def fetch_with_retry(client, max_retries=3):
for attempt in range(max_retries):
try:
return client.fetch_matches_list_json()
except FogisAPIRequestError as e:
if attempt < max_retries - 1:
time.sleep(2 ** attempt) # Exponential backoff
continue
raise e
Data Validation Issues
# Problem: FogisDataError
# Solution: Validate data before sending
def safe_report_result(client, result_data):
required_fields = ['matchid', 'hemmamal', 'bortamal']
if not all(field in result_data for field in required_fields):
raise ValueError(f"Missing required fields: {required_fields}")
return client.report_match_result(result_data)
For more detailed troubleshooting, see docs/troubleshooting.md.
📄 License
This project is licensed under the MIT License - see the LICENSE.txt file for details.
🙏 Acknowledgments
- Swedish Football Association (Svensk Fotboll) for providing the FOGIS system
- All contributors who have helped improve this library
- The Python community for excellent tools and libraries
📞 Support
- Documentation: docs/
- Issues: GitHub Issues
- Discussions: GitHub Discussions
Made with ⚽ for the Swedish football community
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fogis_api_client_timmybird-0.6.0.tar.gz.
File metadata
- Download URL: fogis_api_client_timmybird-0.6.0.tar.gz
- Upload date:
- Size: 145.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b7b5552d0dabb32a2bd9d3014108c09db814f34579cef9774dedc33c90a60760
|
|
| MD5 |
1e4d034f8d399bcb3e5e327dd22df8de
|
|
| BLAKE2b-256 |
6eb6beacc79ff7d07e875f455251e4e4c476b500b68154e025b0f26c8f0a3fd5
|
File details
Details for the file fogis_api_client_timmybird-0.6.0-py3-none-any.whl.
File metadata
- Download URL: fogis_api_client_timmybird-0.6.0-py3-none-any.whl
- Upload date:
- Size: 173.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e3eef2e02e937fd270c08509f4d9f1de1d063fc28498518be77094cfe74aa146
|
|
| MD5 |
4aeb7290583f327fdc3dd5fd81a8d0c6
|
|
| BLAKE2b-256 |
f0b69dd6db2bd211814a6f7e26f0e472e74a8976b90f4758d39c481a09a5fec9
|