Developer Interface

OAuth 1.0

class requests_oauthlib.OAuth1(client_key, client_secret=None, resource_owner_key=None, resource_owner_secret=None, callback_uri=None, signature_method=u'HMAC-SHA1', signature_type=u'AUTH_HEADER', rsa_key=None, verifier=None, decoding=u'utf-8', client_class=None, force_include_body=False, **kwargs)

Signs the request using OAuth 1 (RFC5849)

client_class

alias of Client

OAuth 1.0 Session

class requests_oauthlib.OAuth1Session(client_key, client_secret=None, resource_owner_key=None, resource_owner_secret=None, callback_uri=None, signature_method=u'HMAC-SHA1', signature_type=u'AUTH_HEADER', rsa_key=None, verifier=None, client_class=None, force_include_body=False, **kwargs)

Request signing and convenience methods for the oauth dance.

What is the difference between OAuth1Session and OAuth1?

OAuth1Session actually uses OAuth1 internally and its purpose is to assist in the OAuth workflow through convenience methods to prepare authorization URLs and parse the various token and redirection responses. It also provide rudimentary validation of responses.

An example of the OAuth workflow using a basic CLI app and Twitter.

>>> # Credentials obtained during the registration.
>>> client_key = 'client key'
>>> client_secret = 'secret'
>>> callback_uri = 'https://127.0.0.1/callback'
>>>
>>> # Endpoints found in the OAuth provider API documentation
>>> request_token_url = 'https://api.twitter.com/oauth/request_token'
>>> authorization_url = 'https://api.twitter.com/oauth/authorize'
>>> access_token_url = 'https://api.twitter.com/oauth/access_token'
>>>
>>> oauth_session = OAuth1Session(client_key,client_secret=client_secret, callback_uri=callback_uri)
>>>
>>> # First step, fetch the request token.
>>> oauth_session.fetch_request_token(request_token_url)
{
    'oauth_token': 'kjerht2309u',
    'oauth_token_secret': 'lsdajfh923874',
}
>>>
>>> # Second step. Follow this link and authorize
>>> oauth_session.authorization_url(authorization_url)
'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback'
>>>
>>> # Third step. Fetch the access token
>>> redirect_response = raw_input('Paste the full redirect URL here.')
>>> oauth_session.parse_authorization_response(redirect_response)
{
    'oauth_token: 'kjerht2309u',
    'oauth_token_secret: 'lsdajfh923874',
    'oauth_verifier: 'w34o8967345',
}
>>> oauth_session.fetch_access_token(access_token_url)
{
    'oauth_token': 'sdf0o9823sjdfsdf',
    'oauth_token_secret': '2kjshdfp92i34asdasd',
}
>>> # Done. You can now make OAuth requests.
>>> status_url = 'http://api.twitter.com/1/statuses/update.json'
>>> new_status = {'status':  'hello world!'}
>>> oauth_session.post(status_url, data=new_status)
<Response [200]>
authorization_url(url, request_token=None, **kwargs)

Create an authorization URL by appending request_token and optional kwargs to url.

This is the second step in the OAuth 1 workflow. The user should be redirected to this authorization URL, grant access to you, and then be redirected back to you. The redirection back can either be specified during client registration or by supplying a callback URI per request.

Parameters:
  • url – The authorization endpoint URL.
  • request_token – The previously obtained request token.
  • kwargs – Optional parameters to append to the URL.
Returns:

The authorization URL with new parameters embedded.

An example using a registered default callback URI.

>>> request_token_url = 'https://api.twitter.com/oauth/request_token'
>>> authorization_url = 'https://api.twitter.com/oauth/authorize'
>>> oauth_session = OAuth1Session('client-key', client_secret='secret')
>>> oauth_session.fetch_request_token(request_token_url)
{
    'oauth_token': 'sdf0o9823sjdfsdf',
    'oauth_token_secret': '2kjshdfp92i34asdasd',
}
>>> oauth_session.authorization_url(authorization_url)
'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf'
>>> oauth_session.authorization_url(authorization_url, foo='bar')
'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&foo=bar'

An example using an explicit callback URI.

>>> request_token_url = 'https://api.twitter.com/oauth/request_token'
>>> authorization_url = 'https://api.twitter.com/oauth/authorize'
>>> oauth_session = OAuth1Session('client-key', client_secret='secret', callback_uri='https://127.0.0.1/callback')
>>> oauth_session.fetch_request_token(request_token_url)
{
    'oauth_token': 'sdf0o9823sjdfsdf',
    'oauth_token_secret': '2kjshdfp92i34asdasd',
}
>>> oauth_session.authorization_url(authorization_url)
'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback'
authorized

Boolean that indicates whether this session has an OAuth token or not. If self.authorized is True, you can reasonably expect OAuth-protected requests to the resource to succeed. If self.authorized is False, you need the user to go through the OAuth authentication dance before OAuth-protected requests to the resource will succeed.

fetch_access_token(url, verifier=None, **request_kwargs)

Fetch an access token.

This is the final step in the OAuth 1 workflow. An access token is obtained using all previously obtained credentials, including the verifier from the authorization step.

Note that a previously set verifier will be reset for your convenience, or else signature creation will be incorrect on consecutive requests.

>>> access_token_url = 'https://api.twitter.com/oauth/access_token'
>>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'
>>> oauth_session = OAuth1Session('client-key', client_secret='secret')
>>> oauth_session.parse_authorization_response(redirect_response)
{
    'oauth_token: 'kjerht2309u',
    'oauth_token_secret: 'lsdajfh923874',
    'oauth_verifier: 'w34o8967345',
}
>>> oauth_session.fetch_access_token(access_token_url)
{
    'oauth_token': 'sdf0o9823sjdfsdf',
    'oauth_token_secret': '2kjshdfp92i34asdasd',
}
fetch_request_token(url, realm=None, **request_kwargs)

Fetch a request token.

This is the first step in the OAuth 1 workflow. A request token is obtained by making a signed post request to url. The token is then parsed from the application/x-www-form-urlencoded response and ready to be used to construct an authorization url.

Parameters:
  • url – The request token endpoint URL.
  • realm – A list of realms to request access to.
  • **request_kwargs – Optional arguments passed to ‘’post’‘

function in ‘’requests.Session’’ :returns: The response in dict format.

Note that a previously set callback_uri will be reset for your convenience, or else signature creation will be incorrect on consecutive requests.

>>> request_token_url = 'https://api.twitter.com/oauth/request_token'
>>> oauth_session = OAuth1Session('client-key', client_secret='secret')
>>> oauth_session.fetch_request_token(request_token_url)
{
    'oauth_token': 'sdf0o9823sjdfsdf',
    'oauth_token_secret': '2kjshdfp92i34asdasd',
}
parse_authorization_response(url)

Extract parameters from the post authorization redirect response URL.

Parameters:url – The full URL that resulted from the user being redirected back from the OAuth provider to you, the client.
Returns:A dict of parameters extracted from the URL.
>>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'
>>> oauth_session = OAuth1Session('client-key', client_secret='secret')
>>> oauth_session.parse_authorization_response(redirect_response)
{
    'oauth_token: 'kjerht2309u',
    'oauth_token_secret: 'lsdajfh923874',
    'oauth_verifier: 'w34o8967345',
}
rebuild_auth(prepared_request, response)

When being redirected we should always strip Authorization header, since nonce may not be reused as per OAuth spec.

OAuth 2.0

class requests_oauthlib.OAuth2(client_id=None, client=None, token=None)

Adds proof of authorization (OAuth2 token) to the request.

class requests_oauthlib.TokenUpdated(token)

OAuth 2.0 Session

class requests_oauthlib.OAuth2Session(client_id=None, client=None, auto_refresh_url=None, auto_refresh_kwargs=None, scope=None, redirect_uri=None, token=None, state=None, token_updater=None, **kwargs)

Versatile OAuth 2 extension to requests.Session.

Supports any grant type adhering to oauthlib.oauth2.Client spec including the four core OAuth 2 grants.

Can be used to create authorization urls, fetch tokens and access protected resources using the requests.Session interface you are used to.

  • oauthlib.oauth2.WebApplicationClient (default): Authorization Code Grant
  • oauthlib.oauth2.MobileApplicationClient: Implicit Grant
  • oauthlib.oauth2.LegacyApplicationClient: Password Credentials Grant
  • oauthlib.oauth2.BackendApplicationClient: Client Credentials Grant

Note that the only time you will be using Implicit Grant from python is if you are driving a user agent able to obtain URL fragments.

authorization_url(url, state=None, **kwargs)

Form an authorization URL.

Parameters:
  • url – Authorization endpoint url, must be HTTPS.
  • state – An optional state string for CSRF protection. If not given it will be generated for you.
  • kwargs – Extra parameters to include.
Returns:

authorization_url, state

authorized

Boolean that indicates whether this session has an OAuth token or not. If self.authorized is True, you can reasonably expect OAuth-protected requests to the resource to succeed. If self.authorized is False, you need the user to go through the OAuth authentication dance before OAuth-protected requests to the resource will succeed.

fetch_token(token_url, code=None, authorization_response=None, body=u'', auth=None, username=None, password=None, method=u'POST', timeout=None, headers=None, verify=True, proxies=None, **kwargs)

Generic method for fetching an access token from the token endpoint.

If you are using the MobileApplicationClient you will want to use token_from_fragment instead of fetch_token.

Parameters:
  • token_url – Token endpoint URL, must use HTTPS.
  • code – Authorization code (used by WebApplicationClients).
  • authorization_response – Authorization response URL, the callback URL of the request back to you. Used by WebApplicationClients instead of code.
  • body – Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body.
  • auth – An auth tuple or method as accepted by requests.
  • username – Username used by LegacyApplicationClients.
  • password – Password used by LegacyApplicationClients.
  • method – The HTTP method used to make the request. Defaults to POST, but may also be GET. Other methods should be added as needed.
  • headers – Dict to default request headers with.
  • timeout – Timeout of the request in seconds.
  • verify – Verify SSL certificate.
  • kwargs – Extra parameters to include in the token request.
Returns:

A token dict

new_state()

Generates a state string to be used in authorizations.

refresh_token(token_url, refresh_token=None, body=u'', auth=None, timeout=None, headers=None, verify=True, proxies=None, **kwargs)

Fetch a new access token using a refresh token.

Parameters:
  • token_url – The token endpoint, must be HTTPS.
  • refresh_token – The refresh_token to use.
  • body – Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body.
  • auth – An auth tuple or method as accepted by requests.
  • timeout – Timeout of the request in seconds.
  • verify – Verify SSL certificate.
  • kwargs – Extra parameters to include in the token request.
Returns:

A token dict

register_compliance_hook(hook_type, hook)

Register a hook for request/response tweaking.

Available hooks are:
access_token_response invoked before token parsing. refresh_token_response invoked before refresh token parsing. protected_request invoked before making a request.

If you find a new hook is needed please send a GitHub PR request or open an issue.

request(method, url, data=None, headers=None, withhold_token=False, client_id=None, client_secret=None, **kwargs)

Intercept all requests and add the OAuth 2 token if present.

token_from_fragment(authorization_response)

Parse token from the URI fragment, used by MobileApplicationClients.

Parameters:authorization_response – The full URL of the redirect back to you
Returns:A token dict