Last active
May 14, 2021 00:53
-
-
Save epikulski/c268cd7d85174ef30405977276e365ad to your computer and use it in GitHub Desktop.
Set up app-only authentication on Twitter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Scratch pad for experimenting with the twitter API. | |
""" | |
import base64 | |
import os | |
import requests | |
from requests_oauthlib import OAuth1 | |
""" | |
SECRETS | |
""" | |
# API Keys | |
api_key = os.getenv("TW_API_KEY") | |
api_secret_key = os.getenv("TW_API_SECRET_KEY") | |
""" | |
AUTHENTICATION | |
""" | |
# First, encode the keys in the way that twitter wants. | |
# See: https://developer.twitter.com/en/docs/basics/authentication/overview/application-only | |
api_key = api_key.encode("utf-8") | |
api_secret_key = api_secret_key.encode("utf-8") | |
bearer_token_credential = base64.b64encode(api_key + b":" + api_secret_key) | |
bearer_token_credential = bearer_token_credential.decode("utf-8") | |
# Next, lets get the bearer token from the API. | |
headers = { | |
"Authorization": f"Basic {bearer_token_credential}", | |
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", | |
} | |
data="grant_type=client_credentials" | |
response = requests.post("https://api.twitter.com/oauth2/token", headers=headers, data=data) | |
response = response.json() | |
bearer_token = response["access_token"] | |
""" | |
SEARCHING | |
""" | |
# Now we can send some requests to the search API using our bearer token. | |
search_params = {"q": "Khrushchev"} | |
search_response = requests.get( | |
"https://api.twitter.com/1.1/search/tweets.json", | |
params=search_params, | |
headers={"Authorization": f"Bearer {bearer_token}"} | |
) | |
search_response = search_response.json() | |
print("End of script") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment