or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-interface.mdauthentication.mdclient-v2.mddata-models.mdindex.mdlegacy-api.mdstreaming.mdutilities.md

authentication.mddocs/

0

# Authentication

1

2

Tweepy provides comprehensive authentication support for different Twitter API access patterns through multiple OAuth handlers. Each handler supports different application types and use cases, from simple app-only access to full user authorization flows.

3

4

## Capabilities

5

6

### OAuth 1.0a User Context Authentication

7

8

OAuth 1.0a User Context authentication enables applications to act on behalf of a specific Twitter user, providing access to user-specific endpoints and data.

9

10

```python { .api }

11

class OAuth1UserHandler:

12

def __init__(self, consumer_key, consumer_secret, access_token=None,

13

access_token_secret=None, callback=None):

14

"""

15

Initialize OAuth 1.0a User Context authentication handler.

16

17

Parameters:

18

- consumer_key (str): Consumer key from Twitter app dashboard

19

- consumer_secret (str): Consumer secret from Twitter app dashboard

20

- access_token (str, optional): User's access token

21

- access_token_secret (str, optional): User's access token secret

22

- callback (str, optional): Callback URL for authorization flow

23

"""

24

25

def get_authorization_url(self, signin_with_twitter=False, access_type=None):

26

"""

27

Get authorization URL for user to grant access to the application.

28

29

Parameters:

30

- signin_with_twitter (bool): Use Sign in with Twitter flow (default: False)

31

- access_type (str, optional): "read" or "write" access level

32

33

Returns:

34

tuple: (authorization_url, request_token_secret)

35

"""

36

37

def get_access_token(self, verifier=None):

38

"""

39

Exchange authorization verifier for access token.

40

41

Parameters:

42

- verifier (str, optional): OAuth verifier from callback or PIN

43

44

Returns:

45

tuple: (access_token, access_token_secret)

46

"""

47

48

def set_access_token(self, key, secret):

49

"""

50

Set access token and secret (deprecated - use constructor parameters).

51

52

Parameters:

53

- key (str): Access token

54

- secret (str): Access token secret

55

"""

56

57

def apply_auth(self):

58

"""

59

Apply authentication to HTTP requests.

60

61

Returns:

62

OAuth1 authentication object for requests

63

"""

64

```

65

66

#### Usage Example

67

68

```python

69

import tweepy

70

71

# Initialize handler with app credentials

72

auth = tweepy.OAuth1UserHandler(

73

consumer_key="your_consumer_key",

74

consumer_secret="your_consumer_secret",

75

callback="http://localhost:3000/callback"

76

)

77

78

# Get authorization URL

79

auth_url, request_token_secret = auth.get_authorization_url()

80

print(f"Please authorize: {auth_url}")

81

82

# After user authorizes, get verifier and exchange for access token

83

verifier = input("Enter verifier: ")

84

access_token, access_token_secret = auth.get_access_token(verifier)

85

86

# Create client with user authentication

87

client = tweepy.Client(

88

consumer_key="your_consumer_key",

89

consumer_secret="your_consumer_secret",

90

access_token=access_token,

91

access_token_secret=access_token_secret

92

)

93

94

# Now you can make user-authenticated requests

95

user = client.get_me()

96

print(f"Authenticated as: {user.data.username}")

97

```

98

99

### OAuth 2.0 Bearer Token Authentication

100

101

OAuth 2.0 Bearer Token authentication provides app-only access for applications that don't need to act on behalf of specific users.

102

103

```python { .api }

104

class OAuth2BearerHandler:

105

def __init__(self, bearer_token):

106

"""

107

Initialize OAuth 2.0 Bearer Token authentication handler.

108

109

Parameters:

110

- bearer_token (str): Bearer token from Twitter app dashboard

111

"""

112

113

def apply_auth(self):

114

"""

115

Apply authentication to HTTP requests.

116

117

Returns:

118

HTTPBearerAuth authentication object for requests

119

"""

120

```

121

122

#### Usage Example

123

124

```python

125

import tweepy

126

127

# Simple bearer token authentication

128

client = tweepy.Client(bearer_token="your_bearer_token")

129

130

# Make app-only requests

131

tweets = client.search_recent_tweets(query="python programming", max_results=10)

132

for tweet in tweets.data:

133

print(tweet.text)

134

```

135

136

### OAuth 2.0 App-Only Authentication

137

138

OAuth 2.0 App-Only authentication uses consumer credentials to obtain a bearer token programmatically.

139

140

```python { .api }

141

class OAuth2AppHandler:

142

def __init__(self, consumer_key, consumer_secret):

143

"""

144

Initialize OAuth 2.0 App-Only authentication handler.

145

146

Parameters:

147

- consumer_key (str): Consumer key from Twitter app dashboard

148

- consumer_secret (str): Consumer secret from Twitter app dashboard

149

"""

150

151

def apply_auth(self):

152

"""

153

Apply authentication to HTTP requests.

154

155

Returns:

156

HTTPBasicAuth authentication object for requests

157

"""

158

```

159

160

#### Usage Example

161

162

```python

163

import tweepy

164

165

# OAuth 2.0 App-Only authentication

166

auth = tweepy.OAuth2AppHandler(

167

consumer_key="your_consumer_key",

168

consumer_secret="your_consumer_secret"

169

)

170

171

# Use with legacy API

172

api = tweepy.API(auth)

173

tweets = api.search_tweets(q="python programming", count=10)

174

```

175

176

### OAuth 2.0 Authorization Code Flow with PKCE

177

178

OAuth 2.0 Authorization Code Flow with PKCE enables user authentication for modern applications with enhanced security.

179

180

```python { .api }

181

class OAuth2UserHandler:

182

def __init__(self, *, client_id, redirect_uri, scope, client_secret=None):

183

"""

184

Initialize OAuth 2.0 Authorization Code Flow with PKCE.

185

186

Parameters:

187

- client_id (str): OAuth 2.0 client ID from Twitter app dashboard

188

- redirect_uri (str): Registered redirect URI

189

- scope (list): List of requested scopes

190

- client_secret (str, optional): Client secret (for confidential clients)

191

"""

192

193

def get_authorization_url(self):

194

"""

195

Get authorization URL for user to grant access.

196

197

Returns:

198

tuple: (authorization_url, state, code_verifier)

199

"""

200

201

def fetch_token(self, authorization_response):

202

"""

203

Exchange authorization code for access token.

204

205

Parameters:

206

- authorization_response (str): Full authorization response URL

207

208

Returns:

209

dict: Token response with access_token, refresh_token, etc.

210

"""

211

```

212

213

#### Usage Example

214

215

```python

216

import tweepy

217

218

# OAuth 2.0 Authorization Code Flow with PKCE

219

oauth2_handler = tweepy.OAuth2UserHandler(

220

client_id="your_client_id",

221

redirect_uri="http://localhost:3000/callback",

222

scope=["tweet.read", "tweet.write", "users.read", "offline.access"]

223

)

224

225

# Get authorization URL

226

auth_url, state, code_verifier = oauth2_handler.get_authorization_url()

227

print(f"Please authorize: {auth_url}")

228

229

# After user authorizes and returns to callback

230

authorization_response = input("Enter full callback URL: ")

231

token = oauth2_handler.fetch_token(authorization_response)

232

233

# Create client with OAuth 2.0 user token

234

client = tweepy.Client(bearer_token=token["access_token"])

235

236

# Make user-authenticated requests

237

user = client.get_me()

238

print(f"Authenticated as: {user.data.username}")

239

```

240

241

### Legacy Authentication Aliases

242

243

Tweepy provides backward compatibility aliases for older authentication class names.

244

245

```python { .api }

246

class OAuthHandler(OAuth1UserHandler):

247

"""Deprecated alias for OAuth1UserHandler (use OAuth1UserHandler instead)"""

248

249

class AppAuthHandler(OAuth2AppHandler):

250

"""Deprecated alias for OAuth2AppHandler (use OAuth2AppHandler instead)"""

251

```

252

253

## Authentication Patterns

254

255

### Client Authentication Methods

256

257

The Client class accepts authentication credentials directly in its constructor:

258

259

```python

260

# Method 1: Direct credential parameters

261

client = tweepy.Client(

262

consumer_key="your_consumer_key",

263

consumer_secret="your_consumer_secret",

264

access_token="your_access_token",

265

access_token_secret="your_access_token_secret"

266

)

267

268

# Method 2: Bearer token only

269

client = tweepy.Client(bearer_token="your_bearer_token")

270

271

# Method 3: Mixed authentication (bearer token + user credentials)

272

client = tweepy.Client(

273

bearer_token="your_bearer_token",

274

consumer_key="your_consumer_key",

275

consumer_secret="your_consumer_secret",

276

access_token="your_access_token",

277

access_token_secret="your_access_token_secret"

278

)

279

```

280

281

### API Authentication Methods

282

283

The legacy API class uses authentication handler objects:

284

285

```python

286

# OAuth 1.0a User Context

287

auth = tweepy.OAuth1UserHandler(

288

consumer_key="your_consumer_key",

289

consumer_secret="your_consumer_secret",

290

access_token="your_access_token",

291

access_token_secret="your_access_token_secret"

292

)

293

api = tweepy.API(auth)

294

295

# OAuth 2.0 Bearer Token

296

auth = tweepy.OAuth2BearerHandler(bearer_token="your_bearer_token")

297

api = tweepy.API(auth)

298

299

# OAuth 2.0 App-Only

300

auth = tweepy.OAuth2AppHandler(

301

consumer_key="your_consumer_key",

302

consumer_secret="your_consumer_secret"

303

)

304

api = tweepy.API(auth)

305

```

306

307

### StreamingClient Authentication

308

309

StreamingClient requires a bearer token for authentication:

310

311

```python

312

# Streaming authentication (bearer token required)

313

stream = tweepy.StreamingClient(bearer_token="your_bearer_token")

314

```

315

316

## Authentication Context Requirements

317

318

Different API endpoints require different authentication contexts:

319

320

- **App-only authentication**: Public data access (search, user lookup, tweet lookup)

321

- **User authentication**: Private data and write operations (post tweets, follow users, access home timeline)

322

- **Streaming**: Bearer token authentication for real-time data

323

324

### User Authentication Required

325

326

These operations require user authentication (`user_auth=True`):

327

328

- Creating, deleting, or modifying tweets

329

- Following, unfollowing, blocking, or muting users

330

- Accessing private user data (home timeline, bookmarks, muted users)

331

- Managing lists owned by the authenticated user

332

- Sending direct messages

333

334

### App-only Authentication Sufficient

335

336

These operations work with app-only authentication:

337

338

- Searching public tweets

339

- Getting public user information

340

- Accessing public lists and their tweets

341

- Getting public tweet information and metrics

342

- Searching Twitter Spaces

343

344

## Error Handling

345

346

Authentication errors are represented by specific exception types:

347

348

```python { .api }

349

class Unauthorized(HTTPException):

350

"""401 Unauthorized - Invalid or missing authentication credentials"""

351

352

class Forbidden(HTTPException):

353

"""403 Forbidden - Valid credentials but insufficient permissions"""

354

```

355

356

## Rate Limiting and Authentication

357

358

Different authentication contexts have different rate limits:

359

360

- **App-only authentication**: Shared rate limits across all requests from the app

361

- **User authentication**: Per-user rate limits, typically higher limits for most endpoints

362

- **Streaming**: Connection-based limits with different rules for filtered vs sample streams

363

364

Configure rate limit handling in the client:

365

366

```python

367

# Wait when rate limit is exceeded

368

client = tweepy.Client(

369

bearer_token="your_bearer_token",

370

wait_on_rate_limit=True

371

)

372

```