Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

Add support for round trip search

Punit Arani3c40137f029c
diff --git a/docs/api/models.md b/docs/api/models.md
index adde5e2..e786a51 100644
--- a/docs/api/models.md
+++ b/docs/api/models.md
@@ -7,18 +7,41 @@
The main model for configuring flight searches.
```python
-from fli.models import FlightSearchFilters, SeatType, MaxStops, SortBy
+from fli.models import (
+ FlightSearchFilters, FlightSegment, Airport,
+ SeatType, MaxStops, SortBy, TripType, PassengerInfo
+)
+
+# Create flight segments for round trip
+flight_segments = [
+ FlightSegment(
+ departure_airport=[[Airport.JFK, 0]],
+ arrival_airport=[[Airport.LAX, 0]],
+ travel_date="2024-06-01",
+ ),
+ FlightSegment(
+ departure_airport=[[Airport.LAX, 0]],
+ arrival_airport=[[Airport.JFK, 0]],
+ travel_date="2024-06-15",
+ )
+]
filters = FlightSearchFilters(
- trip_type=TripType.ONE_WAY,
+ trip_type=TripType.ROUND_TRIP,
passenger_info=PassengerInfo(adults=1),
- flight_segments=[...],
+ flight_segments=flight_segments,
stops=MaxStops.NON_STOP,
seat_type=SeatType.ECONOMY,
sort_by=SortBy.CHEAPEST
)
```
+**Validation Rules:**
+- Flight segments must have different departure and arrival airports
+- Travel dates cannot be in the past
+- For round trips, exactly two flight segments are required
+- Passenger counts must be valid (at least one adult)
+
::: fli.models.google_flights.FlightSearchFilters
### FlightResult
@@ -53,6 +76,12 @@ Available sorting options for flight results.
::: fli.models.google_flights.SortBy
+### TripType
+
+Type of trip for flight search.
+
+::: fli.models.google_flights.TripType
+
## Support Models
### PassengerInfo
@@ -71,4 +100,4 @@ Time constraints for flight departure and arrival.
Price constraints for flight search.
-::: fli.models.google_flights.PriceLimit
\ No newline at end of file
+::: fli.models.google_flights.PriceLimit
diff --git a/docs/examples/advanced.md b/docs/examples/advanced.md
index f37707f..6d06c9f 100644
--- a/docs/examples/advanced.md
+++ b/docs/examples/advanced.md
@@ -13,6 +13,7 @@ from fli.search import SearchFlights, SearchFlightsFilters
# Create detailed filters
filters = SearchFlightsFilters(
+ trip_type=TripType.ONE_WAY,
departure_airport=Airport.JFK,
arrival_airport=Airport.LHR,
departure_date="2024-06-01",
@@ -43,6 +44,7 @@ from fli.search import SearchFlights, SearchFlightsFilters
# Create filters with time restrictions
filters = SearchFlightsFilters(
+ trip_type=TripType.ONE_WAY,
departure_airport=Airport.JFK,
arrival_airport=Airport.LAX,
departure_date="2024-06-01",
@@ -75,6 +77,7 @@ from fli.models import DateSearchFilters, Airport, SeatType
# Create filters for weekends only
filters = DateSearchFilters(
+ trip_type=TripType.ONE_WAY,
departure_airport=Airport.JFK,
arrival_airport=Airport.LAX,
from_date="2024-06-01",
@@ -179,4 +182,187 @@ def analyze_results(results: List[FlightResult]) -> pd.DataFrame:
})
return pd.DataFrame(flights_data)
-```
\ No newline at end of file
+```
+
+### Complex Round Trip Search with Validations
+
+```python
+from fli.models import (
+ Airport, Airline, SeatType, MaxStops,
+ PassengerInfo, TimeRestrictions, TripType,
+ FlightSegment, FlightSearchFilters
+)
+from fli.search import SearchFlights
+from datetime import datetime, timedelta
+
+# Create flight segments with time restrictions
+outbound = FlightSegment(
+ departure_airport=[[Airport.JFK, 0]],
+ arrival_airport=[[Airport.LHR, 0]],
+ travel_date="2024-06-01",
+ time_restrictions=TimeRestrictions(
+ earliest_departure=6, # 6 AM
+ latest_departure=12, # 12 PM
+ earliest_arrival=18, # 6 PM
+ latest_arrival=23 # 11 PM
+ )
+)
+
+return_flight = FlightSegment(
+ departure_airport=[[Airport.LHR, 0]],
+ arrival_airport=[[Airport.JFK, 0]],
+ travel_date="2024-06-15",
+ time_restrictions=TimeRestrictions(
+ earliest_departure=14, # 2 PM
+ latest_departure=20, # 8 PM
+ earliest_arrival=17, # 5 PM
+ latest_arrival=23 # 11 PM
+ )
+)
+
+# Validate dates
+today = datetime.now().date()
+outbound_date = datetime.strptime(outbound.travel_date, "%Y-%m-%d").date()
+return_date = datetime.strptime(return_flight.travel_date, "%Y-%m-%d").date()
+
+if outbound_date <= today:
+ raise ValueError("Outbound date must be in the future")
+if return_date <= outbound_date:
+ raise ValueError("Return date must be after outbound date")
+if return_date - outbound_date > timedelta(days=30):
+ raise ValueError("Trip duration cannot exceed 30 days")
+
+# Create filters with complex requirements
+filters = FlightSearchFilters(
+ trip_type=TripType.ROUND_TRIP,
+ passenger_info=PassengerInfo(
+ adults=2,
+ children=1,
+ infants_on_lap=1
+ ),
+ flight_segments=[outbound, return_flight],
+ stops=MaxStops.ONE_STOP_OR_FEWER,
+ seat_type=SeatType.BUSINESS,
+ airlines=[Airline.BA, Airline.VS], # British Airways and Virgin Atlantic
+ max_duration=720, # 12 hours max flight time
+ layover_restrictions=LayoverRestrictions(
+ airports=[Airport.DUB, Airport.AMS], # Preferred layover airports
+ max_duration=180 # Maximum 3-hour layover
+ )
+)
+
+search = SearchFlights()
+results = search.search(filters)
+
+# Process results with detailed information
+for flight in results:
+ print(f"\nTotal Price: ${flight.total_price}")
+
+ print("\nOutbound Flight:")
+ for leg in flight.outbound.legs:
+ print(f"Flight: {leg.airline.value} {leg.flight_number}")
+ print(f"From: {leg.departure_airport.value} at {leg.departure_datetime}")
+ print(f"To: {leg.arrival_airport.value} at {leg.arrival_datetime}")
+ print(f"Duration: {leg.duration} minutes")
+ if leg.layover_duration:
+ print(f"Layover: {leg.layover_duration} minutes")
+
+ print("\nReturn Flight:")
+ for leg in flight.return_flight.legs:
+ print(f"Flight: {leg.airline.value} {leg.flight_number}")
+ print(f"From: {leg.departure_airport.value} at {leg.departure_datetime}")
+ print(f"To: {leg.arrival_airport.value} at {leg.arrival_datetime}")
+ print(f"Duration: {leg.duration} minutes")
+ if leg.layover_duration:
+ print(f"Layover: {leg.layover_duration} minutes")
+```
+
+### Advanced Date Search with Validation
+
+```python
+from fli.models import (
+ DateSearchFilters, Airport, TripType,
+ FlightSegment, PassengerInfo, SeatType
+)
+from fli.search import SearchDates
+from datetime import datetime, timedelta
+
+def validate_dates(from_date: str, to_date: str, min_stay: int, max_stay: int):
+ """Validate date ranges for round trip searches."""
+ start = datetime.strptime(from_date, "%Y-%m-%d").date()
+ end = datetime.strptime(to_date, "%Y-%m-%d").date()
+ today = datetime.now().date()
+
+ if start <= today:
+ raise ValueError("Start date must be in the future")
+ if end <= start:
+ raise ValueError("End date must be after start date")
+ if end - start > timedelta(days=180):
+ raise ValueError("Date range cannot exceed 180 days")
+ if min_stay < 1:
+ raise ValueError("Minimum stay must be at least 1 day")
+ if max_stay > 30:
+ raise ValueError("Maximum stay cannot exceed 30 days")
+ if min_stay > max_stay:
+ raise ValueError("Minimum stay cannot be greater than maximum stay")
+
+# Create flight segments for date search
+segments = [
+ FlightSegment(
+ departure_airport=[[Airport.JFK, 0]],
+ arrival_airport=[[Airport.LAX, 0]],
+ time_restrictions=TimeRestrictions(
+ earliest_departure=9, # 9 AM
+ latest_departure=18, # 6 PM
+ )
+ )
+]
+
+# Validate and create filters
+from_date = "2024-06-01"
+to_date = "2024-06-30"
+min_stay = 2
+max_stay = 4
+
+validate_dates(from_date, to_date, min_stay, max_stay)
+
+filters = DateSearchFilters(
+ trip_type=TripType.ROUND_TRIP,
+ passenger_info=PassengerInfo(adults=1),
+ flight_segments=segments,
+ from_date=from_date,
+ to_date=to_date,
+ min_stay_days=min_stay,
+ max_stay_days=max_stay,
+ seat_type=SeatType.ECONOMY
+)
+
+search = SearchDates()
+results = search.search(filters)
+
+# Process results with weekend filtering
+weekend_trips = []
+for trip in results:
+ outbound = datetime.strptime(trip.outbound_date, "%Y-%m-%d")
+ return_date = datetime.strptime(trip.return_date, "%Y-%m-%d")
+
+ # Check if outbound is on weekend (5 = Saturday, 6 = Sunday)
+ if outbound.weekday() >= 5:
+ stay_duration = (return_date - outbound).days
+ weekend_trips.append({
+ 'outbound': trip.outbound_date,
+ 'return': trip.return_date,
+ 'duration': stay_duration,
+ 'price': trip.total_price
+ })
+
+# Sort by price
+weekend_trips.sort(key=lambda x: x['price'])
+
+# Display results
+for trip in weekend_trips:
+ print(f"\nWeekend Trip:")
+ print(f"Outbound: {trip['outbound']} (Weekend)")
+ print(f"Return: {trip['return']}")
+ print(f"Duration: {trip['duration']} days")
+ print(f"Total Price: ${trip['price']}")
\ No newline at end of file
diff --git a/docs/guides/quickstart.md b/docs/guides/quickstart.md
index aaab506..3df564c 100644
--- a/docs/guides/quickstart.md
+++ b/docs/guides/quickstart.md
@@ -10,7 +10,7 @@ This guide will help you get started with Fli quickly.
pip install flights
```
-### For CLI and GUI Usage
+### For CLI Usage
```bash
pipx install flights
@@ -18,33 +18,31 @@ pipx install flights
## Basic Usage
-### Application (GUI)
+### Command Line Interface
+
+1. Search for one-way flights:
```bash
-fli app
+fli search JFK LHR 2024-06-01
```
-This will launch the Streamlit application at [http://localhost:3600](http://localhost:3600).
-
-### Command Line Interface
-
-1. Search for flights on a specific date:
+2. Search for round trip flights:
```bash
-fli search JFK LHR 2024-06-01
+fli search JFK LHR 2024-06-01 --return 2024-06-15
```
-2. Search with filters:
+3. Search with filters:
```bash
fli search JFK LHR 2024-06-01 \
-t 6-20 \ # Time range (6 AM - 8 PM)
-a BA KL \ # Airlines (British Airways, KLM)
- -s BUSINESS \ # Seat type
- -x NON_STOP # Non-stop flights only
+ -c BUSINESS \ # Seat type
+ -s 0 # Non-stop flights only
```
-3. Find cheapest dates:
+4. Find cheapest dates:
```bash
fli cheap JFK LHR --from 2024-06-01 --to 2024-06-30
@@ -52,17 +50,29 @@ fli cheap JFK LHR --from 2024-06-01 --to 2024-06-30
### Python API
-1. Basic Flight Search:
+1. Basic One-Way Flight Search:
```python
-from fli.search import SearchFlights, SearchFlightsFilters
-from fli.models import Airport, SeatType
+from fli.search import SearchFlights
+from fli.models import (
+ FlightSearchFilters, FlightSegment,
+ Airport, SeatType, TripType, PassengerInfo
+)
+
+# Create flight segment
+flight_segments = [
+ FlightSegment(
+ departure_airport=[[Airport.JFK, 0]],
+ arrival_airport=[[Airport.LAX, 0]],
+ travel_date="2024-06-01"
+ )
+]
# Create filters
-filters = SearchFlightsFilters(
- departure_airport=Airport.JFK,
- arrival_airport=Airport.LAX,
- departure_date="2024-06-01",
+filters = FlightSearchFilters(
+ trip_type=TripType.ONE_WAY,
+ passenger_info=PassengerInfo(adults=1),
+ flight_segments=flight_segments,
seat_type=SeatType.ECONOMY
)
@@ -78,7 +88,58 @@ for flight in results:
print(f"Flight: {leg.airline.value} {leg.flight_number}")
```
-2. Date Range Search:
+2. Round Trip Flight Search:
+
+```python
+from fli.search import SearchFlights
+from fli.models import (
+ FlightSearchFilters, FlightSegment,
+ Airport, TripType, PassengerInfo
+)
+
+# Create flight segments for round trip
+flight_segments = [
+ FlightSegment(
+ departure_airport=[[Airport.JFK, 0]],
+ arrival_airport=[[Airport.LAX, 0]],
+ travel_date="2024-06-01"
+ ),
+ FlightSegment(
+ departure_airport=[[Airport.LAX, 0]],
+ arrival_airport=[[Airport.JFK, 0]],
+ travel_date="2024-06-15"
+ )
+]
+
+# Create filters
+filters = FlightSearchFilters(
+ trip_type=TripType.ROUND_TRIP,
+ passenger_info=PassengerInfo(adults=1),
+ flight_segments=flight_segments
+)
+
+# Search flights
+search = SearchFlights()
+results = search.search(filters)
+
+# Process results
+for flight in results:
+ print(f"\nOutbound Flight:")
+ for leg in flight.outbound.legs:
+ print(f"Flight: {leg.airline.value} {leg.flight_number}")
+ print(f"Departure: {leg.departure_datetime}")
+ print(f"Arrival: {leg.arrival_datetime}")
+
+ print(f"\nReturn Flight:")
+ for leg in flight.return_flight.legs:
+ print(f"Flight: {leg.airline.value} {leg.flight_number}")
+ print(f"Departure: {leg.departure_datetime}")
+ print(f"Arrival: {leg.arrival_datetime}")
+
+ print(f"\nTotal Price: ${flight.total_price}")
+```
+
+3. Date Range Search:
```python
from fli.search import SearchDates
diff --git a/fli/cli/commands/cheap.py b/fli/cli/commands/cheap.py
index 86ca391..9fac396 100644
--- a/fli/cli/commands/cheap.py
+++ b/fli/cli/commands/cheap.py
@@ -9,6 +9,7 @@ from fli.cli.utils import (
filter_dates_by_days,
parse_airlines,
parse_stops,
+ parse_trip_type,
validate_date,
validate_time_range,
)
@@ -19,6 +20,7 @@ from fli.models import (
PassengerInfo,
SeatType,
TimeRestrictions,
+ TripType,
)
from fli.search import SearchDates
@@ -32,6 +34,14 @@ def cheap(
to_date: Annotated[
str, typer.Option("--to", help="End date (YYYY-MM-DD)", callback=validate_date)
] = (datetime.now() + timedelta(days=60)).strftime("%Y-%m-%d"),
+ duration: Annotated[
+ int,
+ typer.Option(
+ "--duration",
+ "-d",
+ help="Duration of trip in days",
+ ),
+ ] = 3,
airlines: Annotated[
list[str] | None,
typer.Option(
@@ -40,14 +50,14 @@ def cheap(
help="List of airline codes (e.g., BA KL)",
),
] = None,
- seat: Annotated[
+ trip_type: Annotated[
str,
typer.Option(
- "--class",
- "-c",
- help="Seat type (ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST)",
+ "--type",
+ "-t",
+ help="Trip type (ONEWAY, ROUND)",
),
- ] = "ECONOMY",
+ ] = "ONEWAY",
stops: Annotated[
str,
typer.Option(
@@ -56,6 +66,14 @@ def cheap(
help="Maximum number of stops (ANY, 0 for non-stop, 1 for one stop, 2+ for two stops)",
),
] = "ANY",
+ seat: Annotated[
+ str,
+ typer.Option(
+ "--class",
+ "-c",
+ help="Seat type (ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST)",
+ ),
+ ] = "ECONOMY",
sort: Annotated[
bool,
typer.Option(
@@ -123,7 +141,7 @@ def cheap(
str | None,
typer.Option(
"--time",
- "-t",
+ "-time",
help="Time range in 24h format (e.g., 6-20)",
callback=validate_time_range,
),
@@ -139,8 +157,10 @@ def cheap(
# Parse parameters
departure_airport = getattr(Airport, from_airport.upper())
arrival_airport = getattr(Airport, to_airport.upper())
- seat_type = getattr(SeatType, seat.upper())
+ trip_type = parse_trip_type(trip_type)
max_stops = parse_stops(stops)
+ seat_type = getattr(SeatType, seat.upper())
+ airlines = parse_airlines(airlines)
# Parse time restrictions
time_restrictions = None
@@ -164,15 +184,33 @@ def cheap(
time_restrictions=time_restrictions,
)
+ # Handle round trip
+ if trip_type == TripType.ROUND_TRIP:
+ return_flight_segment = FlightSegment(
+ departure_airport=[[arrival_airport, 0]],
+ arrival_airport=[[departure_airport, 0]],
+ travel_date=(
+ datetime.strptime(flight_segment.travel_date, "%Y-%m-%d")
+ + timedelta(days=duration)
+ ).strftime("%Y-%m-%d"),
+ time_restrictions=time_restrictions,
+ )
+
+ flight_segments = [flight_segment, return_flight_segment]
+ else:
+ flight_segments = [flight_segment]
+
# Create search filters
filters = DateSearchFilters(
+ trip_type=trip_type,
passenger_info=PassengerInfo(adults=1),
- flight_segments=[flight_segment],
+ flight_segments=flight_segments,
stops=max_stops,
seat_type=seat_type,
- airlines=parse_airlines(airlines),
+ airlines=airlines,
from_date=from_date,
to_date=to_date,
+ duration=duration if trip_type == TripType.ROUND_TRIP else None,
)
# Perform search
@@ -200,7 +238,8 @@ def cheap(
if sunday:
selected_days.append(DayOfWeek.SUNDAY)
- dates = filter_dates_by_days(dates, selected_days)
+ if selected_days:
+ dates = filter_dates_by_days(dates, selected_days, trip_type)
if not dates:
typer.echo("No flights found for the selected days.")
@@ -211,8 +250,10 @@ def cheap(
dates.sort(key=lambda x: x.price)
# Display results
- display_date_results(dates)
+ display_date_results(dates, trip_type)
except (AttributeError, ValueError) as e:
+ if "module 'fli.search' has no attribute 'SearchDates'" in str(e):
+ raise
typer.echo(f"Error: {str(e)}")
raise typer.Exit(1) from e
diff --git a/fli/cli/commands/search.py b/fli/cli/commands/search.py
index 4dcc973..182a915 100644
--- a/fli/cli/commands/search.py
+++ b/fli/cli/commands/search.py
@@ -4,8 +4,6 @@ import typer
from fli.cli.utils import (
display_flight_results,
- filter_flights_by_airlines,
- filter_flights_by_time,
parse_airlines,
parse_stops,
validate_date,
@@ -19,13 +17,16 @@ from fli.models import (
SeatType,
SortBy,
)
+from fli.models.google_flights.base import TimeRestrictions, TripType
from fli.search import SearchFlights
def search_flights(
+ trip_type: TripType,
from_airport: str,
to_airport: str,
date: str,
+ return_date: str | None = None,
time: tuple[int, int] | None = None,
airlines: list[str] | None = None,
seat: str = "ECONOMY",
@@ -39,20 +40,43 @@ def search_flights(
arrival_airport = getattr(Airport, to_airport.upper())
seat_type = getattr(SeatType, seat.upper())
max_stops = parse_stops(stops)
+ airlines = parse_airlines(airlines)
sort_by = getattr(SortBy, sort.upper())
+ time_restrictions = None
+ if time:
+ start_hour, end_hour = time
+ time_restrictions = TimeRestrictions(
+ earliest_departure=start_hour, latest_departure=end_hour
+ )
+
+ # Create flight segments
+ flight_segments = [
+ FlightSegment(
+ departure_airport=[[departure_airport, 0]],
+ arrival_airport=[[arrival_airport, 0]],
+ travel_date=date,
+ time_restrictions=time_restrictions,
+ )
+ ]
+ if return_date:
+ flight_segments.append(
+ FlightSegment(
+ departure_airport=[[arrival_airport, 0]],
+ arrival_airport=[[departure_airport, 0]],
+ travel_date=return_date,
+ time_restrictions=time_restrictions,
+ )
+ )
+
# Create search filters
filters = FlightSearchFilters(
+ trip_type=trip_type,
passenger_info=PassengerInfo(adults=1),
- flight_segments=[
- FlightSegment(
- departure_airport=[[departure_airport, 0]],
- arrival_airport=[[arrival_airport, 0]],
- travel_date=date,
- )
- ],
- seat_type=seat_type,
+ flight_segments=flight_segments,
stops=max_stops,
+ seat_type=seat_type,
+ airlines=airlines,
sort_by=sort_by,
)
@@ -64,16 +88,6 @@ def search_flights(
typer.echo("No flights found.")
raise typer.Exit(1)
- # Apply time filter if specified
- if time:
- start_hour, end_hour = time
- flights = filter_flights_by_time(flights, start_hour, end_hour)
-
- # Apply airline filter if specified
- airline_list = parse_airlines(airlines)
- if airline_list:
- flights = filter_flights_by_airlines(flights, airline_list)
-
# Display results
display_flight_results(flights)
@@ -86,6 +100,15 @@ def search(
from_airport: Annotated[str, typer.Argument(help="Departure airport code (e.g., JFK)")],
to_airport: Annotated[str, typer.Argument(help="Arrival airport code (e.g., LHR)")],
date: Annotated[str, typer.Argument(help="Travel date (YYYY-MM-DD)", callback=validate_date)],
+ return_date: Annotated[
+ str | None,
+ typer.Option(
+ "--return",
+ "-r",
+ help="Return date (YYYY-MM-DD)",
+ callback=validate_date,
+ ),
+ ] = None,
time: Annotated[
str | None,
typer.Option(
@@ -135,9 +158,11 @@ def search(
"""
search_flights(
+ trip_type=TripType.ROUND_TRIP if return_date else TripType.ONE_WAY,
from_airport=from_airport,
to_airport=to_airport,
date=date,
+ return_date=return_date,
time=time,
airlines=airlines,
seat=seat,
diff --git a/fli/cli/utils.py b/fli/cli/utils.py
index 6f4e9ed..c7ffdfa 100644
--- a/fli/cli/utils.py
+++ b/fli/cli/utils.py
@@ -10,11 +10,14 @@ from rich.text import Text
from fli.cli.console import console
from fli.cli.enums import DayOfWeek
-from fli.models import Airline, Airport, MaxStops
+from fli.models import Airline, Airport, MaxStops, TripType
-def validate_date(ctx: Context, param: Parameter, value: str) -> str:
+def validate_date(ctx: Context, param: Parameter, value: str) -> str | None:
"""Validate date format."""
+ if value is None:
+ return None
+
try:
datetime.strptime(value, "%Y-%m-%d")
return value
@@ -38,6 +41,19 @@ def validate_time_range(
raise typer.BadParameter("Time range must be in format 'start-end' (e.g., 6-20)") from e
+def parse_airlines(airlines: list[str] | None) -> list[Airline] | None:
+ """Parse airlines from list of airline codes."""
+ if not airlines:
+ return None
+
+ try:
+ return [
+ getattr(Airline, airline.strip().upper()) for airline in airlines if airline.strip()
+ ]
+ except AttributeError as e:
+ raise typer.BadParameter(f"Invalid airline code: {str(e)}") from e
+
+
def parse_stops(stops: str) -> MaxStops:
"""Convert stops parameter to MaxStops enum."""
# Try parsing as integer first
@@ -59,17 +75,15 @@ def parse_stops(stops: str) -> MaxStops:
raise typer.BadParameter(f"Invalid stops value: {stops}") from e
-def parse_airlines(airlines: list[str] | None) -> list[Airline] | None:
- """Parse airlines from list of airline codes."""
- if not airlines:
- return None
-
- try:
- return [
- getattr(Airline, airline.strip().upper()) for airline in airlines if airline.strip()
- ]
- except AttributeError as e:
- raise typer.BadParameter(f"Invalid airline code: {str(e)}") from e
+def parse_trip_type(trip_type: str) -> TripType:
+ """Convert trip type parameter to TripType enum."""
+ match trip_type.upper():
+ case "ONEWAY" | "ONE_WAY":
+ return TripType.ONE_WAY
+ case "ROUND" | "ROUND_TRIP":
+ return TripType.ROUND_TRIP
+ case _:
+ raise typer.BadParameter(f"Invalid trip type: {trip_type}")
def filter_flights_by_time(flights: list, start_hour: int, end_hour: int) -> list:
@@ -86,7 +100,7 @@ def filter_flights_by_airlines(flights: list, airlines: list[Airline]) -> list:
return [flight for flight in flights if any(leg.airline in airlines for leg in flight.legs)]
-def filter_dates_by_days(dates: list, days: list[DayOfWeek]) -> list:
+def filter_dates_by_days(dates: list, days: list[DayOfWeek], trip_type: TripType) -> list:
"""Filter dates by days of the week."""
if not days:
return dates
@@ -102,7 +116,7 @@ def filter_dates_by_days(dates: list, days: list[DayOfWeek]) -> list:
}
allowed_days = {day_numbers[day] for day in days}
- return [date_price for date_price in dates if date_price.date.weekday() in allowed_days]
+ return [date_price for date_price in dates if date_price.date[0].weekday() in allowed_days]
def format_airport(airport: Airport) -> str:
@@ -120,51 +134,78 @@ def format_duration(minutes: int) -> str:
def display_flight_results(flights: list):
- """Display flight results in a beautiful format."""
+ """Display flight results in a beautiful format.
+
+ Args:
+ flights: List of either FlightResult objects (one-way)
+ or tuples of (outbound, return) FlightResults (round-trip)
+
+ """
if not flights:
console.print(Panel("No flights found matching your criteria", style="red"))
return
- for i, flight in enumerate(flights, 1):
+ for i, flight_data in enumerate(flights, 1):
+ is_round_trip = isinstance(flight_data, tuple)
+ flight_segments = [flight_data] if not is_round_trip else [flight_data[0], flight_data[1]]
+
# Create main flight info table
table = Table(show_header=False, box=box.SIMPLE)
table.add_column("Label", style="blue")
table.add_column("Value", style="green")
- table.add_row("Price", f"${flight.price:,.2f}")
- table.add_row("Duration", format_duration(flight.duration))
- table.add_row("Stops", str(flight.stops))
-
- # Create segments table
- segments = Table(title="Flight Segments", box=box.ROUNDED)
- segments.add_column("Airline", style="cyan")
- segments.add_column("Flight", style="magenta")
- segments.add_column("From", style="yellow", width=30)
- segments.add_column("Departure", style="green")
- segments.add_column("To", style="yellow", width=30)
- segments.add_column("Arrival", style="green")
-
- for leg in flight.legs:
- segments.add_row(
- leg.airline.value,
- leg.flight_number,
- format_airport(leg.departure_airport),
- leg.departure_datetime.strftime("%H:%M %d-%b"),
- format_airport(leg.arrival_airport),
- leg.arrival_datetime.strftime("%H:%M %d-%b"),
+ total_price = flight_segments[0].price
+ if is_round_trip:
+ total_price += flight_segments[1].price
+ table.add_row("Total Price", f"${total_price:,.2f}")
+
+ if is_round_trip:
+ table.add_row("Outbound Price", f"${flight_segments[0].price:,.2f}")
+ table.add_row("Return Price", f"${flight_segments[1].price:,.2f}")
+
+ total_duration = sum(flight.duration for flight in flight_segments)
+ table.add_row("Total Duration", format_duration(total_duration))
+ total_stops = sum(flight.stops for flight in flight_segments)
+ table.add_row("Total Stops", str(total_stops))
+
+ # Create segments tables for each direction
+ all_segments = []
+ for idx, flight in enumerate(flight_segments):
+ direction = "Outbound" if idx == 0 else "Return" if is_round_trip else ""
+ segments = Table(
+ title=f"{direction} Flight Segments" if direction else "Flight Segments",
+ box=box.ROUNDED,
)
+ segments.add_column("Airline", style="cyan")
+ segments.add_column("Flight", style="magenta")
+ segments.add_column("From", style="yellow", width=30)
+ segments.add_column("Departure", style="green")
+ segments.add_column("To", style="yellow", width=30)
+ segments.add_column("Arrival", style="green")
+
+ for leg in flight.legs:
+ segments.add_row(
+ leg.airline.value,
+ leg.flight_number,
+ format_airport(leg.departure_airport),
+ leg.departure_datetime.strftime("%H:%M %d-%b"),
+ format_airport(leg.arrival_airport),
+ leg.arrival_datetime.strftime("%H:%M %d-%b"),
+ )
+ all_segments.extend([segments, Text("")])
# Display in a panel
+ title = "Round-trip Flight" if is_round_trip else "One-way Flight"
console.print(
Panel(
Group(
- Text(f"Flight Option {i}", style="bold blue"),
+ Text(f"{title} Option {i}", style="bold blue"),
Text(""),
table,
Text(""),
- segments,
+ *all_segments[:-1], # Remove the last empty Text
),
- title=f"[bold]Flight {i} of {len(flights)}[/bold]",
+ title=f"[bold]Option {i} of {len(flights)}[/bold]",
border_style="blue",
box=box.ROUNDED,
)
@@ -172,23 +213,35 @@ def display_flight_results(flights: list):
console.print()
-def display_date_results(dates: list):
+def display_date_results(dates: list, trip_type: TripType):
"""Display date search results in a beautiful format."""
if not dates:
console.print(Panel("No flights found for these dates", style="red"))
return
table = Table(title="Cheapest Dates to Fly", box=box.ROUNDED)
- table.add_column("Date", style="cyan")
+ table.add_column("Departure", style="cyan")
table.add_column("Day", style="yellow")
+ if trip_type == TripType.ROUND_TRIP:
+ table.add_column("Return", style="cyan")
+ table.add_column("Day", style="yellow")
table.add_column("Price", style="green")
for date_price in dates:
- table.add_row(
- date_price.date.strftime("%Y-%m-%d"),
- date_price.date.strftime("%A"),
- f"${date_price.price:,.2f}",
- )
+ if trip_type == TripType.ONE_WAY:
+ table.add_row(
+ date_price.date[0].strftime("%Y-%m-%d"),
+ date_price.date[0].strftime("%A"),
+ f"${date_price.price:,.2f}",
+ )
+ else:
+ table.add_row(
+ date_price.date[0].strftime("%Y-%m-%d"),
+ date_price.date[0].strftime("%A"),
+ date_price.date[1].strftime("%Y-%m-%d"),
+ date_price.date[1].strftime("%A"),
+ f"${date_price.price:,.2f}",
+ )
console.print(table)
console.print()
diff --git a/fli/models/__init__.py b/fli/models/__init__.py
index fcadf3f..21d0fd1 100644
--- a/fli/models/__init__.py
+++ b/fli/models/__init__.py
@@ -13,6 +13,7 @@ from .google_flights import (
SeatType,
SortBy,
TimeRestrictions,
+ TripType,
)
__all__ = [
@@ -30,4 +31,5 @@ __all__ = [
"SeatType",
"SortBy",
"TimeRestrictions",
+ "TripType",
]
diff --git a/fli/models/google_flights.py b/fli/models/google_flights.py
deleted file mode 100644
index ab05f50..0000000
--- a/fli/models/google_flights.py
+++ /dev/null
@@ -1,551 +0,0 @@
-"""Models for interacting with Google Flights API.
-
-This module contains all the data models used for flight searches and results.
-Models are designed to match Google Flights' APIs while providing a clean pythonic interface.
-"""
-
-import json
-import urllib.parse
-from datetime import datetime
-from enum import Enum
-
-from pydantic import (
- BaseModel,
- NonNegativeFloat,
- NonNegativeInt,
- PositiveInt,
- ValidationInfo,
- field_validator,
- model_validator,
-)
-
-from .airline import Airline
-from .airport import Airport
-
-
-class SeatType(Enum):
- """Available cabin classes for flights."""
-
- ECONOMY = 1
- PREMIUM_ECONOMY = 2
- BUSINESS = 3
- FIRST = 4
-
-
-class SortBy(Enum):
- """Available sorting options for flight results."""
-
- NONE = 0
- TOP_FLIGHTS = 1
- CHEAPEST = 2
- DEPARTURE_TIME = 3
- ARRIVAL_TIME = 4
- DURATION = 5
-
-
-class TripType(Enum):
- """Type of flight journey. Currently only supports one-way flights."""
-
- ONE_WAY = 2
-
- # Currently not supported - kept for future reference
- _ROUND_TRIP = 1 # Deprecated
- _MULTI_CITY = 3 # Deprecated
-
-
-class MaxStops(Enum):
- """Maximum number of stops allowed in flight search."""
-
- ANY = 0
- NON_STOP = 1
- ONE_STOP_OR_FEWER = 2
- TWO_OR_FEWER_STOPS = 3
-
-
-class Currency(Enum):
- """Supported currencies for pricing. Currently only USD."""
-
- USD = "USD"
- # Placeholder for other currencies
-
-
-class TimeRestrictions(BaseModel):
- """Time constraints for flight departure and arrival in local time.
-
- All times are in hours from midnight (e.g., 20 = 8:00 PM).
- """
-
- earliest_departure: NonNegativeInt | None = None
- latest_departure: PositiveInt | None = None
- earliest_arrival: NonNegativeInt | None = None
- latest_arrival: PositiveInt | None = None
-
- @field_validator("latest_departure", "latest_arrival")
- @classmethod
- def validate_latest_times(
- cls, v: PositiveInt | None, info: ValidationInfo
- ) -> PositiveInt | None:
- """Validate and adjust the latest time restrictions."""
- if v is None:
- return v
-
- # Get "departure" or "arrival" from field name
- field_prefix = "earliest_" + info.field_name[7:]
- earliest = info.data.get(field_prefix)
-
- # Swap values to ensure that `from` is always before `to`
- if earliest is not None and earliest > v:
- info.data[field_prefix] = v
- return earliest
- return v
-
-
-class PassengerInfo(BaseModel):
- """Passenger configuration for flight search."""
-
- adults: NonNegativeInt = 1
- children: NonNegativeInt = 0
- infants_in_seat: NonNegativeInt = 0
- infants_on_lap: NonNegativeInt = 0
-
-
-class PriceLimit(BaseModel):
- """Maximum price constraint for flight search."""
-
- max_price: PositiveInt
- currency: Currency | None = Currency.USD
-
-
-class LayoverRestrictions(BaseModel):
- """Constraints for layovers in multi-leg flights."""
-
- airports: list[Airport] | None = None
- max_duration: PositiveInt | None = None
-
-
-class FlightSegment(BaseModel):
- """A segment represents a single portion of a flight journey between two airports.
-
- For example, in a one-way flight from JFK to LAX, there would be one segment.
- In a multi-city trip from JFK -> LAX -> SEA, there would be two segments:
- JFK -> LAX and LAX -> SEA.
- """
-
- departure_airport: list[list[Airport | int]]
- arrival_airport: list[list[Airport | int]]
- travel_date: str
- time_restrictions: TimeRestrictions | None = None
-
- @property
- def parsed_travel_date(self) -> datetime:
- """Parse the travel date string into a datetime object."""
- return datetime.strptime(self.travel_date, "%Y-%m-%d")
-
- @field_validator("travel_date")
- @classmethod
- def validate_travel_date(cls, v: str) -> str:
- """Validate that the travel date is not in the past."""
- travel_date = datetime.strptime(v, "%Y-%m-%d").date()
- if travel_date < datetime.now().date():
- raise ValueError("Travel date cannot be in the past")
- return v
-
- @model_validator(mode="after")
- def validate_airports(self) -> "FlightSegment":
- """Validate that departure and arrival airports are different."""
- if not self.departure_airport or not self.arrival_airport:
- raise ValueError("Both departure and arrival airports must be specified")
-
- # Get first airport from each nested list
- dep_airport = (
- self.departure_airport[0][0]
- if isinstance(self.departure_airport[0][0], Airport)
- else None
- )
- arr_airport = (
- self.arrival_airport[0][0] if isinstance(self.arrival_airport[0][0], Airport) else None
- )
-
- if dep_airport and arr_airport and dep_airport == arr_airport:
- raise ValueError("Departure and arrival airports must be different")
- return self
-
-
-class FlightLeg(BaseModel):
- """A single flight leg (segment) with airline and timing details."""
-
- airline: Airline
- flight_number: str
- departure_airport: Airport
- arrival_airport: Airport
- departure_datetime: datetime
- arrival_datetime: datetime
- duration: PositiveInt # in minutes
-
-
-class FlightResult(BaseModel):
- """Complete flight search result with pricing and timing."""
-
- legs: list[FlightLeg]
- price: NonNegativeFloat # in specified currency
- duration: PositiveInt # total duration in minutes
- stops: NonNegativeInt
-
-
-class FlightSearchFilters(BaseModel):
- """Complete set of filters for flight search.
-
- This model matches required Google Flights' API structure.
- """
-
- trip_type: TripType = TripType.ONE_WAY
- passenger_info: PassengerInfo
- flight_segments: list[FlightSegment]
- stops: MaxStops = MaxStops.ANY
- seat_type: SeatType = SeatType.ECONOMY
- price_limit: PriceLimit | None = None
- airlines: list[Airline] | None = None
- max_duration: PositiveInt | None = None
- layover_restrictions: LayoverRestrictions | None = None
- sort_by: SortBy = SortBy.NONE
-
- def format(self) -> list:
- """Format filters into Google Flights API structure.
-
- This method converts the FlightSearchFilters model into the specific nested list/dict
- structure required by Google Flights' API.
-
- The output format matches Google Flights' internal API structure, with careful handling
- of nested arrays and proper serialization of enums and model objects.
-
- Returns:
- list: A formatted list structure ready for the Google Flights API request
-
- """
-
- def serialize(obj):
- if isinstance(obj, Airport) or isinstance(obj, Airline):
- return obj.name
- if isinstance(obj, Enum):
- return obj.value
- if isinstance(obj, list):
- return [serialize(item) for item in obj]
- if isinstance(obj, dict):
- return {key: serialize(value) for key, value in obj.items()}
- if isinstance(obj, BaseModel):
- return serialize(obj.dict(exclude_none=True))
- return obj
-
- # Format flight segments
- formatted_segments = []
- for segment in self.flight_segments:
- # Format airport codes with correct nesting
- segment_filters = [
- [
- [
- [serialize(airport[0]), serialize(airport[1])]
- for airport in segment.departure_airport
- ]
- ],
- [
- [
- [serialize(airport[0]), serialize(airport[1])]
- for airport in segment.arrival_airport
- ]
- ],
- ]
-
- # Time restrictions
- if segment.time_restrictions:
- time_filters = [
- segment.time_restrictions.earliest_departure,
- segment.time_restrictions.latest_departure,
- segment.time_restrictions.earliest_arrival,
- segment.time_restrictions.latest_arrival,
- ]
- else:
- time_filters = None
-
- # Airlines
- airlines_filters = None
- if self.airlines:
- sorted_airlines = sorted(self.airlines, key=lambda x: x.value)
- airlines_filters = [serialize(airline) for airline in sorted_airlines]
-
- # Layover restrictions
- layover_airports = (
- [serialize(a) for a in self.layover_restrictions.airports]
- if self.layover_restrictions and self.layover_restrictions.airports
- else None
- )
- layover_duration = (
- self.layover_restrictions.max_duration if self.layover_restrictions else None
- )
-
- segment_formatted = [
- segment_filters[0], # departure airport
- segment_filters[1], # arrival airport
- time_filters, # time restrictions
- serialize(self.stops.value), # stops
- airlines_filters, # airlines
- None, # placeholder
- segment.travel_date, # travel date
- [self.max_duration] if self.max_duration else None, # max duration
- None, # placeholder
- layover_airports, # layover airports
- None, # placeholder
- None, # placeholder
- layover_duration, # layover duration
- None, # emissions
- 3, # constant value
- ]
- formatted_segments.append(segment_formatted)
-
- # Create the main filters structure
- filters = [
- [], # empty array at start
- [
- None, # placeholder
- None, # placeholder
- serialize(self.trip_type.value),
- None, # placeholder
- [], # empty array
- serialize(self.seat_type.value),
- [
- self.passenger_info.adults,
- self.passenger_info.children,
- self.passenger_info.infants_on_lap,
- self.passenger_info.infants_in_seat,
- ],
- [None, self.price_limit.max_price] if self.price_limit else None,
- None, # placeholder
- None, # placeholder
- None, # placeholder
- None, # placeholder
- None, # placeholder
- formatted_segments,
- None, # placeholder
- None, # placeholder
- None, # placeholder
- 1, # placeholder (hardcoded to 1)
- ],
- serialize(self.sort_by.value),
- 0, # constant
- 0, # constant
- 2, # constant
- ]
-
- return filters
-
- def encode(self) -> str:
- """URL encode the formatted filters for API request."""
- formatted_filters = self.format()
- # First convert the formatted filters to a JSON string
- formatted_json = json.dumps(formatted_filters, separators=(",", ":"))
- # Then wrap it in a list with null
- wrapped_filters = [None, formatted_json]
- # Finally, encode the whole thing
- return urllib.parse.quote(json.dumps(wrapped_filters, separators=(",", ":")))
-
-
-class DateSearchFilters(BaseModel):
- """Filters for searching flights across a date range.
-
- Similar to FlightSearchFilters but includes date range parameters
- for finding the cheapest dates to fly.
- """
-
- trip_type: TripType = TripType.ONE_WAY
- passenger_info: PassengerInfo
- flight_segments: list[FlightSegment]
- stops: MaxStops = MaxStops.ANY
- seat_type: SeatType = SeatType.ECONOMY
- price_limit: PriceLimit | None = None
- airlines: list[Airline] | None = None
- max_duration: PositiveInt | None = None
- layover_restrictions: LayoverRestrictions | None = None
- from_date: str
- to_date: str
-
- @property
- def parsed_from_date(self) -> datetime:
- """Parse the from_date string into a datetime object."""
- return datetime.strptime(self.from_date, "%Y-%m-%d")
-
- @property
- def parsed_to_date(self) -> datetime:
- """Parse the to_date string into a datetime object."""
- return datetime.strptime(self.to_date, "%Y-%m-%d")
-
- @field_validator("from_date", "to_date")
- @classmethod
- def validate_date_order(cls, v: str, info: ValidationInfo) -> str:
- """Validate and adjust the date range constraints."""
- if info.field_name == "from_date":
- # Remove the past date check since we'll handle it in model validator
- return v
-
- # For to_date, check if it's after from_date
- if "from_date" in info.data:
- from_date = datetime.strptime(info.data["from_date"], "%Y-%m-%d").date()
- to_date = datetime.strptime(v, "%Y-%m-%d").date()
- if from_date > to_date:
- # Swap dates by returning the from_date
- info.data["from_date"] = v
- return from_date.strftime("%Y-%m-%d")
- return v
-
- @field_validator("to_date")
- @classmethod
- def validate_to_date(cls, v: str) -> str:
- """Validate that to_date is in the future."""
- to_date = datetime.strptime(v, "%Y-%m-%d").date()
- if to_date <= datetime.now().date():
- raise ValueError("To date must be in the future")
- return v
-
- @model_validator(mode="after")
- def validate_and_adjust_from_date(self) -> "DateSearchFilters":
- """Adjust from_date to current date if it's in the past."""
- from_date = self.parsed_from_date.date()
- current_date = datetime.now().date()
-
- if from_date < current_date:
- self.from_date = current_date.strftime("%Y-%m-%d")
-
- return self
-
- def format(self) -> list:
- """Format filters into Google Flights API structure.
-
- This method converts the DateSearchFilters model into the specific nested list/dict
- structure required by Google Flights' API.
-
- Returns:
- list: A formatted list structure ready for the Google Flights API request
-
- """
-
- def serialize(obj):
- if isinstance(obj, Airport) or isinstance(obj, Airline):
- return obj.name
- if isinstance(obj, Enum):
- return obj.value
- if isinstance(obj, list):
- return [serialize(item) for item in obj]
- if isinstance(obj, dict):
- return {key: serialize(value) for key, value in obj.items()}
- if isinstance(obj, BaseModel):
- return serialize(obj.dict(exclude_none=True))
- return obj
-
- # Format flight segments
- formatted_segments = []
- for segment in self.flight_segments:
- # Format airport codes with correct nesting
- segment_filters = [
- [
- [
- [serialize(airport[0]), serialize(airport[1])]
- for airport in segment.departure_airport
- ]
- ],
- [
- [
- [serialize(airport[0]), serialize(airport[1])]
- for airport in segment.arrival_airport
- ]
- ],
- ]
-
- # Time restrictions
- if segment.time_restrictions:
- time_filters = [
- segment.time_restrictions.earliest_departure,
- segment.time_restrictions.latest_departure,
- segment.time_restrictions.earliest_arrival,
- segment.time_restrictions.latest_arrival,
- ]
- else:
- time_filters = None
-
- # Airlines
- airlines_filters = None
- if self.airlines:
- sorted_airlines = sorted(self.airlines, key=lambda x: x.value)
- airlines_filters = [serialize(airline) for airline in sorted_airlines]
-
- # Layover restrictions
- layover_airports = (
- [serialize(a) for a in self.layover_restrictions.airports]
- if self.layover_restrictions and self.layover_restrictions.airports
- else None
- )
- layover_duration = (
- self.layover_restrictions.max_duration if self.layover_restrictions else None
- )
-
- segment_formatted = [
- segment_filters[0], # departure airport
- segment_filters[1], # arrival airport
- time_filters, # time restrictions
- serialize(self.stops.value), # stops
- airlines_filters, # airlines
- None, # placeholder
- segment.travel_date, # travel date
- [self.max_duration] if self.max_duration else None, # max duration
- None, # placeholder
- layover_airports, # layover airports
- None, # placeholder
- None, # placeholder
- layover_duration, # layover duration
- None, # emissions
- 3, # constant value
- ]
- formatted_segments.append(segment_formatted)
-
- # Create the main filters structure
- filters = [
- None, # placeholder
- [
- None, # placeholder
- None, # placeholder
- serialize(self.trip_type.value),
- None, # placeholder
- [], # empty array
- serialize(self.seat_type.value),
- [
- self.passenger_info.adults,
- self.passenger_info.children,
- self.passenger_info.infants_on_lap,
- self.passenger_info.infants_in_seat,
- ],
- [None, self.price_limit.max_price] if self.price_limit else None,
- None, # placeholder
- None, # placeholder
- None, # placeholder
- None, # placeholder
- None, # placeholder
- formatted_segments,
- None, # placeholder
- None, # placeholder
- None, # placeholder
- 1, # placeholder (hardcoded to 1)
- ],
- [
- serialize(self.from_date),
- serialize(self.to_date),
- ],
- ]
-
- return filters
-
- def encode(self) -> str:
- """URL encode the formatted filters for API request."""
- formatted_filters = self.format()
- # First convert the formatted filters to a JSON string
- formatted_json = json.dumps(formatted_filters, separators=(",", ":"))
- # Then wrap it in a list with null
- wrapped_filters = [None, formatted_json]
- # Finally, encode the whole thing
- return urllib.parse.quote(json.dumps(wrapped_filters, separators=(",", ":")))
diff --git a/fli/models/google_flights/__init__.py b/fli/models/google_flights/__init__.py
new file mode 100644
index 0000000..d7f8dee
--- /dev/null
+++ b/fli/models/google_flights/__init__.py
@@ -0,0 +1,33 @@
+from .base import (
+ FlightLeg,
+ FlightResult,
+ FlightSegment,
+ LayoverRestrictions,
+ MaxStops,
+ PassengerInfo,
+ PriceLimit,
+ SeatType,
+ SortBy,
+ TimeRestrictions,
+ TripType,
+)
+from .dates import DateSearchFilters
+from .flights import FlightSearchFilters
+
+__all__ = [
+ "Airline",
+ "Airport",
+ "DateSearchFilters",
+ "FlightLeg",
+ "FlightResult",
+ "FlightSearchFilters",
+ "FlightSegment",
+ "LayoverRestrictions",
+ "MaxStops",
+ "PassengerInfo",
+ "PriceLimit",
+ "SeatType",
+ "SortBy",
+ "TimeRestrictions",
+ "TripType",
+]
diff --git a/fli/models/google_flights/base.py b/fli/models/google_flights/base.py
new file mode 100644
index 0000000..6894b1e
--- /dev/null
+++ b/fli/models/google_flights/base.py
@@ -0,0 +1,191 @@
+"""Models for interacting with Google Flights API.
+
+This module contains all the data models used for flight searches and results.
+Models are designed to match Google Flights' APIs while providing a clean pythonic interface.
+"""
+
+from datetime import datetime
+from enum import Enum
+
+from pydantic import (
+ BaseModel,
+ NonNegativeFloat,
+ NonNegativeInt,
+ PositiveInt,
+ ValidationInfo,
+ field_validator,
+ model_validator,
+)
+
+from fli.models.airline import Airline
+from fli.models.airport import Airport
+
+
+class SeatType(Enum):
+ """Available cabin classes for flights."""
+
+ ECONOMY = 1
+ PREMIUM_ECONOMY = 2
+ BUSINESS = 3
+ FIRST = 4
+
+
+class SortBy(Enum):
+ """Available sorting options for flight results."""
+
+ NONE = 0
+ TOP_FLIGHTS = 1
+ CHEAPEST = 2
+ DEPARTURE_TIME = 3
+ ARRIVAL_TIME = 4
+ DURATION = 5
+
+
+class TripType(Enum):
+ """Type of flight journey."""
+
+ ROUND_TRIP = 1
+ ONE_WAY = 2
+
+ # Currently not supported - kept for reference
+ _MULTI_CITY = 3 # Unsupported
+
+
+class MaxStops(Enum):
+ """Maximum number of stops allowed in flight search."""
+
+ ANY = 0
+ NON_STOP = 1
+ ONE_STOP_OR_FEWER = 2
+ TWO_OR_FEWER_STOPS = 3
+
+
+class Currency(Enum):
+ """Supported currencies for pricing. Currently only USD."""
+
+ USD = "USD"
+ # Placeholder for other currencies
+
+
+class TimeRestrictions(BaseModel):
+ """Time constraints for flight departure and arrival in local time.
+
+ All times are in hours from midnight (e.g., 20 = 8:00 PM).
+ """
+
+ earliest_departure: NonNegativeInt | None = None
+ latest_departure: PositiveInt | None = None
+ earliest_arrival: NonNegativeInt | None = None
+ latest_arrival: PositiveInt | None = None
+
+ @field_validator("latest_departure", "latest_arrival")
+ @classmethod
+ def validate_latest_times(
+ cls, v: PositiveInt | None, info: ValidationInfo
+ ) -> PositiveInt | None:
+ """Validate and adjust the latest time restrictions."""
+ if v is None:
+ return v
+
+ # Get "departure" or "arrival" from field name
+ field_prefix = "earliest_" + info.field_name[7:]
+ earliest = info.data.get(field_prefix)
+
+ # Swap values to ensure that `from` is always before `to`
+ if earliest is not None and earliest > v:
+ info.data[field_prefix] = v
+ return earliest
+ return v
+
+
+class PassengerInfo(BaseModel):
+ """Passenger configuration for flight search."""
+
+ adults: NonNegativeInt = 1
+ children: NonNegativeInt = 0
+ infants_in_seat: NonNegativeInt = 0
+ infants_on_lap: NonNegativeInt = 0
+
+
+class PriceLimit(BaseModel):
+ """Maximum price constraint for flight search."""
+
+ max_price: PositiveInt
+ currency: Currency | None = Currency.USD
+
+
+class LayoverRestrictions(BaseModel):
+ """Constraints for layovers in multi-leg flights."""
+
+ airports: list[Airport] | None = None
+ max_duration: PositiveInt | None = None
+
+
+class FlightLeg(BaseModel):
+ """A single flight leg (segment) with airline and timing details."""
+
+ airline: Airline
+ flight_number: str
+ departure_airport: Airport
+ arrival_airport: Airport
+ departure_datetime: datetime
+ arrival_datetime: datetime
+ duration: PositiveInt # in minutes
+
+
+class FlightResult(BaseModel):
+ """Complete flight search result with pricing and timing."""
+
+ legs: list[FlightLeg]
+ price: NonNegativeFloat # in specified currency
+ duration: PositiveInt # total duration in minutes
+ stops: NonNegativeInt
+
+
+class FlightSegment(BaseModel):
+ """A segment represents a single portion of a flight journey between two airports.
+
+ For example, in a one-way flight from JFK to LAX, there would be one segment.
+ In a multi-city trip from JFK -> LAX -> SEA, there would be two segments:
+ JFK -> LAX and LAX -> SEA.
+ """
+
+ departure_airport: list[list[Airport | int]]
+ arrival_airport: list[list[Airport | int]]
+ travel_date: str
+ time_restrictions: TimeRestrictions | None = None
+ selected_flight: FlightResult | None = None
+
+ @property
+ def parsed_travel_date(self) -> datetime:
+ """Parse the travel date string into a datetime object."""
+ return datetime.strptime(self.travel_date, "%Y-%m-%d")
+
+ @field_validator("travel_date")
+ @classmethod
+ def validate_travel_date(cls, v: str) -> str:
+ """Validate that the travel date is not in the past."""
+ travel_date = datetime.strptime(v, "%Y-%m-%d").date()
+ if travel_date < datetime.now().date():
+ raise ValueError("Travel date cannot be in the past")
+ return v
+
+ @model_validator(mode="after")
+ def validate_airports(self) -> "FlightSegment":
+ """Validate that departure and arrival airports are different."""
+ if not self.departure_airport or not self.arrival_airport:
+ raise ValueError("Both departure and arrival airports must be specified")
+
+ # Get first airport from each nested list
+ dep_airport = (
+ self.departure_airport[0][0]
+ if isinstance(self.departure_airport[0][0], Airport)
+ else None
+ )
+ arr_airport = (
+ self.arrival_airport[0][0] if isinstance(self.arrival_airport[0][0], Airport) else None
+ )
+
+ if dep_airport and arr_airport and dep_airport == arr_airport:
+ raise ValueError("Departure and arrival airports must be different")
+ return self
diff --git a/fli/models/google_flights/dates.py b/fli/models/google_flights/dates.py
new file mode 100644
index 0000000..9cb434a
--- /dev/null
+++ b/fli/models/google_flights/dates.py
@@ -0,0 +1,273 @@
+import json
+import urllib.parse
+from datetime import datetime
+from enum import Enum
+
+from pydantic import (
+ BaseModel,
+ PositiveInt,
+ ValidationInfo,
+ field_validator,
+ model_validator,
+)
+
+from fli.models.airline import Airline
+from fli.models.airport import Airport
+from fli.models.google_flights.base import (
+ FlightSegment,
+ LayoverRestrictions,
+ MaxStops,
+ PassengerInfo,
+ PriceLimit,
+ SeatType,
+ TripType,
+)
+
+
+class DateSearchFilters(BaseModel):
+ """Filters for searching flights across a date range.
+
+ Similar to FlightSearchFilters but includes date range parameters
+ for finding the cheapest dates to fly.
+ """
+
+ trip_type: TripType = TripType.ONE_WAY
+ passenger_info: PassengerInfo
+ flight_segments: list[FlightSegment]
+ stops: MaxStops = MaxStops.ANY
+ seat_type: SeatType = SeatType.ECONOMY
+ price_limit: PriceLimit | None = None
+ airlines: list[Airline] | None = None
+ max_duration: PositiveInt | None = None
+ layover_restrictions: LayoverRestrictions | None = None
+ from_date: str
+ to_date: str
+ duration: PositiveInt | None = None
+
+ @property
+ def parsed_from_date(self) -> datetime:
+ """Parse the from_date string into a datetime object."""
+ return datetime.strptime(self.from_date, "%Y-%m-%d")
+
+ @property
+ def parsed_to_date(self) -> datetime:
+ """Parse the to_date string into a datetime object."""
+ return datetime.strptime(self.to_date, "%Y-%m-%d")
+
+ @field_validator("duration")
+ @classmethod
+ def ensure_duration_if_round_trip(
+ cls, v: PositiveInt | None, info: ValidationInfo
+ ) -> PositiveInt | None:
+ """Ensure duration is set if trip_type is ROUND_TRIP."""
+ if "trip_type" in info.data and info.data["trip_type"] == TripType.ROUND_TRIP:
+ if v is None:
+ raise ValueError("Duration must be set for round trip flights")
+ return v
+
+ @field_validator("flight_segments")
+ @classmethod
+ def ensure_correct_flight_segments(
+ cls, v: list[FlightSegment], info: ValidationInfo
+ ) -> list[FlightSegment]:
+ """Ensure flight segments are correct."""
+ # Ensure only one flight segment if trip_type is ONE_WAY
+ if "trip_type" in info.data and info.data["trip_type"] == TripType.ONE_WAY:
+ if len(v) != 1:
+ raise ValueError("One-way trip must have one flight segment")
+ return v
+
+ # Ensure only two flight segments if trip_type is ROUND_TRIP
+ if "trip_type" in info.data and info.data["trip_type"] == TripType.ROUND_TRIP:
+ if len(v) != 2:
+ raise ValueError("Round trip must have two flight segments")
+
+ # Ensure the travel date difference is the same as the duration
+ if "duration" in info.data and info.data["duration"] is not None:
+ if len(v) == 2:
+ duration = info.data["duration"]
+ segment_difference = (v[1].parsed_travel_date - v[0].parsed_travel_date).days
+ if duration != segment_difference:
+ raise ValueError("Flight segments travel dates difference must match duration")
+
+ return v
+
+ @field_validator("from_date", "to_date")
+ @classmethod
+ def validate_date_order(cls, v: str, info: ValidationInfo) -> str:
+ """Validate and adjust the date range constraints."""
+ if info.field_name == "from_date":
+ # Remove the past date check since we'll handle it in model validator
+ return v
+
+ # Ensure to_date is after from_date
+ if "from_date" in info.data:
+ from_date = datetime.strptime(info.data["from_date"], "%Y-%m-%d").date()
+ to_date = datetime.strptime(v, "%Y-%m-%d").date()
+ if from_date > to_date:
+ # Swap dates by returning the from_date
+ info.data["from_date"] = v
+ return from_date.strftime("%Y-%m-%d")
+ return v
+
+ @field_validator("to_date")
+ @classmethod
+ def validate_to_date(cls, v: str) -> str:
+ """Validate that to_date is in the future."""
+ to_date = datetime.strptime(v, "%Y-%m-%d").date()
+ if to_date <= datetime.now().date():
+ raise ValueError("To date must be in the future")
+ return v
+
+ @model_validator(mode="after")
+ def validate_and_adjust_from_date(self) -> "DateSearchFilters":
+ """Adjust from_date to current date if it's in the past."""
+ from_date = self.parsed_from_date.date()
+ current_date = datetime.now().date()
+
+ if from_date < current_date:
+ self.from_date = current_date.strftime("%Y-%m-%d")
+
+ return self
+
+ def format(self) -> list:
+ """Format filters into Google Flights API structure.
+
+ This method converts the DateSearchFilters model into the specific nested list/dict
+ structure required by Google Flights' API.
+
+ Returns:
+ list: A formatted list structure ready for the Google Flights API request
+
+ """
+
+ def serialize(obj):
+ if isinstance(obj, Airport) or isinstance(obj, Airline):
+ return obj.name
+ if isinstance(obj, Enum):
+ return obj.value
+ if isinstance(obj, list):
+ return [serialize(item) for item in obj]
+ if isinstance(obj, dict):
+ return {key: serialize(value) for key, value in obj.items()}
+ if isinstance(obj, BaseModel):
+ return serialize(obj.dict(exclude_none=True))
+ return obj
+
+ # Format flight segments
+ formatted_segments = []
+ for segment in self.flight_segments:
+ # Format airport codes with correct nesting
+ segment_filters = [
+ [
+ [
+ [serialize(airport[0]), serialize(airport[1])]
+ for airport in segment.departure_airport
+ ]
+ ],
+ [
+ [
+ [serialize(airport[0]), serialize(airport[1])]
+ for airport in segment.arrival_airport
+ ]
+ ],
+ ]
+
+ # Time restrictions
+ if segment.time_restrictions:
+ time_filters = [
+ segment.time_restrictions.earliest_departure,
+ segment.time_restrictions.latest_departure,
+ segment.time_restrictions.earliest_arrival,
+ segment.time_restrictions.latest_arrival,
+ ]
+ else:
+ time_filters = None
+
+ # Airlines
+ airlines_filters = None
+ if self.airlines:
+ sorted_airlines = sorted(self.airlines, key=lambda x: x.value)
+ airlines_filters = [serialize(airline) for airline in sorted_airlines]
+
+ # Layover restrictions
+ layover_airports = (
+ [serialize(a) for a in self.layover_restrictions.airports]
+ if self.layover_restrictions and self.layover_restrictions.airports
+ else None
+ )
+ layover_duration = (
+ self.layover_restrictions.max_duration if self.layover_restrictions else None
+ )
+
+ segment_formatted = [
+ segment_filters[0], # departure airport
+ segment_filters[1], # arrival airport
+ time_filters, # time restrictions
+ serialize(self.stops.value), # stops
+ airlines_filters, # airlines
+ None, # placeholder
+ segment.travel_date, # travel date
+ [self.max_duration] if self.max_duration else None, # max duration
+ None, # placeholder
+ layover_airports, # layover airports
+ None, # placeholder
+ None, # placeholder
+ layover_duration, # layover duration
+ None, # emissions
+ 3, # constant value
+ ]
+ formatted_segments.append(segment_formatted)
+
+ # Format duration filters for round trips
+ if self.trip_type == TripType.ROUND_TRIP:
+ duration_filters = (None, [self.duration, self.duration])
+ else:
+ duration_filters = ()
+
+ # Create the main filters structure
+ filters = [
+ None, # placeholder
+ [
+ None, # placeholder
+ None, # placeholder
+ serialize(self.trip_type.value),
+ None, # placeholder
+ [], # empty array
+ serialize(self.seat_type.value),
+ [
+ self.passenger_info.adults,
+ self.passenger_info.children,
+ self.passenger_info.infants_on_lap,
+ self.passenger_info.infants_in_seat,
+ ],
+ [None, self.price_limit.max_price] if self.price_limit else None,
+ None, # placeholder
+ None, # placeholder
+ None, # placeholder
+ None, # placeholder
+ None, # placeholder
+ formatted_segments,
+ None, # placeholder
+ None, # placeholder
+ None, # placeholder
+ 1, # placeholder (hardcoded to 1)
+ ],
+ [
+ serialize(self.from_date),
+ serialize(self.to_date),
+ ],
+ *duration_filters,
+ ]
+
+ return filters
+
+ def encode(self) -> str:
+ """URL encode the formatted filters for API request."""
+ formatted_filters = self.format()
+ # First convert the formatted filters to a JSON string
+ formatted_json = json.dumps(formatted_filters, separators=(",", ":"))
+ # Then wrap it in a list with null
+ wrapped_filters = [None, formatted_json]
+ # Finally, encode the whole thing
+ return urllib.parse.quote(json.dumps(wrapped_filters, separators=(",", ":")))
diff --git a/fli/models/google_flights/flights.py b/fli/models/google_flights/flights.py
new file mode 100644
index 0000000..bc7d2a6
--- /dev/null
+++ b/fli/models/google_flights/flights.py
@@ -0,0 +1,192 @@
+import json
+import urllib.parse
+from enum import Enum
+
+from pydantic import (
+ BaseModel,
+ PositiveInt,
+)
+
+from fli.models.airline import Airline
+from fli.models.airport import Airport
+from fli.models.google_flights.base import (
+ FlightSegment,
+ LayoverRestrictions,
+ MaxStops,
+ PassengerInfo,
+ PriceLimit,
+ SeatType,
+ SortBy,
+ TripType,
+)
+
+
+class FlightSearchFilters(BaseModel):
+ """Complete set of filters for flight search.
+
+ This model matches required Google Flights' API structure.
+ """
+
+ trip_type: TripType = TripType.ONE_WAY
+ passenger_info: PassengerInfo
+ flight_segments: list[FlightSegment]
+ stops: MaxStops = MaxStops.ANY
+ seat_type: SeatType = SeatType.ECONOMY
+ price_limit: PriceLimit | None = None
+ airlines: list[Airline] | None = None
+ max_duration: PositiveInt | None = None
+ layover_restrictions: LayoverRestrictions | None = None
+ sort_by: SortBy = SortBy.NONE
+
+ def format(self) -> list:
+ """Format filters into Google Flights API structure.
+
+ This method converts the FlightSearchFilters model into the specific nested list/dict
+ structure required by Google Flights' API.
+
+ The output format matches Google Flights' internal API structure, with careful handling
+ of nested arrays and proper serialization of enums and model objects.
+
+ Returns:
+ list: A formatted list structure ready for the Google Flights API request
+
+ """
+
+ def serialize(obj):
+ if isinstance(obj, Airport) or isinstance(obj, Airline):
+ return obj.name
+ if isinstance(obj, Enum):
+ return obj.value
+ if isinstance(obj, list):
+ return [serialize(item) for item in obj]
+ if isinstance(obj, dict):
+ return {key: serialize(value) for key, value in obj.items()}
+ if isinstance(obj, BaseModel):
+ return serialize(obj.dict(exclude_none=True))
+ return obj
+
+ # Format flight segments
+ formatted_segments = []
+ for segment in self.flight_segments:
+ # Format airport codes with correct nesting
+ segment_filters = [
+ [
+ [
+ [serialize(airport[0]), serialize(airport[1])]
+ for airport in segment.departure_airport
+ ]
+ ],
+ [
+ [
+ [serialize(airport[0]), serialize(airport[1])]
+ for airport in segment.arrival_airport
+ ]
+ ],
+ ]
+
+ # Time restrictions
+ if segment.time_restrictions:
+ time_filters = [
+ segment.time_restrictions.earliest_departure,
+ segment.time_restrictions.latest_departure,
+ segment.time_restrictions.earliest_arrival,
+ segment.time_restrictions.latest_arrival,
+ ]
+ else:
+ time_filters = None
+
+ # Airlines
+ airlines_filters = None
+ if self.airlines:
+ sorted_airlines = sorted(self.airlines, key=lambda x: x.value)
+ airlines_filters = [serialize(airline) for airline in sorted_airlines]
+
+ # Layover restrictions
+ layover_airports = (
+ [serialize(a) for a in self.layover_restrictions.airports]
+ if self.layover_restrictions and self.layover_restrictions.airports
+ else None
+ )
+ layover_duration = (
+ self.layover_restrictions.max_duration if self.layover_restrictions else None
+ )
+
+ # Selected flight (to fetch return flights)
+ selected_flights = None
+ if self.trip_type == TripType.ROUND_TRIP and segment.selected_flight is not None:
+ selected_flights = [
+ [
+ serialize(leg.departure_airport.name),
+ serialize(leg.departure_datetime.strftime("%Y-%m-%d")),
+ serialize(leg.arrival_airport.name),
+ None,
+ serialize(leg.airline.name),
+ serialize(leg.flight_number),
+ ]
+ for leg in segment.selected_flight.legs
+ ]
+
+ segment_formatted = [
+ segment_filters[0], # departure airport
+ segment_filters[1], # arrival airport
+ time_filters, # time restrictions
+ serialize(self.stops.value), # stops
+ airlines_filters, # airlines
+ None, # placeholder
+ segment.travel_date, # travel date
+ [self.max_duration] if self.max_duration else None, # max duration
+ selected_flights, # selected flight (to fetch return flights)
+ layover_airports, # layover airports
+ None, # placeholder
+ None, # placeholder
+ layover_duration, # layover duration
+ None, # emissions
+ 3, # constant value
+ ]
+ formatted_segments.append(segment_formatted)
+
+ # Create the main filters structure
+ filters = [
+ [], # empty array at start
+ [
+ None, # placeholder
+ None, # placeholder
+ serialize(self.trip_type.value),
+ None, # placeholder
+ [], # empty array
+ serialize(self.seat_type.value),
+ [
+ self.passenger_info.adults,
+ self.passenger_info.children,
+ self.passenger_info.infants_on_lap,
+ self.passenger_info.infants_in_seat,
+ ],
+ [None, self.price_limit.max_price] if self.price_limit else None,
+ None, # placeholder
+ None, # placeholder
+ None, # placeholder
+ None, # placeholder
+ None, # placeholder
+ formatted_segments,
+ None, # placeholder
+ None, # placeholder
+ None, # placeholder
+ 1, # placeholder (hardcoded to 1)
+ ],
+ serialize(self.sort_by.value),
+ 0, # constant
+ 0, # constant
+ 2, # constant
+ ]
+
+ return filters
+
+ def encode(self) -> str:
+ """URL encode the formatted filters for API request."""
+ formatted_filters = self.format()
+ # First convert the formatted filters to a JSON string
+ formatted_json = json.dumps(formatted_filters, separators=(",", ":"))
+ # Then wrap it in a list with null
+ wrapped_filters = [None, formatted_json]
+ # Finally, encode the whole thing
+ return urllib.parse.quote(json.dumps(wrapped_filters, separators=(",", ":")))
diff --git a/fli/search/__init__.py b/fli/search/__init__.py
index 826e263..98a34cd 100644
--- a/fli/search/__init__.py
+++ b/fli/search/__init__.py
@@ -1,7 +1,8 @@
-from .dates import SearchDates
+from .dates import DatePrice, SearchDates
from .flights import SearchFlights
__all__ = [
"SearchFlights",
"SearchDates",
+ "DatePrice",
]
diff --git a/fli/search/dates.py b/fli/search/dates.py
index d91cb4b..7984542 100644
--- a/fli/search/dates.py
+++ b/fli/search/dates.py
@@ -3,8 +3,6 @@
This module provides functionality to search for the cheapest flights across a date range.
It uses Google Flights' calendar view API to find the best prices for each date.
It is intended to be used for finding the cheapest dates to fly, not the cheapest flights.
-
-Currently only supports one-way flights.
"""
import json
@@ -13,13 +11,14 @@ from datetime import datetime, timedelta
from pydantic import BaseModel
from fli.models import DateSearchFilters
+from fli.models.google_flights.base import TripType
from fli.search.client import get_client
class DatePrice(BaseModel):
"""Flight price for a specific date."""
- date: datetime
+ date: tuple[datetime] | tuple[datetime, datetime]
price: float
@@ -30,7 +29,7 @@ class SearchDates:
useful for finding the cheapest dates to fly.
"""
- BASE_URL = "https://www.google.com/_/FlightsFrontendUi/data/travel.frontend.flights.FlightsFrontendService/GetCalendarGrid"
+ BASE_URL = "https://www.google.com/_/FlightsFrontendUi/data/travel.frontend.flights.FlightsFrontendService/GetCalendarGraph"
DEFAULT_HEADERS = {
"content-type": "application/x-www-form-urlencoded;charset=UTF-8",
}
@@ -70,8 +69,17 @@ class SearchDates:
while current_from <= to_date:
current_to = min(current_from + timedelta(days=self.MAX_DAYS_PER_SEARCH - 1), to_date)
+ # Update the travel date for the flight segments
+ if current_from > from_date:
+ for segment in filters.flight_segments:
+ segment.travel_date = (
+ datetime.strptime(segment.travel_date, "%Y-%m-%d")
+ + timedelta(days=self.MAX_DAYS_PER_SEARCH)
+ ).strftime("%Y-%m-%d")
+
# Create new filters for this chunk
chunk_filters = DateSearchFilters(
+ trip_type=filters.trip_type,
passenger_info=filters.passenger_info,
flight_segments=filters.flight_segments,
stops=filters.stops,
@@ -79,6 +87,7 @@ class SearchDates:
airlines=filters.airlines,
from_date=current_from.strftime("%Y-%m-%d"),
to_date=current_to.strftime("%Y-%m-%d"),
+ duration=filters.duration,
)
chunk_results = self._search_chunk(chunk_filters)
@@ -119,7 +128,7 @@ class SearchDates:
data = json.loads(parsed)
dates_data = [
DatePrice(
- date=datetime.strptime(item[0], "%Y-%m-%d"),
+ date=self.__parse_date(item, filters.trip_type),
price=self.__parse_price(item),
)
for item in data[-1]
@@ -130,6 +139,28 @@ class SearchDates:
except Exception as e:
raise Exception(f"Search failed: {str(e)}") from e
+ @staticmethod
+ def __parse_date(
+ item: list[list] | list | None, trip_type: TripType
+ ) -> tuple[datetime] | tuple[datetime, datetime]:
+ """Parse date data from the API response.
+
+ Args:
+ item: Raw date data from the API response
+ trip_type: Trip type (one-way or round-trip)
+
+ Returns:
+ Tuple of datetime objects
+
+ """
+ if trip_type == TripType.ONE_WAY:
+ return (datetime.strptime(item[0], "%Y-%m-%d"),)
+ else:
+ return (
+ datetime.strptime(item[0], "%Y-%m-%d"),
+ datetime.strptime(item[1], "%Y-%m-%d"),
+ )
+
@staticmethod
def __parse_price(item: list[list] | list | None) -> float | None:
"""Parse price data from the API response.
diff --git a/fli/search/flights.py b/fli/search/flights.py
index 7061a70..c45e6cb 100644
--- a/fli/search/flights.py
+++ b/fli/search/flights.py
@@ -2,11 +2,10 @@
This module provides the core flight search functionality, interfacing directly
with Google Flights' API to find available flights and their details.
-
-Currently only supports one-way flights.
"""
import json
+from copy import deepcopy
from datetime import datetime
from fli.models import (
@@ -16,6 +15,7 @@ from fli.models import (
FlightResult,
FlightSearchFilters,
)
+from fli.models.google_flights.base import TripType
from fli.search.client import get_client
@@ -24,8 +24,6 @@ class SearchFlights:
This class handles searching for specific flights with detailed filters,
parsing the results into structured data models.
-
- Currently only supports one-way flights.
"""
BASE_URL = "https://www.google.com/_/FlightsFrontendUi/data/travel.frontend.flights.FlightsFrontendService/GetShoppingResults"
@@ -37,11 +35,14 @@ class SearchFlights:
"""Initialize the search client for flight searches."""
self.client = get_client()
- def search(self, filters: FlightSearchFilters) -> list[FlightResult] | None:
+ def search(
+ self, filters: FlightSearchFilters, top_n: int = 5
+ ) -> list[FlightResult | tuple[FlightResult, FlightResult]] | None:
"""Search for flights using the given FlightSearchFilters.
Args:
filters: Full flight search object including airports, dates, and preferences
+ top_n: Number of flights to limit the return flight search to
Returns:
List of FlightResult objects containing flight details, or None if no results
@@ -73,7 +74,26 @@ class SearchFlights:
for item in encoded_filters[i][0]
]
flights = [self._parse_flights_data(flight) for flight in flights_data]
- return flights
+
+ if (
+ filters.trip_type == TripType.ONE_WAY
+ or filters.flight_segments[0].selected_flight is not None
+ ):
+ return flights
+
+ # Get the return flights if round-trip
+ flight_pairs = []
+ # Call the search again with the return flight data
+ for selected_flight in flights[:top_n]:
+ selected_flight_filters = deepcopy(filters)
+ selected_flight_filters.flight_segments[0].selected_flight = selected_flight
+ return_flights = self.search(selected_flight_filters, top_n=top_n)
+ if return_flights is not None:
+ flight_pairs.extend(
+ (selected_flight, return_flight) for return_flight in return_flights
+ )
+
+ return flight_pairs
except Exception as e:
raise Exception(f"Search failed: {str(e)}") from e
diff --git a/tests/search/test_search_dates.py b/tests/search/test_search_dates.py
index bb3eafc..1b9b0ad 100644
--- a/tests/search/test_search_dates.py
+++ b/tests/search/test_search_dates.py
@@ -11,9 +11,10 @@ from fli.models import (
MaxStops,
PassengerInfo,
SeatType,
+ SortBy,
)
+from fli.models.google_flights.base import TripType
from fli.search import SearchDates
-from fli.search.dates import DatePrice
@pytest.fixture
@@ -27,9 +28,6 @@ def basic_search_params():
"""Create basic date search params for testing."""
today = datetime.now()
future_date = today + timedelta(days=30)
- start_date = future_date - timedelta(days=7)
- end_date = future_date + timedelta(days=7)
-
return DateSearchFilters(
passenger_info=PassengerInfo(
adults=1,
@@ -39,15 +37,16 @@ def basic_search_params():
),
flight_segments=[
FlightSegment(
- departure_airport=[[Airport.JFK, 0]],
+ departure_airport=[[Airport.PHX, 0]],
arrival_airport=[[Airport.SFO, 0]],
travel_date=future_date.strftime("%Y-%m-%d"),
)
],
stops=MaxStops.NON_STOP,
seat_type=SeatType.ECONOMY,
- from_date=start_date.strftime("%Y-%m-%d"),
- to_date=end_date.strftime("%Y-%m-%d"),
+ sort_by=SortBy.CHEAPEST,
+ from_date=(future_date - timedelta(days=30)).strftime("%Y-%m-%d"),
+ to_date=(future_date + timedelta(days=30)).strftime("%Y-%m-%d"),
)
@@ -56,27 +55,95 @@ def complex_search_params():
"""Create more complex date search params for testing."""
today = datetime.now()
future_date = today + timedelta(days=60)
- start_date = future_date - timedelta(days=20)
- end_date = future_date + timedelta(days=20)
-
return DateSearchFilters(
passenger_info=PassengerInfo(
- adults=1,
+ adults=2,
children=1,
infants_in_seat=0,
- infants_on_lap=0,
+ infants_on_lap=1,
),
flight_segments=[
FlightSegment(
departure_airport=[[Airport.JFK, 0]],
- arrival_airport=[[Airport.LHR, 0]],
+ arrival_airport=[[Airport.LAX, 0]],
travel_date=future_date.strftime("%Y-%m-%d"),
)
],
- stops=MaxStops.TWO_OR_FEWER_STOPS,
+ stops=MaxStops.ONE_STOP_OR_FEWER,
+ seat_type=SeatType.FIRST,
+ sort_by=SortBy.TOP_FLIGHTS,
+ from_date=(future_date - timedelta(days=30)).strftime("%Y-%m-%d"),
+ to_date=(future_date + timedelta(days=30)).strftime("%Y-%m-%d"),
+ )
+
+
+def round_trip_search_params():
+ """Create basic round trip search params for testing."""
+ today = datetime.now()
+ outbound_date = today + timedelta(days=30)
+ return_date = outbound_date + timedelta(days=7)
+
+ return DateSearchFilters(
+ passenger_info=PassengerInfo(
+ adults=1,
+ children=0,
+ infants_in_seat=0,
+ infants_on_lap=0,
+ ),
+ flight_segments=[
+ FlightSegment(
+ departure_airport=[[Airport.SFO, 0]],
+ arrival_airport=[[Airport.JFK, 0]],
+ travel_date=outbound_date.strftime("%Y-%m-%d"),
+ ),
+ FlightSegment(
+ departure_airport=[[Airport.JFK, 0]],
+ arrival_airport=[[Airport.SFO, 0]],
+ travel_date=return_date.strftime("%Y-%m-%d"),
+ ),
+ ],
+ stops=MaxStops.NON_STOP,
+ seat_type=SeatType.ECONOMY,
+ sort_by=SortBy.CHEAPEST,
+ trip_type=TripType.ROUND_TRIP,
+ from_date=(outbound_date - timedelta(days=30)).strftime("%Y-%m-%d"),
+ to_date=(outbound_date + timedelta(days=30)).strftime("%Y-%m-%d"),
+ )
+
+
+def complex_round_trip_params():
+ """Create more complex round trip search params for testing."""
+ today = datetime.now()
+ outbound_date = today + timedelta(days=60)
+ return_date = outbound_date + timedelta(days=14)
+
+ return DateSearchFilters(
+ passenger_info=PassengerInfo(
+ adults=2,
+ children=1,
+ infants_in_seat=0,
+ infants_on_lap=1,
+ ),
+ flight_segments=[
+ FlightSegment(
+ departure_airport=[[Airport.LAX, 0]],
+ arrival_airport=[[Airport.ORD, 0]],
+ travel_date=outbound_date.strftime("%Y-%m-%d"),
+ ),
+ FlightSegment(
+ departure_airport=[[Airport.ORD, 0]],
+ arrival_airport=[[Airport.LAX, 0]],
+ travel_date=return_date.strftime("%Y-%m-%d"),
+ ),
+ ],
+ stops=MaxStops.ONE_STOP_OR_FEWER,
seat_type=SeatType.BUSINESS,
- from_date=start_date.strftime("%Y-%m-%d"),
- to_date=end_date.strftime("%Y-%m-%d"),
+ sort_by=SortBy.TOP_FLIGHTS,
+ trip_type=TripType.ROUND_TRIP,
+ from_date=(outbound_date - timedelta(days=30)).strftime("%Y-%m-%d"),
+ to_date=(outbound_date + timedelta(days=30)).strftime("%Y-%m-%d"),
)
@@ -91,50 +158,98 @@ def test_search_functionality(search, search_params_fixture, request):
"""Test date search functionality with different data sets."""
search_params = request.getfixturevalue(search_params_fixture)
results = search.search(search_params)
-
- # Check if results are returned
- assert results is not None
assert isinstance(results, list)
- # Calculate expected number of days
- start_date = datetime.strptime(search_params.from_date, "%Y-%m-%d")
- end_date = datetime.strptime(search_params.to_date, "%Y-%m-%d")
- expected_days = (end_date - start_date).days + 1
-
- # Verify number of results matches the date range
- assert len(results) == expected_days
-
- # Check if results contain DatePrice objects
- for result in results:
- assert isinstance(result, DatePrice)
- assert isinstance(result.date, datetime)
- assert isinstance(result.price, float)
- assert result.price > 0
-
def test_multiple_searches(search, basic_search_params, complex_search_params):
"""Test performing multiple searches with the same SearchDates instance."""
# First search
results1 = search.search(basic_search_params)
assert isinstance(results1, list)
- assert all(isinstance(r, DatePrice) for r in results1)
# Second search with different data
results2 = search.search(complex_search_params)
assert isinstance(results2, list)
- assert all(isinstance(r, DatePrice) for r in results2)
# Third search reusing first search data
results3 = search.search(basic_search_params)
assert isinstance(results3, list)
- assert all(isinstance(r, DatePrice) for r in results3)
def test_date_price_sorting(search, basic_search_params):
- """Test that results are properly sorted by date."""
+ """Test that date prices are sorted chronologically."""
results = search.search(basic_search_params)
- assert results is not None
+ assert len(results) > 0
- # Verify results are sorted by date
- dates = [r.date for r in results]
+ # Verify dates are sorted
+ dates = [result.date[0] for result in results] # Get first date from tuple
assert dates == sorted(dates)
+
+
+def test_basic_round_trip_search(search, round_trip_search_params):
+ """Test basic round trip date search functionality."""
+ results = search.search(round_trip_search_params)
+ assert isinstance(results, list)
+ assert len(results) > 0
+
+ # Verify date range
+ from_date = datetime.strptime(round_trip_search_params.from_date, "%Y-%m-%d")
+ to_date = datetime.strptime(round_trip_search_params.to_date, "%Y-%m-%d")
+
+ for result in results:
+ # For round trips, date is a tuple of (outbound_date, return_date)
+ outbound_date, return_date = result.date
+ assert from_date.date() <= outbound_date.date() <= to_date.date()
+ assert outbound_date.date() <= return_date.date() # Return can be same day or later
+ assert hasattr(result, "price")
+ assert result.price > 0
+
+
+def test_complex_round_trip_search(search, complex_round_trip_params):
+ """Test complex round trip date search with multiple passengers and stops."""
+ results = search.search(complex_round_trip_params)
+ assert isinstance(results, list)
+ assert len(results) > 0
+
+ # Verify date range
+ from_date = datetime.strptime(complex_round_trip_params.from_date, "%Y-%m-%d")
+ to_date = datetime.strptime(complex_round_trip_params.to_date, "%Y-%m-%d")
+
+ for result in results:
+ # For round trips, date is a tuple of (outbound_date, return_date)
+ outbound_date, return_date = result.date
+ assert from_date.date() <= outbound_date.date() <= to_date.date()
+ assert outbound_date.date() <= return_date.date() # Return can be same day or later
+ assert hasattr(result, "price")
+ assert result.price > 0
+
+
+ "search_params_fixture",
+ [
+ "round_trip_search_params",
+ "complex_round_trip_params",
+ ],
+)
+def test_round_trip_result_structure(search, search_params_fixture, request):
+ """Test the structure of round trip date search results with different parameters."""
+ search_params = request.getfixturevalue(search_params_fixture)
+ results = search.search(search_params)
+
+ assert isinstance(results, list)
+ assert len(results) > 0
+
+ # Verify chronological order of outbound dates
+ outbound_dates = [result.date[0] for result in results]
+ assert outbound_dates == sorted(outbound_dates)
+
+ # Verify result structure
+ for result in results:
+ assert isinstance(result.date, tuple)
+ assert len(result.date) == 2 # Should have outbound and return dates
+ outbound_date, return_date = result.date
+ assert isinstance(outbound_date, datetime)
+ assert isinstance(return_date, datetime)
+ assert outbound_date <= return_date # Return can be same day or later
+ assert hasattr(result, "price")
+ assert result.price > 0
diff --git a/tests/search/test_search_flights.py b/tests/search/test_search_flights.py
index e94a446..ed59afd 100644
--- a/tests/search/test_search_flights.py
+++ b/tests/search/test_search_flights.py
@@ -13,6 +13,7 @@ from fli.models import (
SeatType,
SortBy,
)
+from fli.models.google_flights.base import TripType
from fli.search import SearchFlights
@@ -72,6 +73,72 @@ def complex_search_params():
)
+def round_trip_search_params():
+ """Create basic round trip search params for testing."""
+ today = datetime.now()
+ outbound_date = today + timedelta(days=30)
+ return_date = outbound_date + timedelta(days=7)
+
+ return FlightSearchFilters(
+ passenger_info=PassengerInfo(
+ adults=1,
+ children=0,
+ infants_in_seat=0,
+ infants_on_lap=0,
+ ),
+ flight_segments=[
+ FlightSegment(
+ departure_airport=[[Airport.SFO, 0]],
+ arrival_airport=[[Airport.JFK, 0]],
+ travel_date=outbound_date.strftime("%Y-%m-%d"),
+ ),
+ FlightSegment(
+ departure_airport=[[Airport.JFK, 0]],
+ arrival_airport=[[Airport.SFO, 0]],
+ travel_date=return_date.strftime("%Y-%m-%d"),
+ ),
+ ],
+ stops=MaxStops.NON_STOP,
+ seat_type=SeatType.ECONOMY,
+ sort_by=SortBy.CHEAPEST,
+ trip_type=TripType.ROUND_TRIP,
+ )
+
+
+def complex_round_trip_params():
+ """Create more complex round trip search params for testing."""
+ today = datetime.now()
+ outbound_date = today + timedelta(days=60)
+ return_date = outbound_date + timedelta(days=14)
+
+ return FlightSearchFilters(
+ passenger_info=PassengerInfo(
+ adults=2,
+ children=1,
+ infants_in_seat=0,
+ infants_on_lap=1,
+ ),
+ flight_segments=[
+ FlightSegment(
+ departure_airport=[[Airport.LAX, 0]],
+ arrival_airport=[[Airport.ORD, 0]],
+ travel_date=outbound_date.strftime("%Y-%m-%d"),
+ ),
+ FlightSegment(
+ departure_airport=[[Airport.ORD, 0]],
+ arrival_airport=[[Airport.LAX, 0]],
+ travel_date=return_date.strftime("%Y-%m-%d"),
+ ),
+ ],
+ stops=MaxStops.ONE_STOP_OR_FEWER,
+ seat_type=SeatType.BUSINESS,
+ sort_by=SortBy.TOP_FLIGHTS,
+ trip_type=TripType.ROUND_TRIP,
+ )
+
+
@pytest.mark.parametrize(
"search_params_fixture",
[
@@ -99,3 +166,88 @@ def test_multiple_searches(search, basic_search_params, complex_search_params):
# Third search reusing first search data
results3 = search.search(basic_search_params)
assert isinstance(results3, list)
+
+
+def test_basic_round_trip_search(search, round_trip_search_params):
+ """Test basic round trip flight search functionality."""
+ results = search.search(round_trip_search_params)
+ assert isinstance(results, list)
+ assert len(results) > 0
+
+ # Check that results contain tuples of outbound and return flights
+ for outbound, return_flight in results:
+ # Verify outbound flight
+ assert outbound.legs[0].departure_airport == Airport.SFO
+ assert outbound.legs[-1].arrival_airport == Airport.JFK
+
+ # Verify return flight
+ assert return_flight.legs[0].departure_airport == Airport.JFK
+ assert return_flight.legs[-1].arrival_airport == Airport.SFO
+
+
+def test_complex_round_trip_search(search, complex_round_trip_params):
+ """Test complex round trip flight search with multiple passengers and stops."""
+ results = search.search(complex_round_trip_params)
+ assert isinstance(results, list)
+ assert len(results) > 0
+
+ # Check that results contain tuples of outbound and return flights
+ for outbound, return_flight in results:
+ # Verify outbound flight
+ assert outbound.legs[0].departure_airport == Airport.LAX
+ assert outbound.legs[-1].arrival_airport == Airport.ORD
+ assert outbound.stops <= MaxStops.ONE_STOP_OR_FEWER.value
+
+ # Verify return flight
+ assert return_flight.legs[0].departure_airport == Airport.ORD
+ assert return_flight.legs[-1].arrival_airport == Airport.LAX
+ assert return_flight.stops <= MaxStops.ONE_STOP_OR_FEWER.value
+
+
+def test_round_trip_with_selected_outbound(search, round_trip_search_params):
+ """Test round trip search with a pre-selected outbound flight."""
+ # First get outbound flights
+ initial_results = search.search(round_trip_search_params)
+ assert len(initial_results) > 0
+
+ # Select first outbound flight and search for returns
+ selected_outbound = initial_results[0][0] # Get first outbound flight
+ round_trip_search_params.flight_segments[0].selected_flight = selected_outbound
+
+ return_results = search.search(round_trip_search_params)
+ assert isinstance(return_results, list)
+ assert len(return_results) > 0
+
+ # Verify all return flights match the selected outbound
+ for return_flight in return_results:
+ assert return_flight.legs[0].departure_airport == Airport.JFK
+ assert return_flight.legs[-1].arrival_airport == Airport.SFO
+
+
+ "search_params_fixture",
+ [
+ "round_trip_search_params",
+ "complex_round_trip_params",
+ ],
+)
+def test_round_trip_result_structure(search, search_params_fixture, request):
+ """Test the structure of round trip search results with different parameters."""
+ search_params = request.getfixturevalue(search_params_fixture)
+ results = search.search(search_params)
+
+ assert isinstance(results, list)
+ assert len(results) > 0
+
+ for result in results:
+ assert isinstance(result, tuple)
+ assert len(result) == 2
+ outbound, return_flight = result
+
+ # Verify both flights have the expected structure
+ for flight in (outbound, return_flight):
+ assert hasattr(flight, "price")
+ assert hasattr(flight, "duration")
+ assert hasattr(flight, "stops")
+ assert hasattr(flight, "legs")
+ assert len(flight.legs) > 0