Question: I am having trouble with an api call in python. When I set r to a fixed address the program returns the correct json call

I am having trouble with an api call in python. When I set r to a fixed address the program returns the correct json call but when I create variables for mode, orgin and destination I get an invalid requet. I am not sure why it does not work.

code works with set api call:

___________________________________________________________________________________

import json import requests

class Tour: def __init__(self, master): self.master = master master.title("Tour") Label(master, text="Orgin").grid(row=0) Label(master, text="Destination").grid(row=1) Label(master, text="Mode").grid(row=2) e1 = Entry(master) e2 = Entry(master) e3 = Entry(master) e1.grid(row=0, column=1) e2.grid(row=1, column=1) e3.grid(row=2, column=1) Button(master, text='GetDistance', command= self.onClick()).grid(row=3, column=0, sticky=W, pady=4) def onClick(self): api_key = 'AIzaSyCTzy54Y4XxqFuxNPKVxvpnJO5iNpdofOI' source = 'Irvine CA' dest = 'Los Angeles CA' mode = 'driving' url ='https://maps.googleapis.com/maps/api/distancematrix/json?' r = requests.get('http://maps.googleapis.com/maps/api/distancematrix/json?origins=New+York+NY&destinations=Lansing+MI&mode=driving&sensor=false') x = r.json() print(x)

root = Tk()

my_gui = Tour(root)

root.mainloop()

__________________________________________________________________

Code with variables does not work:

____________________________________________________________

import json import requests

class Tour: def __init__(self, master): self.master = master master.title("Tour") Label(master, text="Orgin").grid(row=0) Label(master, text="Destination").grid(row=1) Label(master, text="Mode").grid(row=2) e1 = Entry(master) e2 = Entry(master) e3 = Entry(master) e1.grid(row=0, column=1) e2.grid(row=1, column=1) e3.grid(row=2, column=1) Button(master, text='GetDistance', command= self.onClick()).grid(row=3, column=0, sticky=W, pady=4) def onClick(self): api_key = 'AIzaSyCTzy54Y4XxqFuxNPKVxvpnJO5iNpdofOI' source = 'Irvine CA' dest = 'Los Angeles CA' mode = 'driving' url ='https://maps.googleapis.com/maps/api/distancematrix/json?' r = requests.get(url + 'origins =' + source + '&destinations= ' + dest + '&mode=' + mode + '&sensor=false') x = r.json() print(x)

root = Tk()

my_gui = Tour(root)

root.mainloop()

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!