Created
July 16, 2016 01:56
-
-
Save jaakko-sf/f5d8461aa8d737035776f7dfd75b67bf to your computer and use it in GitHub Desktop.
Script to generate Twitter App-Only OAuth 2 bearer token
This file contains 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
import base64 | |
import requests | |
consumer_key = 'CONSUMER_KEY' | |
consumer_secret = 'CONSUMER_SECRET' | |
# get bearer token for application only requests | |
bearer_token_credentials = base64.urlsafe_b64encode( | |
'{}:{}'.format(consumer_key, consumer_secret).encode('ascii')).decode('ascii') | |
url = 'https://api.twitter.com/oauth2/token' | |
headers = { | |
'Authorization': 'Basic {}'.format(bearer_token_credentials), | |
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', | |
} | |
data = 'grant_type=client_credentials' | |
response = requests.post(url, headers=headers, data=data) | |
response_data = response.json() | |
if response_data['token_type'] == 'bearer': | |
bearer_token = response_data['access_token'] | |
print('Bearer Token:\t{}'.format(bearer_token)) | |
else: | |
raise RuntimeError('unexpected token type: {}'.format(response_data['token_type'])) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment