Authentication
This supplements Twitter’s Authentication documentation.
Introduction
Tweepy supports the OAuth 1.0a User Context, OAuth 2.0 Bearer Token (App-Only), and OAuth 2.0 Authorization Code Flow with PKCE (User Context) authentication methods.
Twitter API v1.1
OAuth 2.0 Bearer Token (App-Only)
The simplest way to generate a bearer token is through your app’s Keys and Tokens tab under the Twitter Developer Portal Projects & Apps page.
You can then initialize OAuth2BearerHandler
with the bearer token and
initialize API
with the OAuth2BearerHandler
instance:
import tweepy
auth = tweepy.OAuth2BearerHandler("Bearer Token here")
api = tweepy.API(auth)
Alternatively, you can use the API / Consumer key and secret that can be found
on the same page and initialize OAuth2AppHandler
instead:
import tweepy
auth = tweepy.OAuth2AppHandler(
"API / Consumer Key here", "API / Consumer Secret here"
)
api = tweepy.API(auth)
OAuth 1.0a User Context
Similarly, the simplest way to authenticate as your developer account is to generate an access token and access token secret through your app’s Keys and Tokens tab under the Twitter Developer Portal Projects & Apps page.
You’ll also need the app’s API / consumer key and secret that can be found on that page.
You can then initialize OAuth1UserHandler
with all four credentials
and initialize API
with the OAuth1UserHandler
instance:
import tweepy
auth = tweepy.OAuth1UserHandler(
"API / Consumer Key here", "API / Consumer Secret here",
"Access Token here", "Access Token Secret here"
)
api = tweepy.API(auth)
To authenticate as a different user, see 3-legged OAuth.
Twitter API v2
Tweepy’s interface for Twitter API v2, Client
, handles OAuth 2.0
Bearer Token (application-only) and OAuth 1.0a User Context authentication for
you.
OAuth 2.0 Bearer Token (App-Only)
The simplest way to generate a bearer token is through your app’s Keys and Tokens tab under the Twitter Developer Portal Projects & Apps page.
You can then simply pass the bearer token to Client
when initializing
it:
import tweepy
client = tweepy.Client("Bearer Token here")
OAuth 1.0a User Context
Similarly, the simplest way to authenticate as your developer account is to generate an access token and access token secret through your app’s Keys and Tokens tab under the Twitter Developer Portal Projects & Apps page.
You’ll also need the app’s API / consumer key and secret that can be found on that page.
You can then simply pass all four credentials to Client
when
initializing it:
import tweepy
client = tweepy.Client(
consumer_key="API / Consumer Key here",
consumer_secret="API / Consumer Secret here",
access_token="Access Token here",
access_token_secret="Access Token Secret here"
)
To authenticate as a different user, see 3-legged OAuth.
OAuth 2.0 Authorization Code Flow with PKCE (User Context)
You can generate an access token to authenticate as a user using
OAuth2UserHandler
.
You’ll need to turn on OAuth 2.0 under the User authentication settings section of your app’s Settings tab under the Twitter Developer Portal Projects & Apps page. To do this, you’ll need to provide a Callback / Redirect URI / URL.
Then, you’ll need to note the app’s Client ID, which you can find through your app’s Keys and Tokens tab under the Twitter Developer Portal Projects & Apps page. If you’re using a confidential client, you’ll also need to generate a Client Secret.
You can then initialize OAuth2UserHandler
with the scopes you need:
import tweepy
oauth2_user_handler = tweepy.OAuth2UserHandler(
client_id="Client ID here",
redirect_uri="Callback / Redirect URI / URL here",
scope=["Scope here", "Scope here"],
# Client Secret is only necessary if using a confidential client
client_secret="Client Secret here"
)
For a list of scopes, see the Scopes section of Twitter’s OAuth 2.0 Authorization Code Flow with PKCE documentation.
Then, you can get the authorization URL:
print(oauth2_user_handler.get_authorization_url())
This can be used to have a user authenticate your app. Once they’ve done so, they’ll be redirected to the Callback / Redirect URI / URL you provided. You’ll need to pass that authorization response URL to fetch the access token:
response = oauth2_user_handler.fetch_token(
"Authorization Response URL here"
)
access_token = response["access_token"]
You can then pass the access token to Client
when initializing it:
client = tweepy.Client("Access Token here")
3-legged OAuth
This section supplements Twitter’s 3-legged OAuth flow documentation.
To authenticate as a user other than your developer account, you’ll need to obtain their access tokens through the 3-legged OAuth flow.
First, you’ll need to turn on OAuth 1.0 under the User authentication settings section of your app’s Settings tab under the Twitter Developer Portal Projects & Apps page. To do this, you’ll need to provide a Callback / Redirect URI / URL.
Then, you’ll need the app’s API / consumer key and secret that can be found through your app’s Keys and Tokens tab under the Twitter Developer Portal Projects & Apps page.
You can then initialize an instance of OAuth1UserHandler
:
import tweepy
oauth1_user_handler = tweepy.OAuth1UserHandler(
"API / Consumer Key here", "API / Consumer Secret here",
callback="Callback / Redirect URI / URL here"
)
Then, you can get the authorization URL:
print(oauth1_user_handler.get_authorization_url())
To use Log in with Twitter / Sign in with Twitter, you can set the
signin_with_twitter
parameter when getting the authorization URL:
print(oauth1_user_handler.get_authorization_url(signin_with_twitter=True))
This can be used to have a user authenticate your app. Once they’ve done so,
they’ll be redirected to the Callback / Redirect URI / URL you provided, with
oauth_token
and oauth_verifier
parameters.
You can then use the verifier to get the access token and secret:
access_token, access_token_secret = oauth1_user_handler.get_access_token(
"Verifier (oauth_verifier) here"
)
If you need to reinitialize OAuth1UserHandler
, you can set the request
token and secret afterward, before using the verifier to get the access token
and secret:
request_token = oauth1_user_handler.request_token["oauth_token"]
request_secret = oauth1_user_handler.request_token["oauth_token_secret"]
new_oauth1_user_handler = tweepy.OAuth1UserHandler(
"API / Consumer Key here", "API / Consumer Secret here",
callback="Callback / Redirect URI / URL here"
)
new_oauth1_user_handler.request_token = {
"oauth_token": "Request Token (oauth_token) here",
"oauth_token_secret": request_secret
}
access_token, access_token_secret = (
new_oauth1_user_handler.get_access_token(
"Verifier (oauth_verifier) here"
)
)
Otherwise, you can simply use the old instance of OAuth1UserHandler
.
You can then use this instance of OAuth1UserHandler
to initialize
API
:
api = tweepy.API(oauth1_user_handler)
You can also use the access_token
and access_token_secret
to initialize
a new instance of OAuth1UserHandler
to initialize API
:
auth = tweepy.OAuth1UserHandler(
"API / Consumer Key here", "API / Consumer Secret here",
"Access Token here", "Access Token Secret here"
)
api = tweepy.API(auth)
For initializing Client
, you can pass access_token
and
access_token_secret
directly:
client = tweepy.Client(
consumer_key="API / Consumer Key here",
consumer_secret="API / Consumer Secret here",
access_token="Access Token here",
access_token_secret="Access Token Secret here"
)
PIN-based OAuth
This section supplements Twitter’s PIN-based OAuth documentation.
The PIN-based OAuth flow can be used by setting the callback
parameter to
"oob"
:
import tweepy
oauth1_user_handler = tweepy.OAuth1UserHandler(
"API / Consumer Key here", "API / Consumer Secret here",
callback="oob"
)
You can then get the authorization URL the same way:
print(oauth1_user_handler.get_authorization_url())
When the user authenticates with this URL, they’ll be provided a PIN. You can retrieve this PIN from the user to use as the verifier:
verifier = input("Input PIN: ")
access_token, access_token_secret = oauth1_user_handler.get_access_token(
verifier
)
You can then use the instance of OAuth1UserHandler
and/or the
access_token
and access_token_secret
.
Reference
- class tweepy.OAuth1UserHandler(consumer_key, consumer_secret, access_token=None, access_token_secret=None, callback=None)
OAuth 1.0a User Context authentication handler
Changed in version 4.5: Renamed from
OAuthHandler
- get_authorization_url(signin_with_twitter=False, access_type=None)
Get the authorization URL to redirect the user to
- get_access_token(verifier=None)
After user has authorized the app, get access token and secret with verifier
- set_access_token(key, secret)
Deprecated since version 4.5: Set through initialization instead.
- class tweepy.OAuthHandler(consumer_key, consumer_secret, access_token=None, access_token_secret=None, callback=None)
Alias for
OAuth1UserHandler
Deprecated since version 4.5: Use
OAuth1UserHandler
instead.
- class tweepy.OAuth2AppHandler(consumer_key, consumer_secret)
OAuth 2.0 Bearer Token (App-Only) using API / Consumer key and secret authentication handler
Changed in version 4.5: Renamed from
AppAuthHandler
- class tweepy.AppAuthHandler(consumer_key, consumer_secret)
Alias for
OAuth2AppHandler
Deprecated since version 4.5: Use
OAuth2AppHandler
instead.
- class tweepy.OAuth2BearerHandler(bearer_token)
Bases:
requests.auth.AuthBase
OAuth 2.0 Bearer Token (App-Only) authentication handler
New in version 4.5.
- class tweepy.OAuth2UserHandler(*, client_id, redirect_uri, scope, client_secret=None)
Bases:
requests_oauthlib.oauth2_session.OAuth2Session
OAuth 2.0 Authorization Code Flow with PKCE (User Context) authentication handler
New in version 4.5.
Construct a new OAuth 2 client session.
- Parameters
client_id – Client id obtained during registration
client –
oauthlib.oauth2.Client
to be used. Default is WebApplicationClient which is useful for any hosted application but not mobile or desktop.scope – List of scopes you wish to request access to
redirect_uri – Redirect URI you registered as callback
token – Token dictionary, must include access_token and token_type.
state – State string used to prevent CSRF. This will be given when creating the authorization url and must be supplied when parsing the authorization response. Can be either a string or a no argument callable.
kwargs – Arguments to pass to the Session constructor.
- Auto_refresh_url
Refresh token endpoint URL, must be HTTPS. Supply this if you wish the client to automatically refresh your access tokens.
- Auto_refresh_kwargs
Extra arguments to pass to the refresh token endpoint.
- Token_updater
Method with one argument, token, to be used to update your token database on automatic token refresh. If not set a TokenUpdated warning will be raised when a token has been refreshed. This warning will carry the token in its token argument.
- get_authorization_url()
Get the authorization URL to redirect the user to
- fetch_token(authorization_response)
After user has authorized the app, fetch access token with authorization response URL