Coder Social home page Coder Social logo

rides-python-sdk's Introduction

Uber Rides Python SDK

Python SDK (beta) to support the Uber Rides API.

Installation

To use the Uber Rides Python SDK:

$ pip install uber_rides

Head over to pip-installer for instructions on installing pip.

To run from source, you can download the source code for uber-rides, and then run:

$ python setup.py install

We recommend using virtualenv when setting up your project environment. You may need to run the above commands with sudo if you’re not using it.

Read-Only Use

If you just need read-only access to Uber API resources, like getting a location’s available products, create a Session with the server token you received after registering your app.

from uber_rides.session import Session
session = Session(server_token=YOUR_SERVER_TOKEN)

Use this Session to create an UberRidesClient and fetch API resources:

from uber_rides.client import UberRidesClient
client = UberRidesClient(session)
response = client.get_products(37.77, -122.41)
products = response.json.get('products')

Authorization

If you need to access protected resources or modify resources (like getting a user’s ride history or requesting a ride), you will need the user to grant access to your application through the OAuth 2.0 Authorization Code flow. See Uber API docs.

The Authorization Code flow is a two-step authorization process. The first step is having the user authorize your app and the second involves requesting an OAuth 2.0 access token from Uber. This process is mandatory if you want to take actions on behalf of a user or access their information.

from uber_rides.auth import AuthorizationCodeGrant
auth_flow = AuthorizationCodeGrant(
    YOUR_CLIENT_ID,
    YOUR_PERMISSION_SCOPES,
    YOUR_CLIENT_SECRET,
    YOUR_REDIRECT_URL,
)
auth_url = auth_flow.get_authorization_url()

You can find YOUR_CLIENT_ID and YOUR_CLIENT_SECRET in the developer dashboard under the settings tab of your application. YOUR_PERMISSION_SCOPES is the list of scopes you have requested in the authorizations tab. Note that YOUR_REDIRECT_URL must match the value you provided when you registered your application.

Navigate the user to the auth_url where they can grant access to your application. After, they will be redirected to a redirect_url with the format YOUR_REDIRECT_URL?code=UNIQUE_AUTH_CODE. Use this redirect_url to create a session and start UberRidesClient.

session = auth_flow.get_session(redirect_url)
client = UberRidesClient(session)
credentials = session.oauth2credential

Keep credentials information in a secure data store and reuse them to make API calls on behalf of your user. The SDK will handle the token refresh for you automatically when it makes API requests with an UberRidesClient.

Example Apps

Navigate to the example folder to access the python example apps. Before you can run an example, you must edit the example/config.*.yaml file and add your app credentials from the Uber developer dashboard.

To get an UberRidesClient through the Authorization Code flow, run:

$ python example/authorize_rider.py

The example above stores user credentials in example/oauth2_rider_session_store.yaml. To create an UberRidesClient with these credentials and go through a surge ride request run:

$ python example/request_ride.py

---

To get an UberRidesClient authorized for driver endpoints, run:

$ python example/authorize_driver.py

The example above stores user credentials in example/oauth2_driver_session_store.yaml.

Flask Demo Apps

To get an understanding of how the sdk can be use in an example app see the flask examples for rider and driver dashboards:

$ pip install flask
$ python example/rider_dashboard.py
$ python example/driver_dashboard.py

Get Available Products

response = client.get_products(37.77, -122.41)
products = response.json.get('products')
product_id = products[0].get('product_id')

Get Price Estimates

response = client.get_price_estimates(
    start_latitude=37.770,
    start_longitude=-122.411,
    end_latitude=37.791,
    end_longitude=-122.405,
    seat_count=2
)

estimate = response.json.get('prices')

Get Rider Profile

response = client.get_rider_profile()
profile = response.json

first_name = profile.get('first_name')
last_name = profile.get('last_name')
email = profile.get('email')

Get User History

response = client.get_user_activity()
history = response.json

Request a Ride

# Get products for location
response = client.get_products(37.77, -122.41)
products = response.json.get('products')

product_id = products[0].get('product_id')

# Get upfront fare for product with start/end location
estimate = client.estimate_ride(
    product_id=product_id,
    start_latitude=37.77,
    start_longitude=-122.41,
    end_latitude=37.79,
    end_longitude=-122.41,
    seat_count=2
)
fare = estimate.json.get('fare')

# Request ride with upfront fare for product with start/end location
response = client.request_ride(
    product_id=product_id,
    start_latitude=37.77,
    start_longitude=-122.41,
    end_latitude=37.79,
    end_longitude=-122.41,
    seat_count=2,
    fare_id=fare['fare_id']
)

request = response.json
request_id = request.get('request_id')

# Request ride details from request_id
response = client.get_ride_details(request_id)
ride = response.json

# Cancel a ride
response = client.cancel_ride(request_id)
ride = response.json

This makes a real-world request and send an Uber driver to the specified start location.

To develop and test against request endpoints in a sandbox environment, make sure to instantiate your UberRidesClient with

client = UberRidesClient(session, sandbox_mode=True)

The default for sandbox_mode is set to False. See our documentation to read more about using the Sandbox Environment.

Update Sandbox Ride

If you are requesting sandbox rides, you will need to step through the different states of a ride.

response = client.update_sandbox_ride(ride_id, 'accepted')
response = client.update_sandbox_ride(ride_id, 'in_progress')

If the update is successful, response.status_code will be 204.

The update_sandbox_ride method is not valid in normal mode, where the ride status will change automatically.

Get Driver Profile

response = client.get_driver_profile()
profile = response.json

first_name = profile.get('first_name')
last_name = profile.get('last_name')
email = profile.get('email')

Get Driver Trips

response = client.get_driver_trips()
trips = response.json

Get Driver Payments

response = client.get_driver_payments()
payments = response.json

Get Uber for Business Receipts

from uber_rides.auth import ClientCredentialGrant
from uber_rides.client import UberRidesClient

auth_flow = ClientCredentialGrant(
<CLIENT_ID>,
<SCOPES>,
<CLIENT_SECRET>
)
session = auth_flow.get_session()

client = UberRidesClient(session)
receipt = client.get_business_trip_receipt('2a2f3da4-asdad-ds-12313asd')
pdf_url = client.get_business_trip_receipt_pdf_url('2a2f3da4-asdad-ds-12313asd')

Getting help

Uber developers actively monitor the Uber Tag on StackOverflow. If you need help installing or using the library, you can ask a question there. Make sure to tag your question with uber-api and python!

For full documentation about our API, visit our Developer Site.

See the Getting Started Tutorial.

Contributing

We love contributions. If you've found a bug in the library or would like new features added, go ahead and open issues or pull requests against this repo. Write a test to show your bug was fixed or the feature works as expected.

rides-python-sdk's People

Contributors

albertyw avatar christinekim avatar dustinwhittle avatar jheld avatar robbiet480 avatar shampab avatar subzidion avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rides-python-sdk's Issues

Can't call client.estimate_ride with server_token

Hello,

I need to call client.estimate_ride which authenticate by server_token.

However, It show the error.

>>> result = client.estimate_ride(
...     product_id='cafb57ec-5157-4462-8453-09a7fc01f5d1',
...     start_latitude=10.7212701,
...     start_longitude=106.61727189999999,
...     end_latitude=10.7718007,
...     end_longitude=106.7044406
... )
Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
  File "/Users/khoa/.virtualenvs/sosanhgiataxi/lib/python3.5/site-packages/uber_rides/client.py", line 326, in estimate_ride
    return self._api_call('POST', 'v1.2/requests/estimate', args=args)
  File "/Users/khoa/.virtualenvs/sosanhgiataxi/lib/python3.5/site-packages/uber_rides/client.py", line 104, in _api_call
    return request.execute()
  File "/Users/khoa/.virtualenvs/sosanhgiataxi/lib/python3.5/site-packages/uber_rides/request.py", line 152, in execute
    return self._send(prepared_request)
  File "/Users/khoa/.virtualenvs/sosanhgiataxi/lib/python3.5/site-packages/uber_rides/request.py", line 136, in _send
    response = session.send(prepared_request)
  File "/Users/khoa/.virtualenvs/sosanhgiataxi/lib/python3.5/site-packages/requests/sessions.py", line 615, in send
    r = dispatch_hook('response', hooks, r, **kwargs)
  File "/Users/khoa/.virtualenvs/sosanhgiataxi/lib/python3.5/site-packages/requests/hooks.py", line 31, in dispatch_hook
    _hook_data = hook(hook_data, **kwargs)
  File "/Users/khoa/.virtualenvs/sosanhgiataxi/lib/python3.5/site-packages/uber_rides/utils/handlers.py", line 60, in error_handler
    raise ClientError(response, error_message)
uber_rides.errors.ClientError: 401: Invalid OAuth 2.0 credentials provided.

API estimate response is different from the app

So i'm using following API call to get fare estimate:

response = api_client.estimate_ride(
        product_id=products[0].get('product_id'),
        start_latitude=home['lat'],
        start_longitude=home['long'],
        end_latitude=work['lat'],
        end_longitude=work['long'],
        seat_count=1
    )

the price in the response is different from what's shown on the actual Uber app. Why the discrepancy? Is this intentional?
Thanks.

OAuth 2.0 Credentials Refreshing Issue

Thank you for the great SDK. Totally appreciated!

I tried the simple example in the rides-python-sdk and I added the needed information in the "config.yaml" file and I got the right credentials in the "oauth2_session_store.yaml". I managed to request a ride with sandbox enabled and everything works like a charm.

Problem is 4 to 5 days later when I try to request a ride, I get 401: Invalid OAuth 2.0 credentials provided.

Under the "Authorization" section in the README.rst file it is stated that

The SDK will handle the token refresh for you automatically when it makes API requests with an UberRidesClient.

Am I missing any steps that I am not aware of ? or is this an issue with the example ?

Thank you again for your great effort providing a python SDK for Uber.

API Access

I have created an app in the uber developer dashboard so that I could access uber's API however accessing the API requires a Server Token. When going back into the app to find the server token I see the image linked https://postimg.cc/bZQscYNv which states that I need to contact my Uber Business Development representative, however, I have no idea how to do this.
Can you help me in finding someone to contact about this?

Retrieve data fails with 500 error (We have experienced a problem)

I'm getting errors when trying to fetch data such as user profile or activity.

here is my sample code :

import os
from datetime import datetime
from flask import Flask, request, flash, url_for, redirect, \
     render_template, abort, send_from_directory, redirect

from uber_rides.auth import AuthorizationCodeGrant
from uber_rides.session import Session
from uber_rides.client import UberRidesClient

app = Flask(__name__)
app.config.from_pyfile('flaskapp.cfg')

# Configure Uber Oauth2.0
auth_flow = AuthorizationCodeGrant(
    '<client_id>',
    ['profile', 'history'],
    '<client_secret>',
    'http://localhost:8080/callback'
    )

@app.route('/')
def index():
    auth_url = auth_flow.get_authorization_url()
    return redirect(auth_url, code=302)

@app.route('/callback')
def callback():
    session = auth_flow.get_session(request.url)
    client = UberRidesClient(session)
    credentials = session.oauth2credential

    # Fetch users profile
    response = client.get_user_profile()
    profile = response.json

    first_name = profile.get('first_name')
    last_name = profile.get('last_name')
    email = profile.get('email')

    # Fetch user activity
    response = client.get_user_activity()
    history = response.json

    return first_name, 200

if __name__ == '__main__':
    app.run(debug=True)

And trace of errors :

Starting WSGIServer type flask on 127.0.0.1:8080 ...
INFO:werkzeug: * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
INFO:werkzeug:127.0.0.1 - - [15/Jan/2017 18:58:09] "GET / HTTP/1.1" 302 -
DEBUG:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): login.uber.com
DEBUG:requests.packages.urllib3.connectionpool:https://login.uber.com:443 "POST /oauth/token HTTP/1.1" 200 None
INFO:werkzeug:127.0.0.1 - - [15/Jan/2017 18:58:19] "GET /callback?state=z9ga01Y6kgNFRbgDbeEA3IjCYLMTnI7M&code=wwTzfIbFivsCoGE4RIu0rDb2fO22NI HTTP/1.1" 200 -
DEBUG:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): sandbox-api.uber.com
DEBUG:requests.packages.urllib3.connectionpool:https://sandbox-api.uber.com:443 "GET /v1.2/me HTTP/1.1" 500 75
INFO:werkzeug:127.0.0.1 - - [15/Jan/2017 18:58:35] "GET /profile HTTP/1.1" 500 -
ERROR:werkzeug:Error on request:

debug request library :

Starting WSGIServer type flask on 127.0.0.1:8080 ...
INFO:werkzeug: * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
^C(venv) Davids-MacBook-Pro:uber crazywizard$ clear
(venv) Davids-MacBook-Pro:uber crazywizard$ python app.py
Starting WSGIServer type flask on 127.0.0.1:8080 ...
INFO:werkzeug: * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
INFO:werkzeug:127.0.0.1 - - [17/Jan/2017 22:35:04] "GET / HTTP/1.1" 302 -
DEBUG:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): login.uber.com
send: 'POST /oauth/token HTTP/1.1\r\nHost: login.uber.com\r\nConnection: keep-alive\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nUser-Agent: python-requests/2.12.4\r\nContent-Length: 217\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\ncode=Mg1VBWKR0V0ioeLYTAv61pAbjy3WD4&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fcallback&client_id=xxx&client_secret=xxx&grant_type=authorization_code'
reply: 'HTTP/1.1 200 OK\r\n'
header: Server: nginx
header: Date: Tue, 17 Jan 2017 19:35:08 GMT
header: Content-Type: application/json
header: Transfer-Encoding: chunked
header: Connection: keep-alive
header: Pragma: no-cache
header: Cache-Control: no-store
header: Set-Cookie: session=ab5c70960ceb1415_587e71ec.pJiJyH80bf4wULzs_NpDCMc-Ymw; Domain=login.uber.com; Secure; HttpOnly; Path=/
header: X-Uber-App: login
header: Strict-Transport-Security: max-age=604800
header: X-Content-Type-Options: nosniff
header: X-XSS-Protection: 1; mode=block
header: Strict-Transport-Security: max-age=2592000
header: X-Frame-Options: SAMEORIGIN
header: Cache-Control: max-age=0
header: Content-Encoding: gzip
DEBUG:requests.packages.urllib3.connectionpool:https://login.uber.com:443 "POST /oauth/token HTTP/1.1" 200 None
DEBUG:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): sandbox-api.uber.com
send: 'GET /v1/products?latitude=37.77&longitude=-122.41 HTTP/1.1\r\nHost: sandbox-api.uber.com\r\nAccept-Encoding: identity\r\nX-Uber-User-Agent: Python Rides SDK v0.2.7\r\nAuthorization: Bearer xxx\r\n\r\n'
reply: 'HTTP/1.1 500 Internal Server Error\r\n'
header: Server: nginx
header: Date: Tue, 17 Jan 2017 19:35:09 GMT
header: Content-Type: application/json
header: Content-Length: 75
header: Connection: keep-alive
header: X-Uber-App: uberex-sandbox
header: X-Uber-App: migrator-uberex-sandbox-optimus
header: Strict-Transport-Security: max-age=604800
header: X-Content-Type-Options: nosniff
header: X-XSS-Protection: 1; mode=block
DEBUG:requests.packages.urllib3.connectionpool:https://sandbox-api.uber.com:443 "GET /v1/products?latitude=37.77&longitude=-122.41 HTTP/1.1" 500 75
INFO:werkzeug:127.0.0.1 - - [17/Jan/2017 22:35:10] "GET /callback?state=dH1nnut35q9xcOdC3W9a1lFKNqGXn9h5&code=Mg1VBWKR0V0ioeLYTAv61pAbjy3WD4 HTTP/1.1" 500 -
ERROR:werkzeug:Error on request:

I've noticed that after the oauth2.0 successfully completes, all other calls to the the Uber service, even non privileged ones, fail with 500 errors

Python 3.x: invalid exception handing syntax

except (ClientError, UberIllegalState), error: fail_print(error) return

Given syntax is invalid in Python 3.x. Only next syntax is allowed
except (ClientError, UberIllegalState) as error: fail_print(error) return

Problem with AuthorizationCodeGrant (auth_flow.get_authorization_url())

The call to AuthorizationCodeGrant does not seem to work:
The Authorization url that I generate following instructions on
https://developer.uber.com/docs/drivers/tutorials/api/pythonelf.auth_flow =

AuthorizationCodeGrant(self.client_id,self.scope,self.secret,self.redirect)
self.auth_url = self.auth_flow.get_authorization_url()

returns a string as follows
https://login.uber.com/oauth/v2/authorize?scope=h+i+s+t+o+r+y&state=XpHSFELXll499LqbJUCFhScbIxm3XhZm&redirect_uri=http%3A%2F%2Flocalhost&response_type=code&client_id=<redacted_client_id>

Instead of what I receive when I access web interface and it works correctly
https://login.uber.com/oauth/v2/authorize?response_type=code&client_id=<redacted_client_id>&scope=history&redirect_uri=http://localhost

Python 3.x: urlparse was renamed to urllib.parse

Unable to work with uber API within this SDK since it doesn't support Python 3.x (this might be an series of issues).

Issue-1: urlparse is not in the python 3.x libs, it was moved under urllib.parse

rate limit error

I'm getting rate limited even tho I'm only making 2 requests every 5 min, or 24 requests/hour. According to this doc we're allowed 2000 requests/hour... what gives?

My app id: mytestappnewyo
thanks.

I'm trying to test the uber signon with Auth0..redirect uri issues..

I'm attempting to connect my uber app with a Auth0 signon.
And allow my users to sign on using their uber accounts.

When setting up and then trying the integration,
I received the attached error...

screen shot 2016-08-12 at 12 24 30 pm

I see this is the link that is being activated when pressing the try button within Auth0:

https://teamxna2.auth0.com/authorize/?response_type=code&scope=openid%20profile&client_id=aC7p8ZN4QVaBSq0HrQCa83yHBiAEhYoF&connection=uber&redirect_uri=https://manage.auth0.com/tester/callback?connection=uber

So in the Uber App dashboard I changed my redirect uri to variations of...

https://manage.auth0.com/tester/callback?connection=uber
https://manage.auth0.com/tester/callback
https://manage.auth0.com

But i'm still recieving errors...What should put as the redirect URI in uber dash
to try this integration?

thanks!

Python 3.5: Switch from requests to aiohttp

In order to make library more desirable to be integrated into existing or new solution based on Python 3.5 (released on April 2015) it is necessary to switch into aiohttp lib that applies async paradigm of coroutines to HTTP workflows.

Improve default logging for all errors

Background

There are default messages defined for ClientError and ServerError in errors.py. This causes default message obscures the actual error and message when you simply log the error class as most developers would do.

Task

Implement logic in errors.py to populate message with the actual error content returned by the API rather than using a default message.

Why can't be used in China

I am a developer from China, why I can't use your SDK, If I need to modify, please tell me to change what

how to get the redirect url in script only

hello if i run the code it is working properly but how to automate the redirect uri in the code we have to copy and paste the link in the browser and it gives new uri but i want to automate that please help me

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.