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='HMAC-SHA1', signature_type='AUTH_HEADER', rsa_key=None, verifier=None, decoding='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='HMAC-SHA1', signature_type='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 = 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'
property 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, pkce=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.

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

property 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='', auth=None, username=None, password=None, method='POST', force_querystring=False, timeout=None, headers=None, verify=None, proxies=None, include_client_id=None, client_secret=None, cert=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.

The current implementation enforces the RFC guidelines.

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 required by LegacyApplicationClients to appear in the request body.

  • password – Password required by LegacyApplicationClients to appear in the request body.

  • method – The HTTP method used to make the request. Defaults to POST, but may also be GET. Other methods should be added as needed.

  • force_querystring – If True, force the request body to be sent in the querystring instead.

  • timeout – Timeout of the request in seconds.

  • headers – Dict to default request headers with.

  • verify – Verify SSL certificate.

  • proxies – The proxies argument is passed onto requests.

  • include_client_id – Should the request body include the client_id parameter. Default is None, which will attempt to autodetect. This can be forced to always include (True) or never include (False).

  • client_secret – The client_secret paired to the client_id. This is generally required unless provided in the auth tuple. If the value is None, it will be omitted from the request, however if the value is an empty string, an empty string will be sent.

  • cert – Client certificate to send for OAuth 2.0 Mutual-TLS Client Authentication (draft-ietf-oauth-mtls). Can either be the path of a file containing the private key and certificate or a tuple of two filenames for certificate and key.

  • 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='', auth=None, timeout=None, headers=None, verify=None, 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.

  • headers – A dict of headers to be used by requests.

  • verify – Verify SSL certificate.

  • proxies – The proxies argument will be passed to requests.

  • 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. access_token_request invoked before making a token fetch request. refresh_token_request invoked before making a refresh 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, files=None, **kwargs)

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

property scope

By default the scope from the client is used, except if overridden

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