Skip to content

Instantly share code, notes, and snippets.

@angelabauer
Created October 21, 2020 10:29
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 23 You must be signed in to fork a gist
  • Save angelabauer/99301f807578ad8b6f54e8fb8ec7162b to your computer and use it in GitHub Desktop.
Save angelabauer/99301f807578ad8b6f54e8fb8ec7162b to your computer and use it in GitHub Desktop.
from pprint import pprint
import requests
SHEETY_PRICES_ENDPOINT = YOUR SHEETY PRICES ENDPOINT URL
class DataManager:
def __init__(self):
self.destination_data = {}
def get_destination_data(self):
# 2. Use the Sheety API to GET all the data in that sheet and print it out.
response = requests.get(url=SHEETY_PRICES_ENDPOINT)
data = response.json()
self.destination_data = data["prices"]
# 3. Try importing pretty print and printing the data out again using pprint().
# pprint(data)
return self.destination_data
# 6. In the DataManager Class make a PUT request and use the row id  from sheet_data
# to update the Google Sheet with the IATA codes. (Do this using code).
def update_destination_codes(self):
for city in self.destination_data:
new_data = {
"price": {
"iataCode": city["iataCode"]
}
}
response = requests.put(
url=f"{SHEETY_PRICES_ENDPOINT}/{city['id']}",
json=new_data
)
print(response.text)
import requests
TEQUILA_ENDPOINT = "https://tequila-api.kiwi.com"
TEQUILA_API_KEY = YOUR FLIGHT SEARCH API KEY
class FlightSearch:
def get_destination_code(self, city_name):
location_endpoint = f"{TEQUILA_ENDPOINT}/locations/query"
headers = {"apikey": TEQUILA_API_KEY}
query = {"term": city_name, "location_types": "city"}
response = requests.get(url=location_endpoint, headers=headers, params=query)
results = response.json()["locations"]
code = results[0]["code"]
return code
# 4. Pass the data back to the main.py file, so that you can print the data from main.py
from data_manager import DataManager
data_manager = DataManager()
sheet_data = data_manager.get_destination_data()
# print(sheet_data)
# 5. In main.py check if sheet_data contains any values for the "iataCode" key.
# If not, then the IATA Codes column is empty in the Google Sheet.
# In this case, pass each city name in sheet_data one-by-one
# to the FlightSearch class to get the corresponding IATA code
# for that city using the Flight Search API.
# You should use the code you get back to update the sheet_data dictionary.
if sheet_data[0]["iataCode"] == "":
from flight_search import FlightSearch
flight_search = FlightSearch()
for row in sheet_data:
row["iataCode"] = flight_search.get_destination_code(row["city"])
print(sheet_data)
data_manager.destination_data = sheet_data
data_manager.update_destination_codes()
@kucung06
Copy link

I have a question, what is row id?

@SadSack963
Copy link

I have a question, what is row id?

It's just the row number in your spreadsheet.

@kucung06
Copy link

kucung06 commented Apr 3, 2023

someone please explain what happened.?
did i missing somting?

for row in sheet_data:
if row["iataCode"] == "":
from flight_search import FlightSearch
fc= FlightSearch()
row["iataCode"] = fc.get_distination_name(row["city"])
data_manager.destination_code(row)
print(sheet_data)

i get this:
TypeError: string indices must be integers, not 'str'

@ben-ben-bigelow
Copy link

Hi, I copied the entire solution, generated my TEQUILA_API_KEY, and got "KeyError: 'locations', any idea what is wrong?

@chaturvedis90
Copy link

someone please explain what happened.? did i missing somting?

for row in sheet_data: if row["iataCode"] == "": from flight_search import FlightSearch fc= FlightSearch() row["iataCode"] = fc.get_distination_name(row["city"]) data_manager.destination_code(row) print(sheet_data)

i get this: TypeError: string indices must be integers, not 'str'

Somewhere in your code it requires an integer and you have given a string. Example:

classroom = [{
    'student_name': 'a',
    'student_subject': 'Maths'
},
{
    'student_name': 'z',
    'student_subject': 'Biology'
}]

The API response you are getting it's JSON looks somewhat like above classroom example. So if I print,

print(classroom["student_name"])

It gives me error - TypeError: list indices must be integers or slices, not str

But if I print,

print(classroom[0]["student_name"])

it gives me correct result - a

Because, if you look at classroom the dictionaries are inside a list, so in order to get inside a dictionary first I have to mention into which index of the list I want to access a dictionary. Classroom has two indexes 0 & 1, both have two dictionaries. So in order to get to the first dictionary in the list, I first put index number [0] and then I put the attribute I want to access in that dictionary i.e. [student_name]. If I have to access second dictionary in the classroom list I will print:

print(classroom[1]["student_name"])

result - z

@AleemRahil
Copy link

AleemRahil commented May 7, 2023

{
"errors": [
{
"detail": "Bad Request. The JSON payload should be inside a root property called 'price'. Check https://sheety.co/docs for more details."
}
]
}

@angelabauer Why am I getting this error if my sheetname is 'prices'

image

@SadSack963
Copy link

Because you are setting one price at a time.

Add_Row

@AleemRahil
Copy link

Because you are setting one price at a time.

Add_Row

what if the sheetname was sheet1? what about then?

@SadSack963
Copy link

As I understand it, you would not alter that. Just use it as is for your root property.

@AleemRahil
Copy link

As I understand it, you would not alter that. Just use it as is for your root property.

but why is that so?

@SadSack963
Copy link

What is the singular version of "sheet1"? It's meaningless.

@AleemRahil
Copy link

What is the singular version of "sheet1"? It's meaningless.

but why does it need a singular version?

@SadSack963
Copy link

Because that's the rule that Sheety have defined. It's their application, their rules!

@AleemRahil
Copy link

Because that's the rule that Sheety have defined. It's their application, their rules!

ah kk lol
ty for clarifying this for me!!

@NavinduH
Copy link

This isn't the place where I should be posting this but I couldn't find anywhere else, but the Kiwi site has been updated and the applications in My Company cannot be found. Can someone please help?

@SadSack963
Copy link

@BacemDallel
Copy link

@peterschwps I added that correctly and re-checked, no issues in that. But still getting this "unauthorized" error. Is there anything else which can cause this issue??

If you have any authentication try to remove it and retry for now, it must work, happened to me and worked later this way.

@vasudev17
Copy link

I tried the code that Angela wrote and I'm getting the error
Traceback (most recent call last): File "/Users/vasu/Dev/Python/Day39-FlightTracker/main.py", line 11, in <module> row["iataCode"] = flight_search.get_destination_code(row["city"]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/vasu/Dev/Python/Day39-FlightTracker/flight_search.py", line 15, in get_destination_code code = results[0]["code"] ~~~~~~~^^^ IndexError: list index out of range

Please help.

@xcoder94
Copy link

Im getting “keyError” locations. Please help

Hi, I copied the entire solution, generated my TEQUILA_API_KEY, and got "KeyError: 'locations', any idea what is wrong?
Me too
Any one found the solution

@MissNkini
Copy link

MissNkini commented Dec 19, 2023

hi,
I would love some help here, i have updated the code from the function
def get_destination_code(self, city_name):
location_endpoint = f"{TEQUILA_ENDPOINT}/locations/query"
headers = {"apikey": TEQUILA_API_KEY}
query = {"term": city_name, "location_types": "city"}
response = requests.get(url=location_endpoint, headers=headers, params=query)
response.raise_for_status()
print(response.status_code)
results = response.json()["locations"]
code = results[0]["code"]
return code
But my main.py still show me the "TESTING" as a response in "iataCode" and i have rechecked and refreshed my sheety protect template, still its written "TESTING"

Can someone please help me what would be the problem. * The code is well indented in my file.

@Skydplay95
Copy link

hi, I would love some help here, i have updated the code from the function def get_destination_code(self, city_name): location_endpoint = f"{TEQUILA_ENDPOINT}/locations/query" headers = {"apikey": TEQUILA_API_KEY} query = {"term": city_name, "location_types": "city"} response = requests.get(url=location_endpoint, headers=headers, params=query) response.raise_for_status() print(response.status_code) results = response.json()["locations"] code = results[0]["code"] return code But my main.py still show me the "TESTING" as a response in "iataCode" and i have rechecked and refreshed my sheety protect template, still its written "TESTING"

Can someone please help me what would be the problem. * The code is well indented in my file.

when you print before code before return it, what have you on the console ?

@ribak12
Copy link

ribak12 commented Jan 3, 2024

import requests
TEQUILLA_ENDPOINT = "https://api.tequila.kiwi.com/"
location_endpoint = f"{TEQUILLA_ENDPOINT}/locations/query"
header = {"apikey": "qSNCluvMp5nmtTJZOs29s2nQE-M2yBb"}
query = {"term": "Paris", "location_types": "city"}
response = requests.get(url=location_endpoint, json=query, headers=header)
data = response.text
print(data)

i am getting this error when i formated in the text form

<title>400 Bad Request</title>

Error: Bad Request

Your client has issued a malformed or illegal request.

also when i try to get the data in json it is giving me an exception and i am not able to get the result can someone please help

@BacemDallel
Copy link

import requests TEQUILLA_ENDPOINT = "https://api.tequila.kiwi.com/" location_endpoint = f"{TEQUILLA_ENDPOINT}/locations/query" header = {"apikey": "qSNCluvMp5nmtTJZOs29s2nQE-M2yBb"} query = {"term": "Paris", "location_types": "city"} response = requests.get(url=location_endpoint, json=query, headers=header) data = response.text print(data)

i am getting this error when i formated in the text form

<title>400 Bad Request</title> # Error: Bad Request ## Your client has issued a malformed or illegal request. also when i try to get the data in json it is giving me an exception and i am not able to get the result can someone please help

Try it this way of passing the querry parameter as a part of the url

import requests

TEQUILLA_ENDPOINT = "https://api.tequila.kiwi.com/"
location_endpoint = f"{TEQUILLA_ENDPOINT}/locations/query"
header = {"apikey": "qSNCluvMp5nmtTJZOs29s2nQE-M2yBb"}
params = {"term": "Paris", "location_types": "city"}
response = requests.get(url=location_endpoint, params=params, headers=header)
data = response.text
print(data)

@ribak12
Copy link

ribak12 commented Jan 4, 2024

import requests TEQUILLA_ENDPOINT = "https://api.tequila.kiwi.com/" location_endpoint = f"{TEQUILLA_ENDPOINT}/locations/query" header = {"apikey": "qSNCluvMp5nmtTJZOs29s2nQE-M2yBb"} query = {"term": "Paris", "location_types": "city"} response = requests.get(url=location_endpoint, json=query, headers=header) data = response.text print(data)
i am getting this error when i formated in the text form

<title>400 Bad Request</title> # Error: Bad Request ## Your client has issued a malformed or illegal request. also when i try to get the data in json it is giving me an exception and i am not able to get the result can someone please help

Try it this way of passing the querry parameter as a part of the url

import requests

TEQUILLA_ENDPOINT = "https://api.tequila.kiwi.com/" location_endpoint = f"{TEQUILLA_ENDPOINT}/locations/query" header = {"apikey": "qSNCluvMp5nmtTJZOs29s2nQE-M2yBb"} params = {"term": "Paris", "location_types": "city"} response = requests.get(url=location_endpoint, params=params, headers=header) data = response.text print(data)

thank you for the help

@Cruel-Croissant
Copy link

import requests TEQUILLA_ENDPOINT = "https://api.tequila.kiwi.com/" location_endpoint = f"{TEQUILLA_ENDPOINT}/locations/query" header = {"apikey": "qSNCluvMp5nmtTJZOs29s2nQE-M2yBb"} query = {"term": "Paris", "location_types": "city"} response = requests.get(url=location_endpoint, json=query, headers=header) data = response.text print(data)

i am getting this error when i formated in the text form

<title>400 Bad Request</title> # Error: Bad Request ## Your client has issued a malformed or illegal request.

also when i try to get the data in json it is giving me an exception and i am not able to get the result can someone please help

Try removing forward slash from url endpoint after "com"

@yutinghi
Copy link

the key is ["locations"] not location

@1z1da
Copy link

1z1da commented Feb 21, 2024

the key is ["locations"] not location

Negative.
The issue was that the user has put the (json=) parameter to a "GET" function, instead of (params=) as it should be.

(json=) is taking place in the "POST" and "PUT" behvaior.

@YaldaKarimii
Copy link

It's very hard to find support here, youtube's comment section always has all the answers sadly here it's no helping at all. the code is not working for updating the sheety page(iata codes). i used the same code of Angela.

yes i also have the same issue

It's very hard to find support here, youtube's comment section always has all the answers sadly here it's no helping at all. the code is not working for updating the sheety page(iata codes). i used the same code of Angela.

i find the solution delete all value in (iata code) then run your code it will work

@kriswen
Copy link

kriswen commented Apr 6, 2024

it's because in angela's code main.py line 13, it's only checking if the first row of iata is empty, then it will run through the sheet_data, like this if sheet_data[0]["iataCode"] == "":

below is how i did it in main.py instead, it'll loop through every row of iata in sheet_data, and update if it's empty:

for row in sheet_data:
    if row["iataCode"] == "":
        row["iataCode"] = fs.get_dest_code(row["city"])
        dm.update_row_data(row["id"])

@chiragkaushikofficial
Copy link

It's very hard to find support here, youtube's comment section always has all the answers sadly here it's no helping at all. the code is not working for updating the sheety page(iata codes). i used the same code of Angela.

"Share your github repo or ss here"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment