Now that the Ruby application has an authorization
code, it can exchange it for an
access_token required to make a request to a vehicle.
In the previous section, we retrieved an authorization
code. The Ruby application must exchange the
code for an
access_token to make a request.
After receiving the
access_token, the user can be redirected to the
/vehicle route which we will implement in the next step.
# ./app.rb # global variable to store the token @@token = '' get "/exchange" do code = params[:code] # TODO: Request Step 1: Obtain an access token # In a production app you'll want to store this in some kind of persistent storage @@token = @@client.get_token(code)[:access_token] "OK" end
Once the application has the
access_token, it can send requests to a vehicle using Smartcar’s API.
Once we have the
vehicle_attributes object, we can build and return attributes hash which is displayed on the UI.
# ./app.rb get "/vehicle" do code = params[:code] # TODO: Request Step 2a: Get vehicle ids vehicle_ids = Smartcar::Vehicle.all_vehicle_ids(token: @@token) # TODO: Request Step 2b: Create a vehicle vehicle = Smartcar::Vehicle.new(token: @@token, id: vehicle_ids.first) # TODO: Request Step 2c: Make a request to Smartcar API for the vehicle # Get the vehicle_attributes object for vehicle vehicle_attributes = vehicle.vehicle_attributes # Build a hash of id, make, model and year and return as json vehicle_attributes.slice(*%I(id make model year).to_json end
Make sure the server is running -
bundle exec ruby app.rb
Now you can go to
localhost:8000/login to see your Sinatra app running!