Calling a JSON API Using Python (Retrieve Google Place ID)

In this assignment, we will create a Python program that communicates with a web service, retrieves JSON data, and extracts information from it.

The program works similarly to the example provided at:

👉 http://www.py4e.com/code3/geojson.py

The application will:

✅ Prompt the user for a location
✅ Call a web API using that location
✅ Retrieve JSON data from the service
✅ Parse the JSON response
✅ Extract location details such as latitude, longitude, and formatted address

A Place ID is a unique textual identifier used by Google Maps to identify a specific location.


🌐 API Endpoint

For this assignment, use the following testing API (a static subset of Google data):

http://py4e-data.dr-chuck.net/json?

Important Notes

  • Uses the same address parameter as the Google API
  • No rate limit (safe for testing)
  • Requires a key parameter
  • Address must be URL encoded using urllib.parse.urlencode()

If you open the URL without parameters, you will see:

No address...

🧠 Program Workflow

  1. Ask user to enter a location
  2. Build API request URL
  3. Send request to web service
  4. Receive JSON response
  5. Convert JSON text into Python dictionary
  6. Extract required data
Infographic explaining how to call a JSON API using Python, including API endpoint, workflow steps, JSON parsing, and sample output example.
Step-by-step infographic showing how Python retrieves and parses JSON data from a web API



🐍 Python Solution

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

# API Key setup
api_key = False

# If you have a real Google API key, place it here
# api_key = 'AIzaSyXXXX'

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

# Create parameters dictionary
parms = dict()
parms['address'] = address
if api_key is not False:
parms['key'] = api_key

# Encode parameters into URL
url = serviceurl + urllib.parse.urlencode(parms)

print('Retrieving:', url)

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

# Convert JSON text to dictionary
try:
js = json.loads(data)
except:
js = None

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

# Pretty print JSON
print(json.dumps(js, indent=4))

# Extract required data
lat = js['results'][0]['geometry']['location']['lat']
lng = js['results'][0]['geometry']['location']['lng']
location = js['results'][0]['formatted_address']

print('Latitude:', lat)
print('Longitude:', lng)
print('Location:', location)

📊 Sample Output

Enter location: Ahmedabad
Retrieving: http://py4e-data.dr-chuck.net/json?address=Ahmedabad&key=42
Retrieved 1234 characters

Latitude: 23.0225
Longitude: 72.5714
Location: Ahmedabad, Gujarat, India

🔑 Key Concepts Used

  • urllib.request → Access web URLs
  • urllib.parse.urlencode() → Encode parameters safely
  • json.loads() → Convert JSON to Python dictionary
  • SSL context → Ignore certificate errors during testing
  • API communication using HTTP requests

✅ Learning Outcome

After completing this program, you will understand:

  • How APIs work
  • How to fetch data from web services
  • JSON parsing in Python
  • Extracting nested data structures