Calling a JSON API using Python

The program will prompt for a location, contact a web service and retrieve JSON for the web service and parse that data, and retrieve the first place_id from the JSON. A place ID is a textual identifier that uniquely identifies a place as within Google Maps.

API End Points

To complete this assignment, you should use this API endpoint that has a static subset of the Google Data:

http://py4e-data.dr-chuck.net/json? This API uses the same parameter (address) as the Google API. This API also has no rate limit so you can test as often as you like. If you visit the URL with no parameters, you get "No address..." response.

I have worked on this assignment, but the codes are not running. I am JSONDecodeError whenever I run the program.

import urllib.request, urllib.parse, urllib.error
import json
adr= 'http://py4e-data.dr-chuck.net/json?'
while True:
    loca= input('Enter Location: ')
    if len(loca)<1:break

    url=adr + urllib.parse.urlencode({"address": loca})
    print('Retrieving', url)
    fha=urllib.request.urlopen(url)
    data=fha.read().decode()
    print('Retrieved', len(data))

    jsdata=json.loads(str(data))
    placeid= jsdata['results'][0]['place_id']
    print('The Place ID is: ', placeid)

Upvotes: 0

Views: 32779

Answers (7)

NotSam
NotSam

Reputation: 25

The reason you are unable to get the program to work is because you are missing the key and when you run your program they say its: Missing/incorrect key = parameter (it is an easy number to guess) ...

and i guess as a joke they made it 42 which in The Hitchhiker's Guide to the Galaxy is the meaning of life.

Upvotes: 0

Ankit Bamanpalli
Ankit Bamanpalli

Reputation: 34

Using urllib to open and collect data from URL. JSON to parse the data and load in JavaScript. We will get the result, i.e. place id using placeid = js['results'][0]['place_id'].

import urllib.request, urllib.parse, urllib.error
import json
import ssl

api_key = False
# If you have a Google Places API key, enter it here
# api_key = 'AIzaSy___IDByT70'
# https://developers.google.com/maps/documentation/geocoding/intro

if api_key is False:
    api_key = 42
    serviceurl = 'http://py4e-data.dr-chuck.net/json?'
else :
    serviceurl = 'https://maps.googleapis.com/maps/api/geocode/json?'

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

while True:
    address = input('Enter location: ')
    if len(address) < 1: break

    parms = dict()
    parms['address'] = address
    if api_key is not False: parms['key'] = api_key
    url = serviceurl + urllib.parse.urlencode(parms)

    print('Retrieving', url)
    uh = urllib.request.urlopen(url, context=ctx)
    data = uh.read().decode()
    print('Retrieved', len(data), 'characters')

    try:
        js = json.loads(data)
    except:
        js = None

    if not js or 'status' not in js or js['status'] != 'OK':
        print('==== Failure To Retrieve ====')
        print(data)
        continue


    placeid = js['results'][0]['place_id']

    print('Place id', placeid)

Upvotes: 0

Rushikesh Patil
Rushikesh Patil

Reputation: 1

# In this program you will use a GeoLocation lookup API modelled after the
# Google API to look up some universities and parse the returned data.
import ssl
import urllib.request, urllib.parse, urllib.error
import json

api_key= False
# api_key='....'
if api_key is False:
    api_key=42
    serviceurl= 'http://py4e-data.dr-chuck.net/json?'

else:
    serviceurl='https://maps.googleapis.com/maps/api/geocode/json?'

## Ignore SSL certification
ctx=ssl.create_default_context()
ctx.check_hostname=False
ctx.verify_mode=ssl.CERT_NONE

while True:
    address= input('Enter Adderss: ')
    if len(address)< 1: break

    contents= dict()
    contents['address']=address
    if api_key is not False: contents['key']=api_key
    url= serviceurl+ urllib.parse.urlencode(contents)

    print('Retrieving:', url)
    access= urllib.request.urlopen(url, context=ctx)
    data= access.read().decode()
    print('Retrieved', len(data), 'characters')

    ## check--- working or not
    try:
        js= json.loads(data)
    except:
        None

    # check if status is OK
    if not js or 'status' not in js or js['status'] != 'OK':
        print('========Failure To Retrieve=========')
        print(data)
        continue

    ## For proper representation
    print(json.dumps(js, indent=4))
    ## Print various values
    loc= js['results'][0]['place_id']
    print('Loc', loc)
    addr= js['results'][0]['formatted_address']
    print('Address of', address,'is:',addr)
    lati= js['results'][0]['geometry']['location']['lat']
    long= js['results'][0]['geometry']['location']['lng']
    print('Latitude:',lati,'\nLongitude:',long)

Upvotes: 0

Subhradip Debnath
Subhradip Debnath

Reputation: 21

This is the most updated code for the query

import json,ssl
import urllib.request,urllib.parse, urllib.error



# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE



#Stroring the given parameters
api_key = 42
serviceurl = "http://py4e-data.dr-chuck.net/json?"
# sample_address = "South Federal University"
data_address = "South Federal University"
address_wanted = data_address

#Setting the GET parameters on the URL
parameters = {"address": address_wanted, "key":api_key}
paramsurl = urllib.parse.urlencode(parameters)

#Generating the complete URL. Printing it in order to check if it's correct.
queryurl = serviceurl.strip() + paramsurl.strip()
print("DATA URL: ", queryurl)

#Obtaining and reading the data
try :
    data_read = urllib.request.urlopen(queryurl , context=ctx).read()
    data = data_read.decode()
    # Parsing the data and looking for the field we want.
    jsondata = json.loads(data)
    print(jsondata)
    place_id = jsondata["results"][0]["place_id"]
    print("PLACE ID: ", place_id)
except:
    print("Error.....")
    print("-"*50)
    print(data)

Upvotes: 2

Sravya
Sravya

Reputation: 141

import json,ssl
import urllib.request,urllib.parse, urllib.error



# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE



#Stroring the given parameters
api_key = 42
serviceurl = "http://py4e-data.dr-chuck.net/json?"
# sample_address = "South Federal University"
data_address = "IIT KANPUR"
address_wanted = data_address

#Setting the GET parameters on the URL
parameters = {"address": address_wanted, "key":api_key}
paramsurl = urllib.parse.urlencode(parameters)

#Generating the complete URL. Printing it in order to check if it's correct.
queryurl = serviceurl.strip() + paramsurl.strip()
print("DATA URL: ", queryurl)

#Obtaining and reading the data
try :
    data_read = urllib.request.urlopen(queryurl , context=ctx).read()
    data = data_read.decode()
    # Parsing the data and looking for the field we want.
    jsondata = json.loads(data)
    print(jsondata)
    place_id = jsondata["results"][0]["place_id"]
    print("PLACE ID: ", place_id)
except:
    print("Error.....")
    print("-"*50)
    print(data)
DATA URL:  http://py4e-data.dr-chuck.net/json?address=IIT+KANPUR&key=42
{'results': [{'access_points': [], 'address_components': [{'long_name': 'Kalyanpur', 'short_name': 'Kalyanpur', 'types': ['political', 'sublocality', 'sublocality_level_1']}, {'long_name': 'Kanpur', 'short_name': 'Kanpur', 'types': ['locality', 'political']}, {'long_name': 'Kanpur Nagar', 'short_name': 'Kanpur Nagar', 'types': ['administrative_area_level_2', 'political']}, {'long_name': 'Uttar Pradesh', 'short_name': 'UP', 'types': ['administrative_area_level_1', 'political']}, {'long_name': 'India', 'short_name': 'IN', 'types': ['country', 'political']}, {'long_name': '208016', 'short_name': '208016', 'types': ['postal_code']}], 'formatted_address': 'Kalyanpur, Kanpur, Uttar Pradesh 208016, India', 'geometry': {'location': {'lat': 26.5123388, 'lng': 80.2329}, 'location_type': 'GEOMETRIC_CENTER', 'viewport': {'northeast': {'lat': 26.5136877802915, 'lng': 80.23424898029151}, 'southwest': {'lat': 26.5109898197085, 'lng': 80.23155101970849}}}, 'place_id': 'ChIJcb6oxAE3nDkRNoTDq4Do-zo', 'plus_code': {'compound_code': 'G66M+W5 Kalyanpur, jvs tower, Kanpur, Uttar Pradesh, India', 'global_code': '7MR2G66M+W5'}, 'types': ['establishment', 'point_of_interest', 'university']}], 'status': 'OK'}
PLACE ID:  ChIJcb6oxAE3nDkRNoTDq4Do-zo

Upvotes: 0

Saniya Shanshar
Saniya Shanshar

Reputation: 41

import urllib.error, urllib.request, urllib.parse
import json

target = 'http://py4e-data.dr-chuck.net/json?' 
local = input('Enter location: ')
url = target + urllib.parse.urlencode({'address': local, 'key' : 42})

print('Retriving', url)
data = urllib.request.urlopen(url).read()
print('Retrived', len(data), 'characters')
js = json.loads(data)
print(json.dumps(js, indent = 4)) 
print('Place id', js['results'][0]['place_id'])

Upvotes: 4

Alejandro E. Rendon
Alejandro E. Rendon

Reputation: 309

It seems that the error is that this expects an extra parameter (Key)

Missing/incorrect key = parameter (it is an easy number to guess) ...

Edit: Check the documentation https://www.py4e.com/code3/geodata/README.txt

Example 1: http://py4e-data.dr-chuck.net/json?key=42&address=Monash+University

Example 2: http://py4e-data.dr-chuck.net/json?key=42&address=Kokshetau+Institute+of+Economics+and+Management

Upvotes: 2

Related Questions