Appery.io Server Code makes it simple to invoke any external REST API. In this blog post, I will show you how to invoke Lyft API. I will use the Ride Types API to show what types of cars are available based on a location – latitude and longitude. Lyft is a ride sharing company that’s disrupting car ownership and moving forward with self-driving cars initiative.
Let’s start with the tutorial.
The first step is to perform authentication to get an access token to invoke any Lyft API. As the Ride Types API doesn’t use any user data, you can use client credentials for authentication. The script to get an access token looks like this:
var url = "https://api.lyft.com/oauth/token"; var client_id = "<client_id>"; var client_secret = "<client_secret>"; var XHRResponse = XHR2.send("POST", url, { "body": { "grant_type": "client_credentials", "scope": "public" }, "headers": { "Content-Type": "application/json", "Authorization": "Basic "+encodeBase64(client_id+":"+client_secret) } }); Apperyio.response.success(XHRResponse.body, "application/json");
The response will look like this:
{ "expires_in": 86400, "token_type": "Bearer", "scope": "public", "access_token": "<access_token>" }
Once you have the access_token, it is as simple to invoke the Ride Types API:
var url = "https://api.lyft.com/v1/ridetypes"; // REST API URL var XHRResponse = XHR2.send("GET", url, { "parameters": { "lat": "37.7833", // San Francisco "lng": "-122.4167" }, "headers": { "Authorization": "Bearer " + <access_token> } }); Apperyio.response.success(XHRResponse.body, "application/json");
The response looks like this, it shows the type of rides available in San Francisco: Lyft, Lyft Line, and Lyft Plus.
{ "ride_types": [{ "ride_type": "lyft_line", "pricing_details": { "cost_per_minute": 23, "base_charge": 200, "currency": "USD", "trust_and_service": 175, "cost_per_mile": 115, "cancel_penalty_amount": 500, "cost_minimum": 475 }, "image_url": "https://s3.amazonaws.com/api.lyft.com/assets/car_standard.png", "seats": 2, "display_name": "Lyft Line" }, { "display_name": "Lyft", "image_url": "https://s3.amazonaws.com/api.lyft.com/assets/car_standard.png", "pricing_details": { "cost_minimum": 500, "cost_per_minute": 23, "base_charge": 200, "currency": "USD", "trust_and_service": 175, "cost_per_mile": 115, "cancel_penalty_amount": 500 }, "ride_type": "lyft", "seats": 4 }, { "display_name": "Lyft Plus", "ride_type": "lyft_plus", "image_url": "https://s3.amazonaws.com/api.lyft.com/assets/car_plus.png", "seats": 6, "pricing_details": { "currency": "USD", "cost_minimum": 700, "cost_per_mile": 200, "trust_and_service": 175, "cancel_penalty_amount": 500, "cost_per_minute": 30, "base_charge": 300 } }] }
Want to learn how to build mobile apps fast? Check out the Appery.io YouTube channel for videos.
Leave a Reply