Now that the Python application has an authorization code, it can exchange it for an access_token required to make a request to a vehicle.


1. Obtain an access token

In the previous section, we retrieved an authorization code. The Python application must exchange the code for an access_token to make a request.

The access_token represents your application’s access to a vehicle on behalf of the vehicle owner.

After receiving the access_token, the user can be redirected to the /vehicle route which we will implement in the next step.

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
# ./main.py

# global variable to save our access_token
access = None

@app.route('/exchange', methods=['GET'])
def exchange():
    code = request.args.get('code')

    # TODO: Request Step 1: Obtain an access token
    # access our global variable and store our access tokens
    global access
    # in a production app you'll want to store this in some kind of
    # persistent storage
    access = client.exchange_code(code)
    return redirect('/vehicle')

2. Get vehicle attributes

Once the application has the access_token, it can send requests to a vehicle using Smartcar’s API.

Once we have the vehicle attributes, we'll serialize them as JSON to return to the client.

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
# ./main.py

@app.route('/vehicle', methods=['GET'])
# TODO: Request Step 2: Get vehicle information
def get_vehicle():
    # access our global variable to retrieve our access tokens
    global access
    # Send a request to get a list of vehicle ids
    vehicles = smartcar.get_vehicles(access.access_token)
    vehicle_ids = vehicles.vehicles
    # instantiate the first vehicle in the vehicle id list
    vehicle = smartcar.Vehicle(vehicle_ids[0], access.access_token)

    # Make a request to Smartcar API
    attributes = vehicle.attributes()
    return jsonify({
      "make": attributes.make,
      "model": attributes.model,
      "year": attributes.year    
    })
    '''
    {
        "make": "TESLA",
        "model": "Model S",
        "year": 2014
    }
    '''

Try it out

Make sure the server is running -

  • $
python main.py

Now you can go to localhost:8000/login to see your Python app running!


Next steps