Mohammad Saad
Mohammad Saad

Reputation: 2005

API call (python) from twitter returns Unauthorized error but works on Postman

I recently tried getting organic metrics for a tweet using postman. My trial on postman was successful, I used Oauth 1.0 for authorization. And from this example I extracted the python syntax for the API request.

The following is the sample code:

import requests
url = "https://api.twitter.com/2/tweets/123456789?tweet.fields=non_public_metrics,organic_metrics"
payload={}
headers = {
  'Authorization': 'OAuth oauth_consumer_key="xxxxxxxxxx",oauth_token="xxxxxxxxxx",oauth_signature_method="HMAC-SHA1",oauth_timestamp="123432343",oauth_nonce="abcdefgh",oauth_version="1.0",oauth_signature="xxxxxxx"'
}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)

However, when i try to run this as a standalone python script it returns unauthorized error while through postman it works. May I ask what could be the cause of this behavior?

Error:

{
  "title": "Unauthorized",
  "type": "about:blank",
  "status": 401,
  "detail": "Unauthorized"
}

Look forward to the suggestions! Thanks.

Upvotes: 1

Views: 559

Answers (1)

Mohammad Saad
Mohammad Saad

Reputation: 2005

To work with user context on twitter API use requests_oauthlib class. You can find a simple implementation below in python:

consumer_key = "xxxxxxxx"
consumer_secret = "xxxxxxxxx"
access_token = "xxxxxxxxxxx"
access_token_secret = "xxxxxxxxxxxx"

from requests_oauthlib import OAuth1Session
params = {"ids": "123234343"}
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
)

This implementation requires you to have the all the key parameters like consumer key, consumer secret, access_token and access token secret. Please visit your twitter dev page to generate all the values (if you are not sure you can follow their docs https://developer.twitter.com/en/docs/authentication/oauth-1-0a/api-key-and-secret )

Thanks, hope it helps others!

Upvotes: 1

Related Questions