Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Understanding Key errors
#1
Sometimes when I run this code it throws a Key error for "data", other times (without changing anything) it retrieves the data.

from flight_search import FlightSearch

flight_search_One = FlightSearch()

JSON = flight_search_One.flight_JSON("PAR")

print(JSON["data"])
I'm running it on Pycharm. The flight_search_One.fligh_JSON function makes an API get request to amedeus and returns a JSON for flight offers.
Heres the code for the FlightSearch class, I removed my API Key and Secret
import requests
from datetime import datetime, timedelta

class FlightSearch:
    #This class is responsible for talking to the Flight Search API.\
    def __init__(self):
        self.API_Key = "NA"
        self.API_Secret = "NA"
        self.Auth_Data = data = {"grant_type": "client_credentials",
                "client_id" : self.API_Key,
                "client_secret" : self.API_Secret}
        self.Auth_Token_Endpoint = "https://test.api.amadeus.com/v1/security/oauth2/token"
        self.Auth_Token_Header = {"Content-Type": "application/x-www-form-urlencoded"}


    def get_token(self):
        response = requests.post(url=self.Auth_Token_Endpoint, headers=self.Auth_Token_Header, data= self.Auth_Data)
        access_token = response.json()['access_token']
        return access_token

    def flight_JSON(self, iata):
        dt = datetime.now()
        td = timedelta(days=100)
        future = dt + td
        departure_date = future.date()
        API_Endpoint = "https://test.api.amadeus.com/v2/shopping/flight-offers"
        params = {
            "originLocationCode": "YYZ",
            "destinationLocationCode": iata,
            "departureDate": departure_date,
            "adults": 2,
            "maxPrice" : 1000,
            # "currencyCode" : "EUR"
            }
        headers = {
            "Authorization": f"Bearer {self.get_token()}"
            }
        response = requests.get(url=API_Endpoint, headers=headers, params=params)
        JSON = response.json()
        return JSON
buran write Nov-03-2024, 03:33 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
Add error handling when data key is missing,it's normal that and API sometime give errror back.
When an error occurs the JSON response will contain an errors key(no data key) with details about what went wrong.
def flight_JSON(self, iata):
    dt = datetime.now()
    td = timedelta(days=100)
    future = dt + td
    departure_date = future.date()
    API_Endpoint = "https://test.api.amadeus.com/v2/shopping/flight-offers"
    params = {
        "originLocationCode": "YYZ",
        "destinationLocationCode": iata,
        "departureDate": departure_date,
        "adults": 2,
        "maxPrice": 1000,
        # "currencyCode" : "EUR"
    }
    headers = {
        "Authorization": f"Bearer {self.get_token()}"
    }
    response = requests.get(url=API_Endpoint, headers=headers, params=params)

    # Check if the request was successful and data is in response
    if response.status_code == 200:
        JSON = response.json()
        if "data" in JSON:
            return JSON["data"]
        else:
            print("No 'data' key in the response JSON.")
            print(f"Response JSON: {JSON}")
            return None
    else:
        print(f"Error: Received status code {response.status_code}")
        print(f"Response JSON: {response.json()}")
        return None
Usage:
from flight_search import FlightSearch

flight_search_One = FlightSearch()
data = flight_search_One.flight_JSON("PAR")
if data:
    print(data)
else:
    print("Failed to retrieve flight data.")
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020