# Flughafensuche

Integration der Flughafensuche — Abfragen per Text, Koordinaten und IP mit Mustern für Autovervollständigung und nächstgelegene Flughäfen.



Lauffähige Beispiele, um Flughäfen nach Name oder Standort zu finden, mit den Endpoints der [Flughafensuche](/docs/v31/airport-search): Autovervollständigung per Text und Suche nach den nächstgelegenen Flughäfen anhand von Koordinaten.

| # | Frage                                                                         | Verwendete Daten          |
| - | ----------------------------------------------------------------------------- | ------------------------- |
| 1 | Autovervollständigung: Ein Nutzer tippt „heathrow“ — welche Flughäfen passen? | /airports/search/text     |
| 2 | Die drei nächstgelegenen Flughäfen zu gegebenen GPS-Koordinaten finden        | /airports/search/location |

<DocRequirements>
  <DocRequirementAuth />
</DocRequirements>

### Installation [#install]

Die folgenden Skripte verwenden `requests` für API-Aufrufe und `rich` für die Terminalausgabe. Einmalig installieren:

```bash
pip install requests rich
```

***

### 1. Autovervollständigung von Flughafennamen per Text [#1-text-autocomplete-for-airport-names]

**Frage:** Autovervollständigung: Ein Nutzer tippt „heathrow“ — welche Flughäfen passen?

Der Endpoint `/airports/search/text` liefert nach Relevanz geordnete Ergebnisse. Verwenden Sie den `ident` des ersten Ergebnisses, um `/airports/search?icao=` für vollständige Daten zu Start- und Landebahnen, Frequenzen und Navaids aufzurufen.

```python
import os

import requests
from rich.console import Console
from rich.table import Table

console = Console()

HEADERS = {
    "X-RapidAPI-Key": os.getenv("RAPIDAPI_KEY", "YOUR_RAPIDAPI_KEY"),
    "X-RapidAPI-Host": "skylink-api.p.rapidapi.com",
}
BASE = "https://skylink-api.p.rapidapi.com"


def search_text(query: str, limit: int = 5) -> dict | None:
    r = requests.get(
        f"{BASE}/airports/search/text",
        headers=HEADERS,
        params={"q": query, "limit": limit},
        timeout=(10, 15),
    )
    if r.status_code == 404:
        return None
    r.raise_for_status()
    return r.json()


def main() -> None:
    query = "heathrow"
    result = search_text(query, limit=5)
    if not result:
        console.print("[yellow]No results found.[/]")
        return

    airports = result.get("airports") or []
    found = result.get("airports_found", len(airports))

    table = Table(title=f'Text Search: "{query}" — {found} result(s)')
    table.add_column("ICAO", style="cyan", no_wrap=True)
    table.add_column("IATA")
    table.add_column("Name")
    table.add_column("City")
    table.add_column("Country")
    table.add_column("Relevance", justify="right")

    for apt in airports:
        table.add_row(
            apt.get("ident", "—"),
            apt.get("iata_code", "—"),
            apt.get("name", "—"),
            apt.get("municipality", "—"),
            apt.get("iso_country", "—"),
            f"{apt.get('relevance_score', 0):.2f}",
        )

    console.print(table)

    if airports:
        top_icao = airports[0].get("ident", "")
        console.print(
            f"\n[dim]Top match: [bold]{top_icao}[/bold] — fetch full details with "
            f"[bold]/airports/search?icao={top_icao}[/bold][/]"
        )


if __name__ == "__main__":
    main()
```

**Ausgabe:** Eine nach Relevanz geordnete Tabelle mit bis zu 5 Flughäfen, die zu „heathrow“ passen, mit ICAO, IATA, Name, Stadt, Land und Relevanzwert. Gibt den ICAO-Abfragebefehl für das beste Ergebnis aus.

***

### 2. Nächstgelegene Flughäfen zu GPS-Koordinaten [#2-nearest-airports-to-gps-coordinates]

**Frage:** Die drei nächstgelegenen Flughäfen zu gegebenen GPS-Koordinaten (lat/lon) finden.

Der Endpoint `/airports/search/location` liefert Flughäfen innerhalb eines Radius, sortiert nach Entfernung. Übergeben Sie einen beliebigen `ident` an `/airports/search?icao=`, um vollständige Daten zu Start- und Landebahnen und Frequenzen abzurufen.

```python
import os

import requests
from rich.console import Console
from rich.table import Table

console = Console()

HEADERS = {
    "X-RapidAPI-Key": os.getenv("RAPIDAPI_KEY", "YOUR_RAPIDAPI_KEY"),
    "X-RapidAPI-Host": "skylink-api.p.rapidapi.com",
}
BASE = "https://skylink-api.p.rapidapi.com"


def search_location(lat: float, lon: float, radius_km: int = 80) -> dict | None:
    r = requests.get(
        f"{BASE}/airports/search/location",
        headers=HEADERS,
        params={"lat": lat, "lon": lon, "radius_km": radius_km},
        timeout=(10, 15),
    )
    if r.status_code == 404:
        return None
    r.raise_for_status()
    return r.json()


def main() -> None:
    # Central London
    lat, lon = 51.5074, -0.1278
    result = search_location(lat, lon, radius_km=80)
    if not result:
        console.print("[yellow]No airports found in radius.[/]")
        return

    airports = result.get("airports") or []
    airports.sort(key=lambda a: a.get("distance_km") or 9999)
    nearest_three = airports[:3]

    table = Table(title=f"Nearest Airports to {lat}°N, {abs(lon)}°W (radius 80 km)")
    table.add_column("ICAO", style="cyan", no_wrap=True)
    table.add_column("Name")
    table.add_column("City")
    table.add_column("Country")
    table.add_column("Distance (km)", justify="right")

    for apt in nearest_three:
        dist = apt.get("distance_km")
        table.add_row(
            apt.get("ident", "—"),
            apt.get("name", "—"),
            apt.get("municipality", "—"),
            apt.get("iso_country", "—"),
            f"{dist:.1f}" if dist is not None else "—",
        )

    console.print(table)
    console.print(
        "\n[dim]Chain any ICAO to [bold]/airports/search?icao={ident}[/bold] "
        "for runway lengths and frequencies.[/]"
    )


if __name__ == "__main__":
    main()
```

**Ausgabe:** Die drei Flughäfen, die dem Zentrum Londons am nächsten liegen, sortiert nach Entfernung, mit ICAO, Name, Stadt, Land und Entfernung in km.
