I write the following code to try the free version of Twitter API v2
import requests
import os
# Retrieves the bearer token from the environment variables
bearer_token = os.environ.get("BEARER_TOKEN")
headers = {
'Authorization': f'Bearer {bearer_token}',
}
url = 'https://api.twitter.com/2/users/me'
response = requests.get(url, headers=headers)
# Prints the JSON response
print(response.json())
However, I got error message
{'title': 'Unsupported Authentication', 'detail': 'Authenticating with OAuth 2.0 Application-Only is forbidden for this endpoint. Supported authentication types are [OAuth 1.0a User Context, OAuth 2.0 User Context].', 'type': 'https://api.twitter.com/2/problems/unsupported-authentication', 'status': 403}
I thought this should not require User Context Authentication. If it does require, how should I modify my code.
I do try
consumer_key = os.environ["TWITTER_CONSUMER_KEY"]
consumer_secret = os.environ["TWITTER_CONSUMER_KEY_SECRET"]
access_token = os.environ["TWITTER_ACCESS_TOKEN"]
access_token_secret = os.environ["TWITTER_ACCESS_TOKEN_SECRET"]
# Authenticate using the keys
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
# Create an API class object
api = tweepy.API(auth)
However, i dont know how to connects these two parts.