Google Directions API, Part 2

Contents

Indices and tables

Exercise

For this week, the goal is to implement a function that does the following:

  • The function should accept 3 parameters, which you parsed with the argument parsing function last week:

    • Starting location
    • Destination location
    • Trip waypoints: None or List
  • Sends an http request to the Google Directions API

    • Full information on how to construct a link can be found at the API site (note: an API key is not actually required), but here are some guidelines:

      • Use http://maps.googleapis.com/maps/api/directions/json? as the base of the query. Http works best for python and we want json output.
      • Options are added as name=value, with & joining multiple options together. Start = “origin”, End = “destination”, Waypoints = “waypoints”
      • Here is a sample query to illistrate
  • Return the json result.

This excercise will require use of the requests package, specifically requests.get

For exceptions look at requests.ConnectionError and requests.Timeout

Requests should be installed now, if not try

$ sudo -H pip3 install -U requests

On completion of this exercies, you should be able to run your stub program and have it do the following:

  • Parse the arguments as outlined last week
  • Print the query result with just a start and end point passed.
  • Print the query result with start, end, and one or more waypoints passed.

Note: you might receive a response from the API about being over your allotted number of requests. If this happens, just try again.

Hints

To help you get started, here is one possible signature for the request function:

def http_request(start, end, waypoints):
    """
    Demonstration of using the built in urllib to querying an api.
    :param start: The starting location for the request.
    :param end: The destination for the request.
    :param waypoints: List of waypoints, or None.
    :return: The JSON data received from the api, as bytes.
    """
  • Use exception handling as appropriate.

Solution

When you are ready to see one possible solution, try this file