Version 1.1.1 | Production Ready β
TurkiyeAPI is a comprehensive REST API providing detailed information about Turkiye's administrative divisions including provinces, districts, neighborhoods and villages with demographic and geographical data.
This is a Python/FastAPI implementation based on the original turkiye-api project by Ubeyde Emir Γzdemir, licensed under the MIT License.
- FastAPI Framework: Modern, fast (high-performance), web framework for building APIs
- Multi-Language Documentation: Automatic language detection with English and Turkish support
- Scalar Documentation: Beautiful, interactive API documentation with modern UI
- OpenAPI Support: Full OpenAPI 3.0 specification in multiple languages
- Type Safety: Full type hints with Pydantic models
- API Versioning: Comprehensive versioning strategy (
/api/v1/...) for smooth migrations
- OWASP Security Headers: All critical security headers implemented (CSP, X-Frame-Options, HSTS, etc.)
- Secured Health Endpoint: Environment-aware detail levels with optional authentication
- Redis Caching: High-performance distributed caching with automatic key generation and 30-minute TTL
- Rate Limiting: Built-in rate limiting with Redis support for distributed deployments
- CORS Configuration: Environment-aware Cross-Origin Resource Sharing
- GZip Compression: Automatic response compression for better performance
- Comprehensive Testing: 80+ tests across all layers (data, services, API, middleware)
- Automated Workflows: GitHub Actions for data and documentation synchronization
- Pre-commit Hooks: Automated code quality checks (Black, isort, flake8, Bandit, mypy)
- Code Quality: 9.0/10 quality score with excellent maintainability
- Production Ready: Docker, Gunicorn, comprehensive deployment guides, and production config templates
- Prometheus Metrics: Built-in metrics at
/metricsendpoint - Structured Logging: JSON logging with configurable levels
- Health Checks: Enhanced health endpoint with dependency status monitoring
- Python 3.8+
- pip
- Clone the repository:
git clone https://github.com/gencharitaci/turkiye-api-py.git
cd turkiye-api-py- Create a virtual environment:
python -m venv venv
# On Windows
venv\Scripts\activate
# On macOS/Linux
source venv/bin/activate- Install dependencies:
pip install -r requirements.txt- Create a
.envfile:
# For development
cp .env.example .env
# For production (recommended)
cp .env.production.recommended .envEdit .env to customize settings. See Configuration section for details.
- (Optional) Set up pre-commit hooks for code quality:
pip install pre-commit
pre-commit installAfter installing via pip, you can use the package as a Python SDK to interact with any Turkiye API server:
# Install the latest version
pip install turkiye-api-py
# Or install a specific version
pip install turkiye-api-py==1.1.1from app import TurkiyeClient
# Connect to a running API server (you need to have a server running)
client = TurkiyeClient(base_url="http://localhost:8181")
# Get all provinces
provinces = client.get_provinces()
print(f"Total provinces: {len(provinces)}")
# Get Istanbul (ID: 34)
istanbul = client.get_province(34)
print(f"{istanbul['name']}: {istanbul['population']:,} people")
# Get districts in Istanbul
districts = client.get_districts(province_id=34)
print(f"Istanbul has {len(districts)} districts")
# Filter provinces by population
large_cities = client.get_provinces(min_population=1000000)
for city in large_cities:
print(f"{city['name']}: {city['population']:,}")To use the SDK, you need an API server running. You can either:
Option 1: Run the server from the installed package
# Start the server (after pip install)
turkiye-api serve
# Start with auto-reload for development
turkiye-api serve --reload
# Start on a custom port
turkiye-api serve --port 8000Option 2: Connect to an existing server
from app import TurkiyeClient
# Connect to a remote server
client = TurkiyeClient(base_url="https://your-api-domain.com")
provinces = client.get_provinces()- Simple & Pythonic: Clean, intuitive API
- Type Hints: Full type annotations for better IDE support
- Error Handling: Comprehensive error messages
- Context Manager: Automatic resource cleanup
- Pagination: Built-in pagination support
- Filtering: Advanced filtering options
- Language Support: English and Turkish responses
For complete SDK documentation and examples, see SDK_USAGE.md
python run.pyThe API will be available at: http://localhost:8181
For production deployment, we recommend using Gunicorn with Uvicorn workers or Docker:
Option 1: Docker (Recommended)
docker-compose up -dOption 2: Gunicorn
gunicorn -c gunicorn.conf.py app.main:appOption 3: Quick Start Scripts
# Linux/Mac
chmod +x start-production.sh
./start-production.sh
# Windows
start-production.batFor detailed production deployment instructions, see DEPLOYMENT_EN.md or DEPLOYMENT_TR.md
Key configuration options (see .env.production.recommended for complete list):
# Application
ENVIRONMENT=production
DEBUG=false
PORT=8181
WORKERS=4
# Security (CRITICAL for production)
EXPOSE_SERVER_HEADER=false
HEALTH_CHECK_DETAILED=false
HEALTH_CHECK_AUTH_ENABLED=true
HEALTH_CHECK_PASSWORD=your-secure-password
# Redis (for caching and rate limiting)
REDIS_URL=redis://localhost:6379/0
# Rate Limiting
RATE_LIMIT_ENABLED=true
RATE_LIMIT_PER_MINUTE=100
# CORS
ALLOWED_ORIGINS=https://yourdomain.comProduction Security Checklist:
- β
Set
HEALTH_CHECK_DETAILED=falseto minimize information disclosure - β
Enable
HEALTH_CHECK_AUTH_ENABLED=truefor sensitive environments - β
Set strong
HEALTH_CHECK_PASSWORD - β
Keep
EXPOSE_SERVER_HEADER=falseto prevent technology stack exposure - β
Configure
ALLOWED_ORIGINSwith your actual domains - β Enable HTTPS via reverse proxy (nginx/Apache)
All OWASP security headers are automatically applied:
- X-Content-Type-Options: nosniff
- X-Frame-Options: DENY
- X-XSS-Protection: 1; mode=block
- Content-Security-Policy (configured)
- Referrer-Policy: strict-origin-when-cross-origin
- Permissions-Policy (geolocation, microphone, camera disabled)
- Strict-Transport-Security (production only)
Once the server is running, you can access the documentation in multiple languages:
- Auto-Detect Language: http://localhost:8181/docs (Redirects based on browser language)
- English Documentation: http://localhost:8181/docs/en (Interactive Scalar UI)
- Turkish Documentation: http://localhost:8181/docs/tr (Δ°nteraktif Scalar UI)
- English OpenAPI Spec: http://localhost:8181/openapi-en.json
- Turkish OpenAPI Spec: http://localhost:8181/openapi-tr.json
The documentation automatically detects your browser language and displays content in English or Turkish. You can also manually switch languages using the selector buttons in the top-right corner.
For more details, see the interactive documentation at /docs endpoint.
The guides/ folder contains comprehensive documentation synchronized from the turkiye-api-docs repository.
Auto-Sync: Documentation is automatically updated daily at 2:00 AM UTC via GitHub Actions.
Manual Sync:
# Linux/Mac
./scripts/sync-guides.sh
# Windows
scripts\sync-guides.batFor detailed information about the sync mechanism, see GUIDES_SYNC.md
The app/data/ folder contains administrative data (provinces, districts, etc.) synchronized from the turkiye-api repository.
Auto-Sync: Data is automatically updated weekly on Sunday at 3:00 AM UTC via GitHub Actions.
Manual Sync:
# Linux/Mac
./scripts/sync-data.sh
# Windows
scripts\sync-data.batFeatures:
- β Automatic JSON validation
- β Backup before update
- β Weekly scheduled sync
- β Manual trigger available
For detailed information about data synchronization, see DATA_SYNC.md
For information about advanced features including rate limiting, Redis integration, API versioning, and monitoring, see ADVANCED_FEATURES.md.
- Rate Limiting: Protect your API from abuse with configurable rate limits
- Redis Integration: Distributed rate limiting for multi-instance deployments
- API Versioning:
/api/v1/...with support for future versions - Monitoring: Prometheus metrics at
/metricsendpoint - Version Info: Get supported versions at
/api/versions
GET /health- Enhanced health check with dependency statusGET /api/versions- Get supported API versions information
GET /api/v1/language- Get current language preferencePOST /api/v1/language- Set language preferenceGET /api/v1/languages- Get list of supported languages
GET /api/v1/provinces- Get all provinces with optional filtersGET /api/v1/provinces/{id}- Get specific province by ID
GET /api/v1/districts- Get all districts with optional filtersGET /api/v1/districts/{id}- Get specific district by ID
GET /api/v1/neighborhoods- Get all neighborhoods with optional filtersGET /api/v1/neighborhoods/{id}- Get specific neighborhood by ID
GET /api/v1/villages- Get all villages with optional filtersGET /api/v1/villages/{id}- Get specific village by ID
GET /api/v1/towns- Get all towns with optional filtersGET /api/v1/towns/{id}- Get specific town by ID
All list endpoints support these common query parameters:
name: Filter by name (partial match)minPopulation: Minimum population filtermaxPopulation: Maximum population filteroffset: Pagination offsetlimit: Pagination limitfields: Comma-separated list of fields to returnsort: Sort by field (prefix with-for descending)
Additional filters vary by endpoint. See the interactive documentation for details.
curl http://localhost:8181/api/v1/provincescurl http://localhost:8181/api/v1/provinces?minPopulation=1000000curl http://localhost:8181/api/v1/provinces/34curl http://localhost:8181/api/v1/districts?provinceId=34curl http://localhost:8181/api/v1/provinces?fields=id,name,populationThe project includes comprehensive test coverage (80+ tests) across all layers.
# Install test dependencies
pip install pytest pytest-cov pytest-asyncio httpx
# Run all tests
pytest tests/ -v
# Run with coverage report
pytest tests/ -v --cov=app --cov-report=term-missing
# Run with HTML coverage report
pytest tests/ -v --cov=app --cov-report=html
# Open htmlcov/index.html in browsertests/
βββ test_data_loader.py # DataLoader tests (14 tests)
βββ test_api/
β βββ test_provinces_endpoint.py # API integration tests (19 tests)
βββ test_services/
β βββ test_base_service.py # Base service tests (18 tests)
β βββ test_province_service.py # Province service tests (18 tests)
βββ test_middleware/
βββ test_security.py # Security middleware tests (11 tests)
Current Coverage: 80+ tests covering:
- β Data loading and caching
- β Service layer (filtering, sorting, pagination)
- β API endpoints (all HTTP methods and error cases)
- β Security middleware (all OWASP headers)
For detailed testing guide, see TESTING.md
turkiye-api-py/
βββ app/
β βββ data/ # JSON data files
β βββ i18n/ # Internationalization
β βββ middleware/ # Request/response middleware
β β βββ security.py # Security headers (NEW)
β β βββ metrics.py # Prometheus metrics
β β βββ language.py # Language detection
β βββ models/ # Pydantic models and schemas
β βββ routers/ # API route handlers
β βββ services/ # Business logic layer
β β βββ cache_service.py # Redis caching service (NEW)
β β βββ base_service.py # Base service utilities
β β βββ *_service.py # Domain services
β βββ main.py # FastAPI application
β βββ settings.py # Configuration management
β βββ scalar_docs.py # API documentation setup
βββ tests/ # Test suite (80+ tests) (NEW)
β βββ test_api/ # API integration tests
β βββ test_services/ # Service unit tests
β βββ test_middleware/ # Middleware tests
β βββ conftest.py # Test fixtures
βββ docs/ # Documentation (NEW)
β βββ ADVANCED_FEATURES.md # Advanced features guide
β βββ CHANGELOG.md # Version history
β βββ DATA_SYNC.md # Data synchronization guide
β βββ DEPLOYMENT_EN.md # Deployment guide (English)
β βββ DEPLOYMENT_TR.md # Deployment guide (Turkish)
β βββ GUIDES_SYNC.md # Documentation sync guide
β βββ IMPLEMENTATION_SUMMARY.md # Implementation details
β βββ PRODUCTION_READINESS.md # Production checklist
β βββ TESTING.md # Testing guide
βββ scripts/ # Utility scripts (NEW)
β βββ sync-data.sh # Data sync script (Linux/Mac)
β βββ sync-data.bat # Data sync script (Windows)
β βββ sync-guides.sh # Guides sync script (Linux/Mac)
β βββ sync-guides.bat # Guides sync script (Windows)
βββ .github/
β βββ workflows/
β βββ sync-data.yml # Data sync workflow (NEW)
β βββ sync-guides.yml # Guides sync workflow (NEW)
βββ requirements.txt # Python dependencies
βββ run.py # Development server runner
βββ gunicorn.conf.py # Production Gunicorn configuration
βββ Dockerfile # Docker image definition
βββ docker-compose.yml # Docker Compose configuration
βββ .env.example # Development environment template
βββ .env.production.recommended # Production config template (NEW)
βββ .pre-commit-config.yaml # Pre-commit hooks (NEW)
βββ README.md # This file (English)
βββ README_TR.md # Turkish README
- FastAPI: Modern Python web framework
- Pydantic: Data validation using Python type annotations
- Uvicorn: ASGI server implementation
- Gunicorn: Production WSGI/ASGI server
- Redis: Distributed caching and rate limiting
- In-Memory Cache: Pre-indexed data structures for O(1) lookups
- OWASP Headers: Comprehensive security header middleware
- CORS Middleware: Configurable cross-origin resource sharing
- Rate Limiting: Request throttling with Redis backend
- Scalar: Beautiful, interactive API documentation UI
- OpenAPI 3.0: Full specification with multi-language support
- pytest: Testing framework with 80+ tests
- pytest-cov: Code coverage reporting
- pytest-asyncio: Async test support
- Black: Code formatting
- isort: Import sorting
- flake8: Linting
- Bandit: Security vulnerability scanning
- mypy: Static type checking
- Docker: Containerization
- GitHub Actions: Automated data and documentation synchronization
- Prometheus: Metrics collection
- Pre-commit: Git hooks for code quality
Contributions are welcome! This project maintains high quality standards with comprehensive testing and automated quality checks.
-
Fork and Clone
git clone https://github.com/YOUR_USERNAME/turkiye-api-py.git cd turkiye-api-py -
Set Up Development Environment
python -m venv venv source venv/bin/activate # or venv\Scripts\activate on Windows pip install -r requirements.txt pip install pre-commit pytest pytest-cov pre-commit install
-
Create a Feature Branch
git checkout -b feature/your-feature-name
-
Write Code and Tests
- Follow existing code style (enforced by Black, isort, flake8)
- Add tests for new features (maintain 80%+ coverage)
- Update documentation as needed
-
Run Quality Checks
# Run tests pytest tests/ -v --cov=app # Run pre-commit hooks pre-commit run --all-files
-
Commit and Push
git add . git commit -m "feat: your feature description" git push origin feature/your-feature-name
-
Create Pull Request
- Provide clear description of changes
- Reference any related issues
- Ensure all tests and quality checks pass locally
- Code Style: Black formatting with 120-character line length
- Import Sorting: isort with Black profile
- Type Hints: Required for all public functions and methods
- Docstrings: Required for all public classes and functions
- Testing: Minimum 80% code coverage for new code
- Security: All code scanned by Bandit
- β All tests must pass
- β Code coverage must not decrease
- β Pre-commit hooks must pass
- β Clear commit messages (conventional commits preferred)
- β Update CHANGELOG.md for notable changes
- β For major changes, open an issue first to discuss
Run these checks locally before committing to ensure code quality:
# Test matrix (Python 3.8-3.11)
pytest tests/ -v --cov=app
# Linting
black --check app/ tests/
isort --check app/ tests/
flake8 app/ tests/
mypy app/
# Security
bandit -r app/ -llWhen adding new features:
- Update README.md (English and Turkish)
- Add examples to API documentation in
app/scalar_docs.py - Update DEPLOYMENT guides if configuration changes
- Add entries to CHANGELOG.md
Thank you for contributing to Turkiye API! π
This project is based on the original turkiye-api by Ubeyde Emir Γzdemir.
Original Author: Ubeyde Emir Γzdemir
- Email: ubeydeozdmr@gmail.com
- Telegram: @ubeydeozdmr
- GitHub: @ubeydeozdmr
Python Implementation: Adem Kurtipek
- Email: gncharitaci@gmail.com
- GitHub: @gencharitaci
- Repository: turkiye-api-py
This project is licensed under the MIT License - see the LICENSE file for details.
Based on the original turkiye-api project, also licensed under MIT.