File size: 3,187 Bytes
e2d8145
 
 
 
8152a3c
e2d8145
 
 
 
 
 
 
8152a3c
 
e2d8145
8152a3c
e2d8145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8152a3c
e2d8145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import http.client
import pandas as pd
import numpy as np
import json
import os



def get_flight(departureId, arrivalId, departureDate):

    conn = http.client.HTTPSConnection("booking-com15.p.rapidapi.com")

    rapid_key = os.getenv("RAPIDAPI_KEY")

    headers = {
        'x-rapidapi-key': rapid_key, #Replace with your own RapidAPI key
        'x-rapidapi-host': "booking-com15.p.rapidapi.com"
    }

    conn.request("GET", f"/api/v1/flights/searchFlights?fromId={departureId}.AIRPORT&toId={arrivalId}.AIRPORT&departDate={departureDate}&currency_code=BRL", headers=headers)

    res = conn.getresponse()
    data = res.read()
    json_data = json.loads(data.decode("utf-8"))

    try:
        # Get all flight offers with validation
        if not json_data or 'data' not in json_data or 'flightOffers' not in json_data['data']:
            return None
        
        flight_offers = json_data['data']['flightOffers']

        if not flight_offers:
            return None
        
        # Initialize variables to track cheapest flight
        cheapest_price = float('inf')
        cheapest_flight = None

        # Loop through each flight offer
        for offer in flight_offers:
            try:
                # Validate price breakdown structure
                if ('priceBreakdown' not in offer or 
                    'total' not in offer['priceBreakdown'] or 
                    'units' not in offer['priceBreakdown']['total']):
                    print('a estrutura está correta')
                    continue
                # Get total price in units
                price = float(offer['priceBreakdown']['total']['units'])
                # Add nanos (decimal part) if present
                if 'nanos' in offer['priceBreakdown']['total']:
                    price += float(offer['priceBreakdown']['total']['nanos']) / 1000000000
                # Update cheapest if current price is lower
                if price < cheapest_price:
                    cheapest_price = price
                    cheapest_flight = offer
            except (ValueError, TypeError):
                continue

        # Extract relevant info from cheapest flight
        if cheapest_flight:
            try:
                result = {
                    'price': f"{cheapest_flight['priceBreakdown']['total'].get('currencyCode', 'USD')} {cheapest_price:.2f}",
                    'departure': {
                        'from': cheapest_flight['segments'][0]['departureAirport'].get('cityName', 'Unknown'),
                        'time': cheapest_flight['segments'][0].get('departureTime', 'Unknown')
                    },
                    'arrival': {
                        'to': cheapest_flight['segments'][0]['arrivalAirport'].get('cityName', 'Unknown'),
                        'time': cheapest_flight['segments'][0].get('arrivalTime', 'Unknown')
                    },
                    'airline': cheapest_flight['segments'][0]['legs'][0]['carriersData'][0].get('name', 'Unknown')
                }
                return result
            except (KeyError, IndexError):
                return None
        return None
    except Exception:
        return None