Twitter API v2 Snippets for Python

Last Updated: 2022/02/09 02:51:09

There are a lot of libraries for oauth, and I usually use OAuth1Session in requests_oauthlib.

Actually, there are some other endpoints in Twitter API, and you can see more information from here (opens new window). I will update information as needed in this page.

# Create Session Object

What you should do is basically just to install OAuth1Session and to call OAuth1Session.get or OAuth1Session.post method.

# Install requests_oauthlib

$ pip install requests_oauthlib
1

# Python Code

from requests_oauthlib import OAuth1Session

# 1. Create Twitter Session
twitter = OAuth1Session(
    # Your own Keys
    'Consume Key', 
    'Cuosume Secret',
    "Access Token",
    "Access Secret Key"
)

# 2. Request Twitter API
res = twitter.get(...)

# 3. Do something with the response data
if res.status_code == 200:
    data = json.loads(res.text)
    print(pprint.pformat(data))
else:
    raise Exception("Status code(%d) : %s" % (res.status_code, res.text))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# Users Lookup

# GET /2/users/:id

res = twitter.get("https://api.twitter.com/2/users/1301851771703160833", params={
    'expansions' : 'pinned_tweet_id', # pinned tweet is added in `includes.tweets`
    'tweet.fields' : 'attachments' ,  # `includes.tweets` only when `expansions=pinned_tweet_id` is requested.
                                        # attachements
                                        # author_id
                                        # context_annotations
                                        # conversation_id
                                        # created_at
                                        # entities
                                        # geo
                                        # id
                                        # in_reply_to_user_id
                                        # lang
                                        # non_public_metrics
                                        # public_metrics
                                        # organic_metrics
                                        # promoted_metrics
                                        # possibly_sensitive
                                        # referenced_tweets
                                        # reply_settings
                                        # source
                                        # text
                                        # withheld
    'user.fields' : 'description',  # user fields on `data`
                                        # created_at
                                        # description
                                        # entities
                                        # id
                                        # location
                                        # name
                                        # pinned_tweet_id
                                        # profile_image_url
                                        # protected
                                        # public_metrics
                                        # url
                                        # username
                                        # verified
                                        # withheld
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

# GET /2/users

res = twitter.get("https://api.twitter.com/2/users", params={
    # (Required) user ids
    "ids" : "1461537035320438785,1292439870586011649", 

    # same as `/2/users/:id`
    'expansions' : 'pinned_tweet_id', 
    'tweet.fields' : 'attachments' , 
    'user.fields' : 'description', 
})
1
2
3
4
5
6
7
8
9

# GET /2/users/by

res = twitter.get("https://api.twitter.com/2/users/by", params={
    # (Required) usernames
    "usernames" : "Yamam0t08202008", 

    # following parameters are the same as `/2/users/:id`
    'expansions' : 'pinned_tweet_id', 
    'tweet.fields' : 'attachments' , 
    'user.fields' : 'description', 
})
1
2
3
4
5
6
7
8
9

# GET /2/users/by/username/:username

res = twitter.get("https://api.twitter.com/2/users/by/username/Yamam0t08202008", params={
    # following parameters are the same as `/2/users/:id`
    'expansions' : 'pinned_tweet_id', 
    'tweet.fields' : 'attachments' , 
    'user.fields' : 'description', 
})
1
2
3
4
5
6

# Tweets Lookup

# GET /2/tweets/:id

res = twitter.get("https://api.twitter.com/2/tweets/1466948088728518659" , params={
    "expansions" : "attachments.poll_ids",  # Additional data 
                                                # attachments.poll_ids
                                                # attachments.media_keys
                                                # author_id
                                                # entities.mentions.username
                                                # geo.place_id
                                                # in_reply_to_user_id
                                                # referenced_tweets.id
                                                # referenced_tweets.id.author_id
    "media.fields" : "preview_image_url",   # Media fields
                                                # duration_ms
                                                # height
                                                # media_key
                                                # preview_image_url
                                                # type
                                                # url
                                                # width
                                                # public_metrics
                                                # non_public_metrics
                                                # organic_metrics
                                                # promoted_metrics
                                                # alt_text
    "place.fields" : "name",                # Place fields
                                                # contained_within
                                                # country
                                                # country_code
                                                # full_name
                                                # geo,
                                                # id
                                                # name
                                                # place_type
    "poll.fields" : "voting_status",        # Poll fields
                                                # duration_minutes
                                                # end_datetime
                                                # id,
                                                # options
                                                # voting_status
    
    # following parameters are the same as `/2/users/:id`
    'tweet.fields' : 'attachments' , 
    'user.fields' : 'description', 
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

# GET /2/tweets

res = twitter.get("https://api.twitter.com/2/tweets", params={
    # (Required) tweet ids
    "ids" : "1466948088728518659", 
    
    # following parameters are the same as `/2/tweets/:id`
    "expansions"   : "attachments.poll_ids", 
    "media.fields" : "preview_image_url",
    "place.fields" : "name", 
    "poll.fields"  : "voting_status", 

    # following parameters are the same as `/2/users/:id`
    'tweet.fields' : 'attachments' , 
    'user.fields'  : 'description', 
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# Timelines

# GET /2/users/:id/tweets

res = twitter.get("https://api.twitter.com/2/users/1461537035320438785/tweets", params={
    "end_time"         : "2021-12-07T10:18:00Z", # Minimum allowable time is 2010-11-06T00:00:00Z
    "start_time"       : "2010-11-06T00:00:00Z", # Minimum allowable time is 2010-11-06T00:00:00Z
    "exclude"          : "replies" ,             # retweets | replies
    "max_results"      : 10,                     # 5-100
    "pagination_token" : ".....",                # use `next_token` or `previous_token` in response
    "since_id"         : "1466948088728518659",  # tweet id
    "until_id"         : "1466948088728518659",  # tweet id

    # following parameters are the same as `/2/tweets/:id`
    "expansions" : "attachments.poll_ids", 
    "media.fields" : "preview_image_url",
    "place.fields" : "name", 
    "poll.fields" : "voting_status", 

    # following parameters are the same as `/2/users/:id`
    'tweet.fields' : 'attachments' , 
    'user.fields' : 'description', 
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# GET /2/users/:id/mentions

res = twitter.get("https://api.twitter.com/2/users/1301851771703160833/mentions", params={
    "end_time"         : "2021-12-07T10:18:00Z", # Minimum allowable time is 2010-11-06T00:00:00Z
    "start_time"       : "2010-11-06T00:00:00Z", # Minimum allowable time is 2010-11-06T00:00:00Z
    "max_results"      : 10,                     # 5-100
    "pagination_token" : ".....",                # use `next_token` or `previous_token` in response
    "since_id"         : "1466948088728518659",  # tweet id
    "until_id"         : "1466948088728518659",  # tweet id

    # following parameters are the same as `/2/tweets/:id`
    "expansions"   : "attachments.poll_ids", 
    "media.fields" : "preview_image_url",
    "place.fields" : "name", 
    "poll.fields"  : "voting_status", 

    # following parameters are the same as `/2/users/:id`
    'tweet.fields' : 'attachments' , 
    'user.fields'  : 'description', 
})

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# Search Tweets

# GET /2/tweets/search/recent

res = twitter.get("https://api.twitter.com/2/tweets/search/recent", params={
    # (Required) search query
    # You can find how to build a query in `https://developer.twitter.com/en/docs/twitter-api/tweets/search/integrate/build-a-query`
    'query'            : '#Python', 

    "end_time"         : "2021-12-07T01:44:00Z", # YYYY-MM-DDTHH:mm:ssZ (ISO 8601/RFC 3339).
    "start_time"       : "2021-12-01T00:00:00Z", # YYYY-MM-DDTHH:mm:ssZ (ISO 8601/RFC 3339).
    "max_results"      : 10,                     # 5-100
    "next_token"       : "b26v8....w8xc0vx",     # use `meta.next_token` in response
    "since_id"         : "1466948088728518659",  # tweet id
    "until_id"         : "1466948088728518659",  # tweet id

    # following parameters are the same as `/2/tweets/:id`
    "expansions"   : "attachments.poll_ids", 
    "media.fields" : "preview_image_url",
    "place.fields" : "name", 
    "poll.fields"  : "voting_status", 

    # following parameters are the same as `/2/users/:id`
    'tweet.fields' : 'attachments' , 
    'user.fields'  : 'description', 
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# Retweets

# GET /2/tweets/:id/retweeted_by

res = twitter.get("https://api.twitter.com/2/tweets/1292439870586011649/retweeted_by", json={
    'expansions' : 'pinned_tweet_id', # pinned tweet is added in `includes.tweets`

    "max_results"      : 10,          # 10-100
    "pagination_token" : ".....",     # use `next_token` or `previous_token` in response

    # following parameters are the same as `/2/tweets/:id`
    "media.fields" : "preview_image_url",
    "place.fields" : "name", 
    "poll.fields"  : "voting_status", 

    # following parameters are the same as `/2/users/:id`
    'tweet.fields' : 'attachments' , 
    'user.fields'  : 'description', 
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# POST /2/users/:id/retweets

res = twitter.post("https://api.twitter.com/2/users/1292439870586011649/retweets", json={
    "tweet_id" : "1466948088728518659", # tweet id to RT
})
1
2
3

# DELETE /2/users/:id/retweets/:source_tweet_id

res = twitter.delete("https://api.twitter.com/2/users/1292439870586011649/retweets/1466948088728518659")
# `data.retweeted` will be `False` in successful response.
1
2

# Like

# GET /2/tweets/:id/liking_users

res = twitter.get("https://api.twitter.com/2/users/1292439870586011649/liking_users", json={
    'expansions' : 'pinned_tweet_id', # pinned tweet is added in `includes.tweets`

    "max_results"      : 10,          # 10-100
    "pagination_token" : ".....",     # use `next_token` or `previous_token` in response

    # following parameters are the same as `/2/tweets/:id`
    "media.fields" : "preview_image_url",
    "place.fields" : "name", 
    "poll.fields"  : "voting_status", 

    # following parameters are the same as `/2/users/:id`
    'tweet.fields' : 'attachments' , 
    'user.fields'  : 'description', 
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# GET /2/users/:id/liked_tweets

res = twitter.get("https://api.twitter.com/2/users/1292439870586011649/liked_tweets", json={
    "max_results"      : 10,          # 10-100
    "pagination_token" : ".....",     # use `next_token` or `previous_token` in response

    # following parameters are the same as `/2/tweets/:id`
    "expansions"   : "attachments.poll_ids",
    "media.fields" : "preview_image_url",
    "place.fields" : "name", 
    "poll.fields"  : "voting_status", 

    # following parameters are the same as `/2/users/:id`
    'tweet.fields' : 'attachments' , 
    'user.fields'  : 'description', 
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# POST /2/users/:id/likes

res = twitter.post("https://api.twitter.com/2/users/1292439870586011649/likes/", json={
    "tweet_id" : "1466948088728518659", # tweet id
})
1
2
3

# DELETE /2/users/:id/likes/:tweet_id

res = twitter.delete("https://api.twitter.com/2/users/1292439870586011649/likes/1466948088728518659")
# `data.liked` will be `False` in successful response.
1
2

Last Updated: 2022/02/09 02:51:09
Copyright © Web Ninja All Rights Reserved.