0
# Data Models
1
2
Tweepy provides rich data model classes representing Twitter objects with full field access and type safety. These models correspond to Twitter API v2 objects and include tweets, users, media, spaces, lists, polls, places, and direct message events.
3
4
## Capabilities
5
6
### Tweet Model
7
8
Represents a Twitter tweet with all available fields from Twitter API v2.
9
10
```python { .api }
11
class Tweet:
12
"""
13
Twitter tweet object with full API v2 field support.
14
15
Attributes:
16
- id (str): Unique tweet identifier
17
- text (str): Tweet text content
18
- edit_history_tweet_ids (list): IDs of edit history tweets
19
- attachments (dict): Media and poll attachments
20
- author_id (str): ID of tweet author
21
- context_annotations (list): Context annotations
22
- conversation_id (str): ID of conversation root tweet
23
- created_at (datetime): Tweet creation timestamp
24
- edit_controls (dict): Edit control settings
25
- entities (dict): Extracted entities (mentions, hashtags, URLs, etc.)
26
- geo (dict): Geographic information
27
- in_reply_to_user_id (str): ID of user being replied to
28
- lang (str): Language code (BCP 47)
29
- non_public_metrics (dict): Private engagement metrics (author only)
30
- organic_metrics (dict): Organic engagement metrics (author only)
31
- possibly_sensitive (bool): Potentially sensitive content flag
32
- promoted_metrics (dict): Promoted tweet metrics (author only)
33
- public_metrics (dict): Public engagement metrics (likes, retweets, etc.)
34
- referenced_tweets (list): Referenced tweets (replies, quotes, retweets)
35
- reply_settings (str): Reply settings ("everyone", "mentionedUsers", "following")
36
- source (str): Tweet source application
37
- withheld (dict): Content withheld information
38
"""
39
```
40
41
### User Model
42
43
Represents a Twitter user with all available fields from Twitter API v2.
44
45
```python { .api }
46
class User:
47
"""
48
Twitter user object with full API v2 field support.
49
50
Attributes:
51
- id (str): Unique user identifier
52
- name (str): User's display name
53
- username (str): User's handle (without @)
54
- created_at (datetime): Account creation timestamp
55
- description (str): User's profile description/bio
56
- entities (dict): Extracted entities from profile (URLs, hashtags)
57
- location (str): User-provided location string
58
- pinned_tweet_id (str): ID of pinned tweet
59
- profile_image_url (str): Profile image URL
60
- protected (bool): Protected account flag
61
- public_metrics (dict): Public metrics (followers_count, following_count, etc.)
62
- url (str): User's website URL
63
- verified (bool): Legacy verification status
64
- verified_type (str): Verification type ("blue", "business", "government")
65
- withheld (dict): Account withheld information
66
"""
67
```
68
69
### Media Model
70
71
Represents media attachments (images, videos, GIFs) with metadata and metrics.
72
73
```python { .api }
74
class Media:
75
"""
76
Media attachment object with full metadata and metrics.
77
78
Attributes:
79
- media_key (str): Unique media identifier
80
- type (str): Media type ("photo", "video", "animated_gif")
81
- url (str): Media URL for photos
82
- duration_ms (int): Duration in milliseconds for videos
83
- height (int): Media height in pixels
84
- non_public_metrics (dict): Private media metrics (author only)
85
- organic_metrics (dict): Organic media metrics (author only)
86
- preview_image_url (str): Preview image URL for videos
87
- promoted_metrics (dict): Promoted media metrics (author only)
88
- public_metrics (dict): Public media metrics (view_count)
89
- width (int): Media width in pixels
90
- alt_text (str): Alternative text description
91
- variants (list): Media variants with different quality/format
92
"""
93
```
94
95
### Space Model
96
97
Represents Twitter Spaces (audio conversations) with participant and scheduling information.
98
99
```python { .api }
100
class Space:
101
"""
102
Twitter Space object with full metadata and participant information.
103
104
Attributes:
105
- id (str): Unique Space identifier
106
- state (str): Space state ("live", "scheduled", "ended")
107
- created_at (datetime): Space creation timestamp
108
- ended_at (datetime): Space end timestamp
109
- host_ids (list): List of host user IDs
110
- lang (str): Space language code
111
- is_ticketed (bool): Ticketed Space flag
112
- invited_user_ids (list): List of invited user IDs
113
- participant_count (int): Current participant count
114
- subscriber_count (int): Subscriber count
115
- scheduled_start (datetime): Scheduled start time
116
- speaker_ids (list): List of speaker user IDs
117
- started_at (datetime): Actual start timestamp
118
- title (str): Space title
119
- topic_ids (list): List of topic IDs
120
- updated_at (datetime): Last update timestamp
121
- creator_id (str): Space creator user ID
122
"""
123
```
124
125
### List Model
126
127
Represents Twitter lists with membership and metadata information.
128
129
```python { .api }
130
class List:
131
"""
132
Twitter list object with metadata and membership information.
133
134
Attributes:
135
- id (str): Unique list identifier
136
- name (str): List name
137
- created_at (datetime): List creation timestamp
138
- description (str): List description
139
- follower_count (int): Number of list followers
140
- member_count (int): Number of list members
141
- private (bool): Private list flag
142
- owner_id (str): List owner user ID
143
"""
144
```
145
146
### Poll Model
147
148
Represents Twitter polls with voting options and results.
149
150
```python { .api }
151
class Poll:
152
"""
153
Twitter poll object with voting options and results.
154
155
Attributes:
156
- id (str): Unique poll identifier
157
- options (list): Poll options with vote counts
158
- duration_minutes (int): Poll duration in minutes
159
- end_datetime (datetime): Poll end timestamp
160
- voting_status (str): Voting status ("open", "closed")
161
"""
162
```
163
164
### Place Model
165
166
Represents geographic places referenced in tweets.
167
168
```python { .api }
169
class Place:
170
"""
171
Geographic place object with location information.
172
173
Attributes:
174
- id (str): Unique place identifier
175
- full_name (str): Full place name
176
- name (str): Place name
177
- country (str): Country name
178
- country_code (str): Country code (ISO 3166-1 alpha-2)
179
- geo (dict): Geographic coordinates and bounding box
180
- place_type (str): Place type ("admin", "city", "country", etc.)
181
"""
182
```
183
184
### DirectMessageEvent Model
185
186
Represents direct message events with sender information and content.
187
188
```python { .api }
189
class DirectMessageEvent:
190
"""
191
Direct message event object with full message information.
192
193
Attributes:
194
- id (str): Unique event identifier
195
- text (str): Message text content
196
- event_type (str): Event type ("MessageCreate", "ParticipantsJoin", etc.)
197
- created_at (datetime): Event creation timestamp
198
- sender_id (str): Sender user ID
199
- dm_conversation_id (str): Conversation identifier
200
- referenced_tweet (dict): Referenced tweet information
201
- media_keys (list): List of attached media keys
202
- attachments (dict): Message attachments
203
"""
204
```
205
206
### ReferencedTweet Model
207
208
Represents tweets referenced by other tweets (replies, quotes, retweets).
209
210
```python { .api }
211
class ReferencedTweet:
212
"""
213
Referenced tweet object for replies, quotes, and retweets.
214
215
Attributes:
216
- type (str): Reference type ("replied_to", "quoted", "retweeted")
217
- id (str): Referenced tweet ID
218
"""
219
```
220
221
## Usage Examples
222
223
### Working with Tweet Objects
224
225
```python
226
import tweepy
227
228
client = tweepy.Client(bearer_token="your_bearer_token")
229
230
# Get tweet with full fields
231
tweet = client.get_tweet(
232
"1234567890123456789",
233
tweet_fields=["created_at", "public_metrics", "entities", "context_annotations"],
234
expansions=["author_id", "attachments.media_keys"],
235
user_fields=["username", "verified", "public_metrics"]
236
)
237
238
# Access tweet data
239
print(f"Tweet: {tweet.data.text}")
240
print(f"Created: {tweet.data.created_at}")
241
print(f"Likes: {tweet.data.public_metrics['like_count']}")
242
print(f"Retweets: {tweet.data.public_metrics['retweet_count']}")
243
244
# Access entities
245
if hasattr(tweet.data, 'entities'):
246
entities = tweet.data.entities
247
if 'hashtags' in entities:
248
hashtags = [tag['tag'] for tag in entities['hashtags']]
249
print(f"Hashtags: {hashtags}")
250
251
if 'mentions' in entities:
252
mentions = [mention['username'] for mention in entities['mentions']]
253
print(f"Mentions: {mentions}")
254
255
# Access included data
256
if tweet.includes and 'users' in tweet.includes:
257
author = tweet.includes['users'][0]
258
print(f"Author: @{author.username} ({author.name})")
259
print(f"Followers: {author.public_metrics['followers_count']}")
260
```
261
262
### Working with User Objects
263
264
```python
265
# Get user with metrics
266
user = client.get_user(
267
username="twitter",
268
user_fields=["created_at", "description", "public_metrics", "verified_type"],
269
expansions=["pinned_tweet_id"],
270
tweet_fields=["created_at", "public_metrics"]
271
)
272
273
# Access user data
274
print(f"User: {user.data.name} (@{user.data.username})")
275
print(f"Bio: {user.data.description}")
276
print(f"Joined: {user.data.created_at}")
277
print(f"Followers: {user.data.public_metrics['followers_count']:,}")
278
print(f"Following: {user.data.public_metrics['following_count']:,}")
279
print(f"Verified: {user.data.verified_type}")
280
281
# Access pinned tweet if available
282
if user.includes and 'tweets' in user.includes:
283
pinned_tweet = user.includes['tweets'][0]
284
print(f"Pinned tweet: {pinned_tweet.text}")
285
```
286
287
### Working with Media Objects
288
289
```python
290
# Search for tweets with media
291
tweets = client.search_recent_tweets(
292
query="cats has:images",
293
expansions=["attachments.media_keys"],
294
media_fields=["type", "url", "alt_text", "public_metrics"],
295
max_results=10
296
)
297
298
# Process media attachments
299
for tweet in tweets.data:
300
if tweet.attachments and 'media_keys' in tweet.attachments:
301
media_keys = tweet.attachments['media_keys']
302
303
# Find corresponding media objects in includes
304
if tweets.includes and 'media' in tweets.includes:
305
for media in tweets.includes['media']:
306
if media.media_key in media_keys:
307
print(f"Media type: {media.type}")
308
if hasattr(media, 'url'):
309
print(f"URL: {media.url}")
310
if hasattr(media, 'alt_text'):
311
print(f"Alt text: {media.alt_text}")
312
if hasattr(media, 'public_metrics'):
313
print(f"Views: {media.public_metrics.get('view_count', 0)}")
314
```
315
316
### Working with Space Objects
317
318
```python
319
# Search for live Spaces
320
spaces = client.search_spaces(
321
query="python programming",
322
space_fields=["host_ids", "participant_count", "started_at", "title"],
323
expansions=["host_ids"],
324
user_fields=["username", "name"]
325
)
326
327
# Process Space data
328
for space in spaces.data:
329
print(f"Space: {space.title}")
330
print(f"State: {space.state}")
331
print(f"Participants: {space.participant_count}")
332
333
# Access host information from includes
334
if spaces.includes and 'users' in spaces.includes:
335
hosts = [user for user in spaces.includes['users'] if user.id in space.host_ids]
336
host_names = [f"@{host.username}" for host in hosts]
337
print(f"Hosts: {', '.join(host_names)}")
338
```
339
340
## Data Model Relationships
341
342
### Response Structure
343
344
API responses contain data models organized in a structured format:
345
346
```python
347
# Response structure
348
response = client.get_tweet(tweet_id, expansions=["author_id"])
349
350
# Primary data
351
tweet = response.data # Tweet object
352
353
# Included data (related objects)
354
if response.includes:
355
users = response.includes.get('users', []) # List of User objects
356
media = response.includes.get('media', []) # List of Media objects
357
polls = response.includes.get('polls', []) # List of Poll objects
358
places = response.includes.get('places', []) # List of Place objects
359
spaces = response.includes.get('spaces', []) # List of Space objects
360
361
# Metadata
362
if response.meta:
363
result_count = response.meta.get('result_count')
364
next_token = response.meta.get('next_token')
365
```
366
367
### Field Access Patterns
368
369
Data models provide direct attribute access to all available fields:
370
371
```python
372
# Direct field access
373
tweet_id = tweet.id
374
tweet_text = tweet.text
375
created_at = tweet.created_at
376
377
# Check field availability
378
if hasattr(tweet, 'public_metrics'):
379
likes = tweet.public_metrics['like_count']
380
381
# Safe field access with defaults
382
metrics = getattr(tweet, 'public_metrics', {})
383
likes = metrics.get('like_count', 0)
384
```
385
386
### Field Constants
387
388
Use field constants to specify which fields to include in API requests:
389
390
```python
391
from tweepy import TWEET_FIELDS, USER_FIELDS, MEDIA_FIELDS
392
393
# Request specific fields
394
tweet = client.get_tweet(
395
tweet_id,
396
tweet_fields=TWEET_FIELDS, # All available tweet fields
397
user_fields=USER_FIELDS, # All available user fields
398
media_fields=MEDIA_FIELDS # All available media fields
399
)
400
```