Created
February 8, 2022 13:02
-
-
Save igorbrigadir/6cf53b91a5ca164ba91076be3770978b to your computer and use it in GitHub Desktop.
Simplified example of using oAuth1.0a
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
| from requests_oauthlib import OAuth1Session | |
| import os | |
| import json | |
| # In your terminal please set your environment variables by running the following lines of code. | |
| # export 'CONSUMER_KEY'='<your_consumer_key>' | |
| # export 'CONSUMER_SECRET'='<your_consumer_secret>' | |
| # export 'ACCESS_TOKEN'='<your_access_token>' | |
| # export 'ACCESS_TOKEN_SECRET'='<your_access_token_secret>' | |
| consumer_key = os.environ.get("CONSUMER_KEY") | |
| consumer_secret = os.environ.get("CONSUMER_SECRET") | |
| access_token = os.environ.get("ACCESS_TOKEN") | |
| access_token_secret = os.environ.get("ACCESS_TOKEN_SECRET") | |
| # You can adjust ids to include a single Tweets | |
| # Or you can add to up to 100 comma-separated IDs | |
| params = {"ids": "1490791224856375298", "tweet.fields": "attachments,author_id,context_annotations,conversation_id,created_at,entities,geo,id,in_reply_to_user_id,lang,public_metrics,referenced_tweets,reply_settings,source,text,withheld,non_public_metrics,organic_metrics,possibly_sensitive,promoted_metrics"} | |
| # Tweet fields are adjustable. | |
| # Options include: | |
| # attachments, author_id, context_annotations, | |
| # conversation_id, created_at, entities, geo, id, | |
| # in_reply_to_user_id, lang, non_public_metrics, organic_metrics, | |
| # possibly_sensitive, promoted_metrics, public_metrics, referenced_tweets, | |
| # source, text, and withheld | |
| # the tweet id, 1490791224856375298 must have been authored by the same user as the Access Token. | |
| # Make the request | |
| oauth = OAuth1Session( | |
| consumer_key, | |
| client_secret=consumer_secret, | |
| resource_owner_key=access_token, | |
| resource_owner_secret=access_token_secret, | |
| ) | |
| response = oauth.get( | |
| "https://api.twitter.com/2/tweets", params=params | |
| ) | |
| if response.status_code != 200: | |
| raise Exception( | |
| "Request returned an error: {} {}".format(response.status_code, response.text) | |
| ) | |
| print("Response code: {}".format(response.status_code)) | |
| json_response = response.json() | |
| print(json.dumps(json_response, indent=4, sort_keys=True)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment