Documentation ¶
Overview ¶
This package provides an API client for the Uber API. It exposes methods to get information about Uber products, estimates, times, and users as well as actually requesting an Uber.
A lot of documentation will be pulled directly from https://developer.uber.com/v1/endpoints.
Organization ¶
This package is organized into a few files.
1. `uber.go` contains all the exported types (that directly reflect some json object the Uber API returns) that this package contains. This file also has global constants and variables. Finally, `uber.go` contains a few error types that are used in the package itself.
2. `client.go` contains the definition of `Client` (the type with which the user interacts). Aside from the constructor for the client, this file contains low-level functions for generating and executing HTTP requests to the Uber API.
3. `endpoints.go` contains the definitions of the exported methods on `Client` that call the Uber API endpoints. This is the meat of this package's API.
4. `auth.go` contains all the functions related to authorizing your app.
5. `requests.go` contains a plethora of unexported types needed to make requests and parse responses.
TODO ¶
Write tests.
Index ¶
- Constants
- Variables
- type Client
- func (c *Client) AutOAuth(clientID, clientSecret, redirect string, scope ...string) error
- func (c *Client) DeleteRequest(requestID string) error
- func (c *Client) GetPrices(startLat, startLon, endLat, endLon float64) ([]*Price, error)
- func (c *Client) GetProducts(lat, lon float64) ([]*Product, error)
- func (c *Client) GetRequest(requestID string) (*Request, error)
- func (c *Client) GetRequestMap(requestID string) (string, error)
- func (c *Client) GetTimes(startLat, startLon float64, uuid, productID string) ([]*Time, error)
- func (c *Client) GetUserActivity(offset, limit int) (*UserActivity, error)
- func (c *Client) GetUserProfile() (*User, error)
- func (c *Client) OAuth(clientID, clientSecret, redirect string, scope ...string) (string, error)
- func (c *Client) PostRequest(productID string, startLat, startLon, endLat, endLon float64, ...) (*Request, error)
- func (c *Client) SetAccessToken(authorizationCode string) error
- type Driver
- type Location
- type Price
- type Product
- type Request
- type Time
- type Trip
- type User
- type UserActivity
- type Vehicle
Examples ¶
Constants ¶
const ( Version = "v1" RequestEndpoint = "requests" ProductEndpoint = "products" PriceEndpoint = "estimates/price" TimeEndpoint = "estimates/time" HistoryEndpoint = "history" UserEndpoint = "me" // The `Request` is matching to the most efficient available driver. StatusProcessing = "processing" // The `Request` was unfulfilled because no drivers were available. StatusNoDrivers = "no_drivers_available" // The `Request` has been accepted by a driver and is "en route" to the // start_location. StatusAccepted = "accepted" // The driver has arrived or will be shortly. StatusArriving = "arriving" // The `Request` is "en route" from the start location to the end location. StatusInProgress = "in_progress" // The `Request` has been canceled by the driver. StatusDriverCanceled = "driver_canceled" // The `Request` has been canceled by the rider. StatusRiderCanceled = "rider_canceled" // The `Request` has been completed by the driver. StatusCompleted = "completed" AccessCodeEndpoint = "authorize" AccessTokenEndpoint = "token" State = "go-uber" Port = ":7635" )
Variables ¶
var ( UberAPIHost = fmt.Sprintf("https://api.uber.com/%s", Version) AuthHost = "https://login.uber.com/oauth" UberSandboxAPIHost = fmt.Sprintf("https://sandbox-api.uber.com/%s/sandbox", Version) )
declared as vars so that unit tests can edit the values and hit internal test server
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client stores the tokens needed to access the Uber api. All methods of this package that hit said api are methods on this type.
Example ¶
In order to use the Uber API you must register an application at https://developer.uber.com/. In turn you will receive a `client_id`, `secret`, and `server_token`.
package main import ( uber "github.com/r-medina/go-uber" ) var client *uber.Client func main() { client = uber.NewClient("your server_token") }
Output:
Example (Auth) ¶
Uber's OAuth 2.0 flow requires the user go to URL they provide. You can generate this URL programatically by calling `client.OAuth`. After the user goes to URL and grants your application permissions, you need to figure out a way for the user to input the second argument of the URL to which they are redirected (ie: the `code` argument`AuthCode` in `RedirectUrl/?state=go-uber&code=AuthCode`). You then need to set the access token with `client.SetAccessToken`.
package main import ( "fmt" uber "github.com/r-medina/go-uber" ) var client *uber.Client func main() { url, err := client.OAuth( "your client_id", "your client_secret", "your redirect_url", "profile", // "profile" is justthe scope. You may also pass another argument "history" (or no // scope arguments). ) if err != nil { fmt.Printf("OAuth error: %+v\n", err) return } fmt.Printf("Please go to %+v to authorize this app.\n", url) client.SetAccessToken("AuthCode") }
Output:
Example (AutoAuth) ¶
Alternatively, you can automate the whole thing with the `client.AutoAuth`. This opens up a browser for the user.
package main import ( "fmt" uber "github.com/r-medina/go-uber" ) var client *uber.Client func main() { err := client.AutOAuth( "your client_id", "your client_secret", "your redirect_url", "profile", ) if err != nil { fmt.Printf("OAuth error: %+v\n", err) } }
Output:
Example (Requests) ¶
All requests require a valid server_token. Requests that require latitude or longitude as arguments are float64's (and should be valid coordinates).
package main import ( "fmt" uber "github.com/r-medina/go-uber" ) var client *uber.Client func main() { products, err := client.GetProducts(37.7759792, -122.41823) if err != nil { fmt.Println(err) } else { for _, product := range products { fmt.Println(*product) } } prices, err := client.GetPrices(41.827896, -71.393034, 41.826025, -71.406892) if err != nil { fmt.Println(err) } else { for _, price := range prices { fmt.Println(*price) } } }
Output:
Example (UserProfile) ¶
After authorizing, you can call the scoped endpoints to which your app has access.
package main import ( "fmt" uber "github.com/r-medina/go-uber" ) var client *uber.Client func main() { profile, err := client.GetUserProfile() if err != nil { fmt.Printf("GetUserProfile error: %+v\n", err) return } fmt.Println(profile) }
Output:
func NewClient ¶
NewClient creates a new client. The serverToken is your API token provided by Uber. When accessing a user's profile or activity a serverToken is not enough and an accessToken must be specified with the correct scope. To access those endpoints, use `*Client.OAuth()`
func (*Client) AutOAuth ¶
AutOAuth automatically does the authorization flow by opening the user's browser, asking them to authorize, then booting up a server to deal with the user's redirect and authorizing your client.
func (*Client) DeleteRequest ¶
DeleteRequest cancels an ongoing `Request` on behalf of a rider.
func (*Client) GetPrices ¶
GetPrices returns an estimated price range for each product offered at a given location. The price estimate is provided as a formatted string with the full price range and the localized currency symbol.
The response also includes low and high estimates, and the ISO 4217 currency code for situations requiring currency conversion. When surge is active for a particular product, its surge_multiplier will be greater than 1, but the price estimate already factors in this multiplier. https://developer.uber.com/v1/endpoints/#price-estimates
func (*Client) GetProducts ¶
GetProducts returns information about the Uber products offered at a given location. The response includes the display name and other details about each product, and lists the products in the proper display order. https://developer.uber.com/v1/endpoints/#product-types
func (*Client) GetRequest ¶
GetRequest gets the real time status of an ongoing trip that was created using the Ride Request endpoint.
func (*Client) GetRequestMap ¶
GetRequestMap get a map with a visual representation of a `Request`.
func (*Client) GetTimes ¶
GetTimes returns ETAs for all products offered at a given location, with the responses expressed as integers in seconds. We recommend that this endpoint be called every minute to provide the most accurate, up-to-date ETAs. The uuid and productID parameters can be empty strings. These provide additional experience customization.
func (*Client) GetUserActivity ¶
func (c *Client) GetUserActivity(offset, limit int) (*UserActivity, error)
GetUserActivity returns data about a user's lifetime activity with Uber. The response will include pickup locations and times, dropoff locations and times, the distance of past requests, and information about which products were requested.
func (*Client) GetUserProfile ¶
GetUserProfile returns information about the Uber user that has authorized with the application.
func (*Client) OAuth ¶
OAuth begins the authorization process with Uber. There's no way to do this strictly programatically because of the multi-step OAuth process. This method returns the URL that the user needs to go to in order for Uber to authorize your app and give you a authorization code.
func (*Client) PostRequest ¶
func (c *Client) PostRequest( productID string, startLat, startLon, endLat, endLon float64, surgeConfirmationID string, ) (*Request, error)
PostRequest allows a ride to be requested on behalf of an Uber user given their desired product, start, and end locations.
func (*Client) SetAccessToken ¶
SetAccessToken completes the third step of the authorization process. Once the user generates an authorization code
type Driver ¶
type Driver struct { PhoneNumber string `json:"phone_number"` Rating int `json:"rating"` PictureURL string `json:"picture_url"` Name string `json:"name"` }
Driver represents an Uber driver.
type Location ¶
type Location struct { // Human-readable address // eg: "706 Mission St, San Francisco, CA" Address string `json:"address,omitempty"` // eg: 37.7860099 Latitude float64 `json:"latitude"` // eg: -122.4025387 Longitude float64 `json:"longitude"` }
Location contains a human-readable address as well as the exact coordinates of a location.
type Price ¶
type Price struct { // eg: "08f17084-23fd-4103-aa3e-9b660223934b" ProductID string `json:"product_id"` // ISO 4217 currency code for situations requiring currency conversion // eg: "USD" CurrencyCode string `json:"currency_code"` // eg: "UberBLACK" DisplayName string `json:"display_name"` // Formatted string of estimate in local currency of the start location. Estimate // could be a range, a single number (flat rate) or "Metered" for TAXI. // eg: "$23-29" Estimate string `json:"estimate"` // The lowest value in the estimate for the given currency // eg: 23 LowEstimate int `json:"low_estimate"` // The highest value in the estimate for the given currency // eg: 29 HighEstimate int `json:"high_estimate"` // Uber price gouging factor // http://www.technologyreview.com/review/529961/in-praise-of-efficient-price-gouging/ // eg: 1 SurgeMultiplier float64 `json:"surge_multiplier"` }
Price contains information about a price estimate.
type Product ¶
type Product struct { // Unique identifier representing a specific product for a given latitude & // longitude. For example, uberX in San Francisco will have a different // product_id than uberX in Los Angeles. // eg: "327f7914-cd12-4f77-9e0c-b27bac580d03" ProductID string `json:"product_id"` // Description of product // eg: "The original Uber" Description string `json:"description"` // eg: "UberBLACK" DisplayName string `json:"display_name"` // eg: 4 Capacity int `json:"capacity"` // A URI specifying the location of an image // eg: "http://..." Image string `json:"image"` }
Product type specifies an Uber product. An Uber product refers to a specific type of car/service.
type Request ¶
type Request struct { RequestID string `json:"request_id"` Status string `json:"status"` Vehicle `json:"vehicle"` Driver `json:"driver"` Location `json:"location"` ETA int `json:"eta"` SurgeMultiplier float64 `json:"surge_multiplier"` }
Request contains the information relating to a request for an Uber done on behalf of a user.
type Time ¶
type Time struct { // eg: "5f41547d-805d-4207-a297-51c571cf2a8c" ProductID string `json:"product_id"` // eg: "UberBLACK" DisplayName string `json:"display_name"` // The ETA in seconds // eg: 410, ie: 6 minutes and 50 seconds Estimate int `json:"estimate"` }
Time contains information about the estimated time of arrival for a product at a given location in seconds.
type Trip ¶
type Trip struct { // Customer UUID // eg: "7354db54-cc9b-4961-81f2-0094b8e2d215" Uuid string `json:"uuid"` // Time in seconds // eg: 1401884467 RequestTime int `json:"request_time"` // eg: edf5e5eb-6ae6-44af-bec6-5bdcf1e3ed2c ProductID string `json:"product_id"` // String depicting the status of the trip. Don't know what values these could take // because the website only shows "completed" // eg: "completed" Status string `json:"status"` // Distance of request in miles (presumable that of the customer to he nearest driver) // eg: 0.0279562 Distance float64 `json:"distance"` // Start time of trip // eg: 1401884646 StartTime int `json:"start_time"` // Self explanatory (see `Location`) StartLocation *Location `json:"start_location"` // Start time of trip // eg: 1401884732 EndTime int `json:"end_time"` // Self explanatory (see `Location`) EndLocation *Location `json:"end_location"` }
Trip contains Information including the pickup location, dropoff location, request start time, request end time, and distance of requests (in miles), as well as the product type that was requested.
type User ¶
type User struct { // eg: "Uber" FirstName string `json:"first_name"` // eg: "Developer" LastName string `json:"last_name"` // eg: "developer@uber.com" Email string `json:"email"` // Image URI // eg: "https://..." Picture string `json:"picture"` // Promotion code user has activated // eg: "teypo" PromoCode string `json:"promo_code"` }
User is the response from the /me endpoint. Provides information about the authenticated users profile.
type UserActivity ¶
type UserActivity struct { // How much the list of returned results is offset by (position in pagination) // eg: 0 Offset int `json:"offset"` // Number of items retrieved (that is, the length of `History` in this struct, // but not the total length of the history) // eg: 1 Limit int `json:"limit"` // Total number of items available // eg: 5 Count int `json:"count"` // List of trips (see `Trip`) History []*Trip `json:"history"` }
UserActivity contains data about a user's lifetime activity with Uber.