airport-data-python
A comprehensive Python library providing easy retrieval of airport data based on IATA, ICAO, city codes, country codes, and continents. Ideal for developers building applications related to aviation, travel, and geography in Python.
Features
- 🌍 Comprehensive airport database with worldwide coverage (18,765 airports)
- 🔎 Ranked search across codes, cities and names, typo-tolerant and accent-insensitive
- 🏙️ City and metro-area lookups (
"London","NYC", former names like"Bombay") - 🕐 DST-aware local time helpers
- 🔍 Search by IATA codes, ICAO codes, country, continent, and more
- 📍 Geographic proximity search with customizable radius
- 🔗 External links to Wikipedia, airport websites, and flight tracking services
- 📏 Distance calculation between airports
- 🏷️ Filter by airport type (large_airport, medium_airport, small_airport, heliport, seaplane_base)
- 🕒 Timezone-based airport lookup
- 💡 Autocomplete suggestions for search interfaces
- 🎯 Advanced multi-criteria filtering
- Built-in error handling for invalid input formats
- Efficiently packaged with gzipped data
Installation
You can install airports-py using pip:
pip install airports-py
Airport Data Structure
Each airport object contains the following fields:
{
"iata": "SIN", # 3-letter IATA code
"icao": "WSSS", # 4-letter ICAO code
"time": "Asia/Singapore", # Timezone identifier
"utc": 8, # UTC offset in hours (int)
"country_code": "SG", # 2-letter country code
"continent": "AS", # 2-letter continent code (AS, EU, NA, SA, AF, OC, AN)
"airport": "Singapore Changi Airport", # Airport name
"latitude": 1.361173, # Latitude coordinate (float)
"longitude": 103.990201, # Longitude coordinate (float)
"elevation_ft": 22, # Elevation in feet (int)
"type": "large_airport", # Airport type
"scheduled_service": "TRUE", # Has scheduled commercial service ("TRUE"/"FALSE")
"wikipedia": "https://en.wikipedia.org/wiki/Singapore_Changi_Airport",
"website": "http://www.changiairport.com",
"runway_length": 13200, # Longest runway in feet (int)
"flightradar24_url": "https://www.flightradar24.com/airport/SIN",
"radarbox_url": "https://www.radarbox.com/airport/WSSS",
"flightaware_url": "https://www.flightaware.com/live/airport/WSSS",
"city": "Singapore", # Municipality ("" when unknown)
"city_code": "SIN" # IATA city/metro code, e.g. "NYC", "LON" ("" when unknown)
}
87 US airports whose FAA identifier is not an ICAO code also have "faa_code" (e.g. "80F"); their icao is "".
Codes are trimmed and case-insensitive everywhere: 'lhr', ' LHR ' and 'LHR' are equivalent.
The utc field is a July snapshot, so it is wrong for about half the year in regions with daylight saving time. Use get_utc_offset() instead.
Basic Usage
from airports import airport_data
# Get airport by IATA code
airport_by_iata = airport_data.get_airport_by_iata("SIN")
print(airport_by_iata[0]["airport"]) # "Singapore Changi Airport"
# Get airport by ICAO code
airport_by_icao = airport_data.get_airport_by_icao("WSSS")
print(airport_by_icao[0]["country_code"]) # "SG"
# Search airports by name
airports = airport_data.search_by_name("Singapore")
print(len(airports)) # Multiple airports matching "Singapore"
# Find nearby airports (within 50km of coordinates)
nearby = airport_data.find_nearby_airports(1.35019, 103.994003, 50)
print(nearby) # Airports near Singapore Changi
API Reference
Core Search Functions
get_airport_by_iata(iata_code)
Finds airports by their 3-letter IATA code.
airports = airport_data.get_airport_by_iata('LHR')
# Returns list of airports with IATA code 'LHR'
get_airport_by_icao(icao_code)
Finds airports by their 4-character ICAO code.
airports = airport_data.get_airport_by_icao('EGLL')
# Returns list of airports with ICAO code 'EGLL'
search(query, limit=10, scheduled_only=False, types=None, country_code=None, fuzzy=True)
Unified, ranked search across codes, cities and names. Ranking: exact IATA > exact ICAO > IATA metro code > exact city > city prefix > name prefix > substring > typo-tolerant match, with major scheduled-service airports first in each tier. Case- and accent-insensitive (zurich finds Zürich), and an exact city match also returns the rest of the metro area.
results = airport_data.search('New York')
# JFK, EWR, LGA, ... each with 'score' and 'match_type'
# ('iata', 'icao', 'city_code', 'city', 'name' or 'fuzzy')
airport_data.search('frankfrut')[0]['iata'] # 'FRA' (typo-tolerant)
airport_data.search('Bombay')[0]['iata'] # 'BOM' (former name)
airport_data.search('london', country_code='GB', types=['large_airport'])
airport_data.search('paris', scheduled_only=True, limit=3)
Raises ValueError if the query is over 100 characters or has fewer than 2 letters or digits.
search_by_name(query, max_results=100)
Searches for airports by name (case- and accent-insensitive, at least 2 letters or digits).
airports = airport_data.search_by_name('Heathrow')
# Returns airports with 'Heathrow' in their name
Geographic Functions
find_nearby_airports(lat, lon, radius_km=100, limit=None)
Finds airports within a specified radius of given coordinates, nearest first. Each result is a copy with a distance field in kilometers.
nearby = airport_data.find_nearby_airports(51.5074, -0.1278, 100)
# Returns airports within 100km of London coordinates
closest = airport_data.find_nearby_airports(51.5074, -0.1278, 100, limit=3)
print(closest[0]['distance'])
calculate_distance(code1, code2)
Calculates the great-circle distance between two airports using IATA or ICAO codes.
distance = airport_data.calculate_distance('LHR', 'JFK')
# Returns distance in kilometers (approximately 5540)
Filtering Functions
get_airports_by_city(city)
Finds airports serving a city (case- and accent-insensitive exact match), major airports first. Common former and alternative names are recognized ("Bombay", "Peking", "Athens", "Roma").
airports = airport_data.get_airports_by_city('London')
# LHR, LGW, STN, LCY, ...
Some airports list the municipality they are in rather than the metro area they serve (EWR is "Newark"); use get_airports_by_city_code for metro areas.
get_airports_by_city_code(city_code)
Finds all airports sharing an IATA city/metro code, major airports first.
airports = airport_data.get_airports_by_city_code('NYC')
# JFK, EWR, LGA, ...
get_airport_by_city_code(city_code)
Finds airports by their city code, in dataset order.
airports = airport_data.get_airport_by_city_code('NYC')
# Returns all airports associated with New York City
get_airport_by_country_code(country_code)
Finds all airports in a specific country.
us_airports = airport_data.get_airport_by_country_code('US')
# Returns all airports in the United States
get_airport_by_continent(continent_code)
Finds all airports on a specific continent.
asian_airports = airport_data.get_airport_by_continent('AS')
# Returns all airports in Asia
# Continent codes: AS, EU, NA, SA, AF, OC, AN
get_airports_by_type(airport_type, limit=None)
Finds airports by their type.
large_airports = airport_data.get_airports_by_type('large_airport')
# Available types: large_airport, medium_airport, small_airport, heliport, seaplane_base
# Convenience search for all airports
all_airports = airport_data.get_airports_by_type('airport')
# Returns large_airport, medium_airport, and small_airport
get_airports_by_timezone(timezone)
Finds all airports within a specific timezone.
london_airports = airport_data.get_airports_by_timezone('Europe/London')
# Returns airports in London timezone
Advanced Functions
find_airports(filters)
Finds airports matching multiple criteria.
# Find large airports in Great Britain with scheduled service
airports = airport_data.find_airports({
'country_code': 'GB',
'type': 'large_airport',
'has_scheduled_service': True
})
# Find airports with minimum runway length
long_runway_airports = airport_data.find_airports({
'min_runway_ft': 10000
})
get_autocomplete_suggestions(query, limit=10)
Provides autocomplete suggestions for search interfaces, using the search ranking without typo tolerance (codes, cities, metro codes and names; major airports first). Returns an empty list for queries shorter than 2 or longer than 100 characters.
suggestions = airport_data.get_autocomplete_suggestions('Lon')
# LHR, LGW, STN, LTN, LCY, ...
Time Zone & Local Time
These use the airport's IANA time zone and account for daylight saving time. date may be a datetime (naive means UTC), an ISO 8601 string, or a Unix timestamp in seconds; it defaults to now. Each returns None if the airport is not found. They need an IANA time zone database. Linux and macOS normally provide one; on Windows the tzdata package is installed automatically. Where the system has none (slim or Alpine container images, for example), run pip install tzdata; the helpers raise ValueError until then.
get_utc_offset(code, date=None)
airport_data.get_utc_offset('JFK', '2026-07-01T12:00:00Z') # -4.0 (EDT)
airport_data.get_utc_offset('JFK', '2026-12-01T12:00:00Z') # -5.0 (EST)
airport_data.get_utc_offset('DEL') # 5.5
get_local_time(code, date=None)
t = airport_data.get_local_time('LHR', '2026-07-01T12:00:00Z')
# {'time_zone': 'Europe/London', 'iso': '2026-07-01T13:00:00+01:00',
# 'date': '2026-07-01', 'time': '13:00:00', 'utc_offset': 1.0,
# 'utc_offset_string': '+01:00', 'is_dst': True, 'local': datetime(...)}
format_airport_time(code, date=None, fmt=None)
airport_data.format_airport_time('NRT', '2026-11-10T00:00:00Z')
# 'Nov 10, 2026, 9:00 AM'
airport_data.format_airport_time('NRT', '2026-11-10T00:00:00Z', '%H:%M %Z')
# '09:00 JST'
get_airport_links(code)
Gets external links for an airport using IATA or ICAO code.
links = airport_data.get_airport_links('SIN')
# Returns:
# {
# 'website': "https://www.changiairport.com",
# 'wikipedia': "https://en.wikipedia.org/wiki/Singapore_Changi_Airport",
# 'flightradar24': "https://www.flightradar24.com/airport/SIN",
# 'radarbox': "https://www.radarbox.com/airport/WSSS",
# 'flightaware': "https://www.flightaware.com/live/airport/WSSS"
# }
Statistical & Analytical Functions
get_airport_stats_by_country(country_code)
Gets comprehensive statistics about airports in a specific country.
stats = airport_data.get_airport_stats_by_country('US')
# Returns:
# {
# 'total': 5432,
# 'by_type': {
# 'large_airport': 139,
# 'medium_airport': 467,
# 'small_airport': 4826,
# ...
# },
# 'with_scheduled_service': 606,
# 'average_runway_length': 5234,
# 'average_elevation': 1245,
# 'timezones': ['America/New_York', 'America/Chicago', ...]
# }
get_airport_stats_by_continent(continent_code)
Gets comprehensive statistics about airports on a specific continent.
stats = airport_data.get_airport_stats_by_continent('AS')
# Returns statistics for Asian airports
get_largest_airports_by_continent(continent_code, limit=10, sort_by='runway')
Gets the largest airports on a continent by runway length or elevation.
# Get top 5 airports in Asia by runway length
top_airports = airport_data.get_largest_airports_by_continent('AS', limit=5, sort_by='runway')
# Get top 10 airports by elevation
high_airports = airport_data.get_largest_airports_by_continent('SA', limit=10, sort_by='elevation')
Bulk Operations
get_multiple_airports(codes)
Fetches multiple airports by their IATA or ICAO codes in one call.
airports = airport_data.get_multiple_airports(['SIN', 'LHR', 'JFK', 'WSSS'])
# Returns list of airport objects (None for codes not found)
calculate_distance_matrix(codes)
Calculates distances between all pairs of airports in a list.
matrix = airport_data.calculate_distance_matrix(['SIN', 'LHR', 'JFK'])
# Returns:
# {
# 'airports': [...],
# 'distances': {
# 'SIN': { 'SIN': 0, 'LHR': 10872, 'JFK': 15344 },
# ...
# }
# }
find_nearest_airport(lat, lon, filters=None)
Finds the single nearest airport to given coordinates, optionally with filters.
# Find nearest airport
nearest = airport_data.find_nearest_airport(1.35019, 103.994003)
print(f"{nearest['airport']} is {nearest['distance']} km away")
# Find nearest large airport with scheduled service
nearest_hub = airport_data.find_nearest_airport(1.35019, 103.994003, {
'type': 'large_airport',
'has_scheduled_service': True
})
Validation & Utilities
validate_iata_code(code) / validate_icao_code(code)
Validates if a code exists in the database.
is_valid = airport_data.validate_iata_code('SIN') # True
get_airport_count(filters)
Gets the count of airports matching the given filters.
count = airport_data.get_airport_count({
'country_code': 'US',
'type': 'large_airport'
})
is_airport_operational(code)
Checks if an airport has scheduled commercial service.
is_operational = airport_data.is_airport_operational('SIN') # True
Error Handling
Functions raise ValueError for invalid input formats (e.g., wrong length, invalid characters). For valid formats that simply don't match any airport, an empty list is returned instead.
# Invalid format raises ValueError
try:
airport = airport_data.get_airport_by_iata('AB') # Too short
except ValueError as e:
print(e) # "Invalid IATA format. Please provide a 3-letter code, e.g., 'AAA'."
# Valid format but non-existent code returns empty list
result = airport_data.get_airport_by_iata('XYZ')
print(result) # []
Examples
Find airports near a city
# Find airports within 100km of Paris
paris_airports = airport_data.find_nearby_airports(48.8566, 2.3522, 100)
print(f"Found {len(paris_airports)} airports near Paris")
Get flight distance
# Calculate distance between Singapore and London
distance = airport_data.calculate_distance('SIN', 'LHR')
print(f"Distance: {round(distance)} km")
Build an airport search interface
# Get autocomplete suggestions
suggestions = airport_data.get_autocomplete_suggestions('New York')
for airport in suggestions:
print(f"{airport['iata']} - {airport['airport']}")
Filter airports by multiple criteria
# Find large airports in Asia with scheduled service
asian_hubs = airport_data.find_airports({
'continent': 'AS',
'type': 'large_airport',
'has_scheduled_service': True
})
Get airport statistics
# Get comprehensive statistics for US airports
us_stats = airport_data.get_airport_stats_by_country('US')
print(f"Total airports: {us_stats['total']}")
print(f"Large airports: {us_stats['by_type']['large_airport']}")
print(f"Average runway length: {us_stats['average_runway_length']} ft")
# Get statistics for Asian airports
asia_stats = airport_data.get_airport_stats_by_continent('AS')
print(f"Countries with airports: {len(asia_stats['by_country'])}")
Bulk operations
# Fetch multiple airports at once
airports = airport_data.get_multiple_airports(['SIN', 'LHR', 'JFK', 'NRT'])
for ap in airports:
if ap:
print(f"{ap['iata']}: {ap['airport']}")
# Calculate distance matrix for route planning
matrix = airport_data.calculate_distance_matrix(['SIN', 'LHR', 'JFK'])
print(f"Distance from SIN to LHR: {matrix['distances']['SIN']['LHR']:.0f} km")
print(f"Distance from LHR to JFK: {matrix['distances']['LHR']['JFK']:.0f} km")
Validation utilities
# Validate airport codes before processing
codes = ['SIN', 'XYZ', 'LHR', 'ABCD']
for code in codes:
is_valid = airport_data.validate_iata_code(code)
print(f"{code}: {'Valid' if is_valid else 'Invalid'}")
# Check if airport is operational
operational = airport_data.is_airport_operational('SIN')
print(f"Singapore Changi is operational: {operational}")
Find nearest airport
# Find nearest airport to current location
nearest = airport_data.find_nearest_airport(1.35019, 103.994003)
print(f"Nearest airport: {nearest['airport']} ({nearest['distance']} km away)")
# Find nearest large airport with scheduled service
nearest_hub = airport_data.find_nearest_airport(1.35019, 103.994003, {
'type': 'large_airport',
'has_scheduled_service': True
})
Using Command-Line Interface (CLI)
You can also directly execute Python code from the CLI without entering the interactive shell. Navigate to the root of your project and run:
python3 -c "from airports import airport_data; result = airport_data.get_airport_by_iata('MAA'); print(result)"
Replace 'MAA' with other codes as needed.
Testing
To test the library locally:
- Navigate to the root of the project:
cd path_to_airport-data-python
- Run the tests using:
python3 -m unittest discover tests -v
This command will discover and run all test files inside the tests directory and provide a detailed output.
Example Data Fields
For Singapore Changi Airport (as returned by the library):
| Key | Value |
|---|---|
iata |
"SIN" |
icao |
"WSSS" |
airport |
"Singapore Changi Airport" |
time |
"Asia/Singapore" |
utc |
8 |
country_code |
"SG" |
continent |
"AS" |
latitude |
1.361173 |
longitude |
103.990201 |
elevation_ft |
22 |
type |
"large_airport" |
scheduled_service |
"TRUE" |
runway_length |
13200 |
wikipedia |
"https://en.wikipedia.org/wiki/Singapore_Changi_Airport" |
website |
"http://www.changiairport.com" |
flightradar24_url |
"https://www.flightradar24.com/airport/SIN" |
radarbox_url |
"https://www.radarbox.com/airport/WSSS" |
flightaware_url |
"https://www.flightaware.com/live/airport/WSSS" |
Changelog
See CHANGELOG.md for the full version history and release notes.
Running the Project Locally
Prerequisites
- Python 3.9 or higher
- Git
Setup Instructions
- Clone the repository:
git clone https://github.com/aashishvanand/airport-data-python.git
- Change into the cloned directory:
cd airport-data-python
- Create a virtual environment (recommended):
python3 -m venv venv
- Activate the virtual environment:
# On macOS/Linux:
source venv/bin/activate
# On Windows:
venv\Scripts\activate
- Install development dependencies:
pip install --upgrade pip
pip install build twine pytest pytest-cov
- Install the package in development mode:
pip install -e .
- Generate the compressed data file (if needed):
# Generate airports.gz from airports.json
python scripts/generate_airports_gz.py
# Verify the data file
python scripts/generate_airports_gz.py --verify-only
Testing
- Run all tests:
python -m unittest discover tests -v
- Run tests with pytest (alternative):
python -m pytest tests/ -v
- Run tests with coverage:
python -m pytest tests/ -v --cov=airports --cov-report=term-missing
- Test basic functionality manually:
python -c "
from airports import airport_data
print('Testing IATA lookup:')
result = airport_data.get_airport_by_iata('LHR')
print(f'Found: {result[0][\"airport\"]}')
print('✅ Basic functionality working!')
"
Building and Validation
- Build the package:
# Clean previous builds
rm -rf build/ dist/ *.egg-info/
# Build package
python -m build
- Validate the package:
twine check dist/*
- Test package installation:
pip install dist/airports_py-*.whl --force-reinstall
Development Scripts
The project includes utility scripts in the scripts/ directory:
Generate Compressed Data File
# Generate airports.gz from airports.json
python scripts/generate_airports_gz.py
# Generate with custom compression level
python scripts/generate_airports_gz.py --compression 6
# Generate with custom source/output files
python scripts/generate_airports_gz.py --source custom_data.json --output custom_data.gz
# Verify existing compressed file
python scripts/generate_airports_gz.py --verify-only
Quick Development Workflow
For ongoing development, use this workflow:
# 1. Make your changes to the code
# 2. Regenerate data file if JSON was updated
python scripts/generate_airports_gz.py
# 3. Run tests
python -m pytest tests/ -v
# 4. Build and validate
python -m build && twine check dist/*
# 5. Test installation
pip install dist/airports_py-*.whl --force-reinstall
Troubleshooting
If you get import errors:
- Ensure you're in the virtual environment:
which pythonshould show the venv path - Verify the package is installed:
pip list | grep airports - Check import works:
python -c "import airports.airport_data"
If data file is missing:
- Generate it:
python scripts/generate_airports_gz.py - Verify location:
ls -la airports/data/airports.gz - Check file integrity:
python scripts/generate_airports_gz.py --verify-only
If tests fail:
- Ensure data file exists and is valid
- Check that all dependencies are installed:
pip install pytest pytest-cov - Run individual tests:
python -m pytest tests/test_airport_data.py::TestAirportData::test_get_airport_by_iata -v
If build fails:
- Ensure
setup.pyhas correct package data configuration - Check that
airports/data/airports.gzexists and is included in package
Deactivating Environment
When you're done developing:
deactivate
Data Management
The airport data is stored in airports/data/ directory:
airports.json- Source data in JSON format (4.7MB)airports.gz- Compressed data used by the library (617KB, 86.9% compression)
Updating Airport Data
- Update the source JSON file:
# Edit airports/data/airports.json with new airport data
- Regenerate the compressed file:
python scripts/generate_airports_gz.py
- Verify the update:
python scripts/generate_airports_gz.py --verify-only
python -c "from airports import airport_data; print(f'Loaded {len(airport_data.airports)} airports')"
- Run tests to ensure compatibility:
python -m pytest tests/ -v
Data Source
This library uses a comprehensive dataset of worldwide airports with regular updates to ensure accuracy and completeness.
License
This project is licensed under the Creative Commons Attribution 4.0 International (CC BY 4.0) - see the LICENSE file for details.
Contributing
Contributions, issues, and feature requests are welcome! Please read the CONTRIBUTING.md guide for details on how to contribute, run tests, and publish new versions.
Feel free to check the issues page.
Metadata
Release files for airports-py 3.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| airports_py-3.2.0.tar.gz | 1.3 MB | With provenance | Details for airports_py-3.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| airports_py-3.2.0-py3-none-any.whl | Python 3 | none | any | Details for airports_py-3.2.0-py3-none-any.whl |
Total release size: 2.5 MB
Release files / airports_py-3.2.0.tar.gz
| Download URL | airports_py-3.2.0.tar.gz |
|---|---|
| Size | 1.3 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
245327f1a018298b8e8a10d33cfa1c62fe14558829a4ceb34d491e212ed2b078
|
|
BLAKE2b-256 checksum How to use checksums |
9acab5415ff4040a43b257632bb47ec3b6941005b01bfc11c91b9081c80b62af
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.
Transparency logRelease files / airports_py-3.2.0-py3-none-any.whl
| Download URL | airports_py-3.2.0-py3-none-any.whl |
|---|---|
| Size | 1.3 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b36b10eef43ea092127ad0a827f023884549dd382226cbfbc60f28fe46291917
|
|
BLAKE2b-256 checksum How to use checksums |
88170c92e8889c58384cfe648174fd1ade7fe07c728d96dcf507440c09666395
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.
Transparency logSecurity for airports-py 3.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for airports_py-3.2.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.