Skip to content

Commit 9439ccd

Browse files
author
Jessica Garson
committed
adding python oauth 2.0 samples to bookmarks
1 parent db79cc2 commit 9439ccd

File tree

6 files changed

+319
-0
lines changed

6 files changed

+319
-0
lines changed
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import base64
2+
import hashlib
3+
import os
4+
import re
5+
import json
6+
import requests
7+
from requests.auth import AuthBase, HTTPBasicAuth
8+
from requests_oauthlib import OAuth2Session
9+
10+
# First, you will need to enable OAuth 2.0 in your App’s auth settings in the Developer Portal to get your client ID.
11+
# Inside your terminal you will need to set an enviornment variable
12+
# export CLIENT_ID='your-client-id'
13+
client_id = os.environ.get("CLIENT_ID")
14+
15+
# If you have selected a type of App that is a confidential client you will need to set a client secret.
16+
# Confidential Clients securely authenticate with the authorization server.
17+
18+
# Inside your terminal you will need to set an enviornment variable
19+
# export CLIENT_SECRET='your-client-secret'
20+
21+
# Remove the comment on the following line if you are using a confidential client
22+
# client_secret = os.environ.get("CLIENT_SECRET")
23+
24+
# Replace the following URL with your callback URL, which can be obtained from your App's auth settings.
25+
redirect_uri = "https://www.example.com"
26+
27+
# Set the scopes
28+
scopes = ["bookmark.read", "tweet.read", "users.read", "offline.access"]
29+
30+
# Create a code verifier
31+
code_verifier = base64.urlsafe_b64encode(os.urandom(30)).decode("utf-8")
32+
code_verifier = re.sub("[^a-zA-Z0-9]+", "", code_verifier)
33+
34+
# Create a code challenge
35+
code_challenge = hashlib.sha256(code_verifier.encode("utf-8")).digest()
36+
code_challenge = base64.urlsafe_b64encode(code_challenge).decode("utf-8")
37+
code_challenge = code_challenge.replace("=", "")
38+
39+
# Start an OAuth 2.0 session
40+
oauth = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scopes)
41+
42+
# Create an authorize URL
43+
auth_url = "https://twitter.com/i/oauth2/authorize"
44+
authorization_url, state = oauth.authorization_url(
45+
auth_url, code_challenge=code_challenge, code_challenge_method="S256"
46+
)
47+
48+
# Visit the URL to authorize your App to make requests on behalf of a user
49+
print(
50+
"Visit the following URL to authorize your App on behalf of your Twitter handle in a browser:"
51+
)
52+
print(authorization_url)
53+
54+
# Paste in your authorize URL to complete the request
55+
authorization_response = input(
56+
"Paste in the full URL after you've authorized your App:\n"
57+
)
58+
59+
# Fetch your access token
60+
token_url = "https://api.twitter.com/2/oauth2/token"
61+
62+
# The following line of code will only work if you are using a type of App that is a public client
63+
auth = False
64+
65+
# If you are using a confidential client you will need to pass in basic encoding of your client ID and client secret.
66+
67+
# Please the comment on the following line if you are using a type of App that is a confidential client
68+
# auth = HTTPBasicAuth(client_id, client_secret)
69+
70+
token = oauth.fetch_token(
71+
token_url=token_url,
72+
authorization_response=authorization_response,
73+
auth=auth,
74+
client_id=client_id,
75+
include_client_id=True,
76+
code_verifier=code_verifier,
77+
)
78+
79+
# Your access token
80+
access = token["access_token"]
81+
82+
# Make a request to the users/me endpoint to get your user ID
83+
user_me = requests.request(
84+
"GET",
85+
"https://api.twitter.com/2/users/me",
86+
headers={"Authorization": "Bearer {}".format(access)},
87+
).json()
88+
user_id = user_me["data"]["id"]
89+
90+
# Make a request to the bookmarks url
91+
url = "https://api.twitter.com/2/users/{}/bookmarks".format(user_id)
92+
headers = {
93+
"Authorization": "Bearer {}".format(access),
94+
"User-Agent": "BookmarksSampleCode",
95+
}
96+
response = requests.request("GET", url, headers=headers)
97+
if response.status_code != 200:
98+
raise Exception(
99+
"Request returned an error: {} {}".format(response.status_code, response.text)
100+
)
101+
print("Response code: {}".format(response.status_code))
102+
json_response = response.json()
103+
print(json.dumps(json_response, indent=4, sort_keys=True))
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import base64
2+
import hashlib
3+
import os
4+
import re
5+
import json
6+
import requests
7+
from requests.auth import AuthBase, HTTPBasicAuth
8+
from requests_oauthlib import OAuth2Session
9+
10+
# Replace with a Tweet ID you want to Bookmark
11+
tweet_to_bookmark = {"tweet_id": "1460323737035677698"}
12+
13+
# You will need to enable OAuth 2.0 in your App’s auth settings in the Developer Portal to get your client ID.
14+
# Inside your terminal you will need to set an enviornment variable
15+
# export CLIENT_ID='your-client-id'
16+
client_id = os.environ.get("CLIENT_ID")
17+
18+
# If you have selected a type of App that is a confidential client you will need to set a client secret.
19+
# Confidential Clients securely authenticate with the authorization server.
20+
21+
# Inside your terminal you will need to set an enviornment variable
22+
# export CLIENT_SECRET='your-client-secret'
23+
24+
# Remove the comment on the following line if you are using a confidential client
25+
# client_secret = os.environ.get("CLIENT_SECRET")
26+
27+
# Replace the following URL with your callback URL, which can be obtained from your App's auth settings.
28+
redirect_uri = "https://www.example.com"
29+
30+
# Set the scopes
31+
scopes = ["bookmark.write", "tweet.read", "users.read", "offline.access"]
32+
33+
# Create a code verifier
34+
code_verifier = base64.urlsafe_b64encode(os.urandom(30)).decode("utf-8")
35+
code_verifier = re.sub("[^a-zA-Z0-9]+", "", code_verifier)
36+
37+
# Create a code challenge
38+
code_challenge = hashlib.sha256(code_verifier.encode("utf-8")).digest()
39+
code_challenge = base64.urlsafe_b64encode(code_challenge).decode("utf-8")
40+
code_challenge = code_challenge.replace("=", "")
41+
42+
# Start and OAuth 2.0 session
43+
oauth = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scopes)
44+
45+
# Create an authorize URL
46+
auth_url = "https://twitter.com/i/oauth2/authorize"
47+
authorization_url, state = oauth.authorization_url(
48+
auth_url, code_challenge=code_challenge, code_challenge_method="S256"
49+
)
50+
51+
# Visit the URL to authorize your App to make requests on behalf of a user
52+
print(
53+
"Visit the following URL to authorize your App on behalf of your Twitter handle in a browser:"
54+
)
55+
print(authorization_url)
56+
57+
# Paste in your authorize URL to complete the request
58+
authorization_response = input(
59+
"Paste in the full URL after you've authorized your App:\n"
60+
)
61+
62+
# Fetch your access token
63+
token_url = "https://api.twitter.com/2/oauth2/token"
64+
65+
# The following line of code will only work if you are using a type of App that is a public client
66+
auth = False
67+
68+
# If you are using a confidential client you will need to pass in basic encoding of your client ID and client secret.
69+
70+
# Please the comment on the following line if you are using a type of App that is a confidential client
71+
# auth = HTTPBasicAuth(client_id, client_secret)
72+
73+
token = oauth.fetch_token(
74+
token_url=token_url,
75+
authorization_response=authorization_response,
76+
auth=auth,
77+
client_id=client_id,
78+
include_client_id=True,
79+
code_verifier=code_verifier,
80+
)
81+
82+
# Your access token
83+
access = token["access_token"]
84+
85+
# Make a request to the users/me endpoint to get your user ID
86+
user_me = requests.request(
87+
"GET",
88+
"https://api.twitter.com/2/users/me",
89+
headers={"Authorization": "Bearer {}".format(access)},
90+
).json()
91+
user_id = user_me["data"]["id"]
92+
93+
# Make a request to the bookmarks url
94+
url = "https://api.twitter.com/2/users/{}/bookmarks".format(user_id)
95+
headers = {
96+
"Authorization": "Bearer {}".format(access),
97+
"Content-Type": "application/json",
98+
"User-Agent": "BookmarksSampleCode",
99+
}
100+
response = requests.request("POST", url, headers=headers, json=tweet_to_bookmark)
101+
if response.status_code != 200:
102+
raise Exception(
103+
"Request returned an error: {} {}".format(response.status_code, response.text)
104+
)
105+
print("Response code: {}".format(response.status_code))
106+
json_response = response.json()
107+
print(json.dumps(json_response, indent=4, sort_keys=True))
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import base64
2+
import hashlib
3+
import os
4+
import re
5+
import json
6+
import requests
7+
from requests.auth import AuthBase, HTTPBasicAuth
8+
from requests_oauthlib import OAuth2Session
9+
10+
# Replace with a Tweet ID you want to remove Bookmark of
11+
bookmarked_tweet_id = "1460323737035677698"
12+
13+
# You will need to enable OAuth 2.0 in your App’s auth settings in the Developer Portal to get your client ID.
14+
# Inside your terminal you will need to set an enviornment variable
15+
# export CLIENT_ID='your-client-id'
16+
client_id = os.environ.get("CLIENT_ID")
17+
18+
# If you have selected a type of App that is a confidential client you will need to set a client secret.
19+
# Confidential Clients securely authenticate with the authorization server.
20+
21+
# Inside your terminal you will need to set an enviornment variable
22+
# export CLIENT_SECRET='your-client-secret'
23+
24+
# Remove the comment on the following line if you are using a confidential client
25+
# client_secret = os.environ.get("CLIENT_SECRET")
26+
27+
28+
# Replace the following URL with your callback URL, which can be obtained from your App's auth settings.
29+
redirect_uri = "https://www.example.com"
30+
31+
# Set the scopes
32+
scopes = ["bookmark.write", "tweet.read", "users.read", "offline.access"]
33+
34+
# Create a code verifier
35+
code_verifier = base64.urlsafe_b64encode(os.urandom(30)).decode("utf-8")
36+
code_verifier = re.sub("[^a-zA-Z0-9]+", "", code_verifier)
37+
38+
# Create a code challenge
39+
code_challenge = hashlib.sha256(code_verifier.encode("utf-8")).digest()
40+
code_challenge = base64.urlsafe_b64encode(code_challenge).decode("utf-8")
41+
code_challenge = code_challenge.replace("=", "")
42+
43+
# Start and OAuth 2.0 session
44+
oauth = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scopes)
45+
46+
# Create an authorize URL
47+
auth_url = "https://twitter.com/i/oauth2/authorize"
48+
authorization_url, state = oauth.authorization_url(
49+
auth_url, code_challenge=code_challenge, code_challenge_method="S256"
50+
)
51+
52+
# Visit the URL to authorize your App to make requests on behalf of a user
53+
print(
54+
"Visit the following URL to authorize your App on behalf of your Twitter handle in a browser:"
55+
)
56+
print(authorization_url)
57+
58+
# Paste in your authorize URL to complete the request
59+
authorization_response = input(
60+
"Paste in the full URL after you've authorized your App:\n"
61+
)
62+
63+
# Fetch your access token
64+
token_url = "https://api.twitter.com/2/oauth2/token"
65+
66+
# The following line of code will only work if you are using a type of App that is a public client
67+
auth = False
68+
69+
# If you are using a confidential client you will need to pass in basic encoding of your client ID and client secret.
70+
71+
# Please the comment on the following line if you are using a type of App that is a confidential client
72+
# auth = HTTPBasicAuth(client_id, client_secret)
73+
74+
token = oauth.fetch_token(
75+
token_url=token_url,
76+
authorization_response=authorization_response,
77+
auth=auth,
78+
client_id=client_id,
79+
include_client_id=True,
80+
code_verifier=code_verifier,
81+
)
82+
83+
# Your access token
84+
access = token["access_token"]
85+
86+
# Make a request to the users/me endpoint to get the user ID of the authenticated user
87+
user_me = requests.request(
88+
"GET",
89+
"https://api.twitter.com/2/users/me",
90+
headers={"Authorization": "Bearer {}".format(access)},
91+
).json()
92+
user_id = user_me["data"]["id"]
93+
94+
# Make a request to the bookmarks url
95+
url = "https://api.twitter.com/2/users/{}/bookmarks/{}".format(
96+
user_id, bookmarked_tweet_id
97+
)
98+
headers = {
99+
"Authorization": "Bearer {}".format(access),
100+
"User-Agent": "BookmarksSampleCode",
101+
}
102+
response = requests.request("DELETE", url, headers=headers)
103+
if response.status_code != 200:
104+
raise Exception(
105+
"Request returned an error: {} {}".format(response.status_code, response.text)
106+
)
107+
print("Response code: {}".format(response.status_code))
108+
json_response = response.json()
109+
print(json.dumps(json_response, indent=4, sort_keys=True))

0 commit comments

Comments
 (0)