I am a beginner working through the python basics course on Freecodecamp.com. I am using Mac OS, python3.10.
I am trying to connect to twitter’s API using an http request, gather data and then parse that data.
I made a twitter developer account and got my keys and tokens and all that stuff.
Here is a link to the exact problem I am working through (scroll down to where it says "Application 2: Twitter" in bold).
Here is the code I am trying to run:
import urllib.request, urllib.parse, urllib.error
import twurl
import ssl
# https://apps.twitter.com/
# Create App and get the four strings, put them in hidden.py
TWITTER_URL = 'https://api.twitter.com/1.1/statuses/user_timeline.json'
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
while True:
print('')
acct = input('Enter Twitter Account:')
if (len(acct) < 1): break
url = twurl.augment(TWITTER_URL,
{'screen_name': acct, 'count': '2'})
print('Retrieving', url)
connection = urllib.request.urlopen(url, context=ctx)
data = connection.read().decode()
print(data[:250])
headers = dict(connection.getheaders())
# print headers
print('Remaining', headers['x-rate-limit-remaining'])
And here is the error that code returns:
Enter Twitter Account:drchuck
Retrieving https://api.twitter.com/1.1/statuses/user_timeline.json?oauth_consumer_key=9uxUyq33IRxCL5CZf7LyfubX3&oauth_timestamp=1641148177&oauth_nonce=80764354&oauth_version=1.0&screen_name=drchuck&count=2&oauth_token=1423673018467983360-Tg6vMoRAWO7FCgnGKhz9WgrPUoCsZa&oauth_signature_method=HMAC-SHA1&oauth_signature=C%2FQIvEhgZ8AQQooC4E%2BekJSZwjE%3D
Traceback (most recent call last):
File "/Users/jguinn/env/twtr-api-demo/twitter1.py", line 23, in <module>
connection = urllib.request.urlopen(url, context=ctx)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 216, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 525, in open
response = meth(req, response)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 634, in http_response
response = self.parent.error(
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 563, in error
return self._call_chain(*args)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 496, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 643, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
I went on the Twitter developer website to look for information about response codes and Twitter says that 403: Forbidden codes means that:
"The request is understood, but it has been refused or access is not
allowed. An accompanying error message will explain why."
As a solution they suggest:
"Check that your developer account includes access to the endpoint
you’re trying to use. You may also need to get your App allowlisted
(e.g. Engagement API or Ads API) or sign up for access."
I am not really sure what any of this means. Any help would be greatly appreciated. Thanks.
2
Answers
I don’t know if you resolved the issue yet but here’s how I did it.
You have to go on your developer portal on twitter and apply for Elevated access. It’s a pretty smooth process and once you’ve done that you’ll be good.
The problem is not with the code, the code is absolutely right.
Step one: Sign up for a developer account on Twitter
Step two: upgrade it to Elevated Access (it’s free)
Step three: After that generate APT Key, API Secret, Access Token, and Acess Token Secret
The only thing you have to change is the consumer_key, consumer_secret, token_key, and token_secret in the hidden.py file. (consumer_key = API Key, consumer_secret = API Key Secret, token_key = Access Token, and token_secret = Access Token Secret)