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.exchange_code(code)[:access_token] redirect '/vehicle' 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 vehicles = Smartcar::Vehicle.get_vehicle(token: @@token) vehicle_ids = vehicles.vehicles # 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.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!