Project, Python

How to Make a Google Maps API Call

In this blog, I’m going to rehash how I made a Google API call using Postman and Pycharm. Enjoy!

Retrieving Data Using Postman and PyCharm

  • Install PyCharm and make a new project
  • Google “Google Maps API” and go to desired API section (in this example we are using Directions)
  • Review Introduction for key information:
    • Needs to use HTTP (meaning it must be done over the internet)
    • All communication uses POST command (no GET/PUT/etc)
    • Request/response is in JSON (we will need to use the header “application/json”
  • Get Google API key
    • Make a new project (or open existing)
    • Click menu and go to APIs & Services -> Credentials
    • Click Create Credentials -> API key
    • Copy and paste into file of choice to save key
    • To make a request, this is where the API key goes (example below shows directions from Disneyland to Universal Studios Hollywood)
https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood&key=YOUR_API_KEY
  • To restrict key to only certain services, navigate back to API & Services -> Credentials and edit newly created key, scroll to bottom and click “Restrict key”
  • In PyCharm, go to File->Settings->Project->Project Interpreter and install Requests package
  • Go to Postman to test out the API call, switch to POST and type in URL format from the documentation for the request:
http://maps.googleapis.com/maps/api/directions/outputFormat?parameters
  • In Postman fill out the request parameters per documentation
    • origin: Address or coordinates of starting location
    • destination: Address or coordinates of ending location
    • key: the API key generated above
    • mode (optional): mode of transportation
  • Click Send to check if successful
    • The first error said that requests must be in “https”, so I changed to that and resent
    • Then I got the following error
  • Went back to Documentation and followed the Get Started section and added a billing account for my project and followed prompts to enable the API key
  • After that the Postman call succeeded!
  • Now that the API call works, return to PyCharm to implement it by setting variables and creating a URL with the variables in them:
import requests

#variables
key = "API_KEY_HERE"
origin = "Kalamazoo,+MI"
destination = "Grand+Rapids,+MI"
mode = "bicycle"
url = "https://maps.googleapis.com/maps/api/directions/json?origin={}&destination={}&key={}&mode={}" .format(origin,destination,key,mode)

#Call API
response = requests.post(url)
print(response)
  • Run the code (in PyCharm it is Ctrl+Shift+F10), if the response returns as <Response [200]> it means the call succeeded with no errors
  • To return the actual text of the response, change the print statement to:
print(response.text)

Working with JSON

  • JSON stands for JavaScript Object Notation and is the de facto standard for information exchange
  • For example, the Google Driving API returns a JSON file
  • To better understand JSON in Python, my friend gave me a quick tutorial referencing this link https://realpython.com/python-json/
  • The structure of the JSON is as follows
    • The words in “” on the left side of the : are the keys
    • The values for the keys are on the right side after the :
    • The [] are for multiple values in a key
    • The {} are for nested JSON objects (these objects can again nest more JSON objects)
  • It is really the same structure as a Python dictionary, to use in Python simply import the json library
import json
  • Deserialization: our code needs to parse the response to be a usable object in python, to do so we use the function from the json library to turn it into a python json object
  • The load method will take JSON and load it into the code:
data = json.loads(response.text)

To write a JSON object to a file for example, use the dump method

with open("data_file.json", "w") as write_file: json.dump(data, write_file)

In order to “traverse” through the object and get elements, I wrote the following code (the print statements are there to show the object, the object type, and the specific value I wanted to return in the object)

#Call API
response = requests.post(url)

#Deserialize request
data = json.loads(response.text)
print(data)
print(type(data))
print(data["geocoded_waypoints"][0]["geocoder_status"])

To write the value to a file and print it out for confirmation, I wrote this code:

#write value to file
geocoder_status_value = data["geocoded_waypoints"][0]["geocoder_status"]
f = open("valuefile.txt", "a")
f.write(geocoder_status_value)
f.close()

#open and read the file
f = open("valuefile.txt", "r")
print(f.read())

And that is my first Google API call! πŸ™‚ Full code below to replicate the entire process of calling the API, parsing the response, and saving it to a file.

import requests
import json

#variables
key = "YOUR-API-KEY-HERE"
origin = "Kalamazoo,+MI"
destination = "Grand+Rapids,+MI"
mode = "bicycle"
url = "https://maps.googleapis.com/maps/api/directions/json?origin={}&destination={}&key={}&mode={}" .format(origin,destination,key,mode)

#Call API
response = requests.post(url)

#Deserialize request
data = json.loads(response.text)
print(data)
print(type(data))

#write value to file
geocoder_status_value = data["geocoded_waypoints"][0]["geocoder_status"]
f = open("valuefile.txt", "a")
f.write(geocoder_status_value)
f.close()

#open and read the file
f = open("valuefile.txt", "r")
print(f.read())

Leave a Reply