skip to Main Content

I was trying to hit Twitter API to retrieve data from POSTMAN but I am stuck at an error.

I have created a project in Twitter and then created an app which is associated with the twitter project. Retrieved the Key, Secret and Bearer Token. I hit the below endpoint with Bearer token and got the error

endpoint : https://api.twitter.com/2/tweets?ids=1261326399320715264,1278347468690915330

Error: When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal.

Then I hot the same endpoint using OAuth 1.0 with Consumer Key, Consumer Secret, Access Token and Access Secret and getting the below error

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

I do not understand what I am missing there. Can someone please help with this?

Edit by Espoir Murhabazi: I have tried to use beared token to authenticate as shown in this example but in vain

I tried to use the authentication scheme used by tweepy but also in vain. I look like there is something we are missing.

Here is a full example of what I have tried:

import requests
import os
import sys
from tweepy import OAuthHandler
from dotenv import load_dotenv


load_dotenv()


def get_twitter_auth():
    """Setup Twitter authentication.

    Return: tweepy.OAuthHandler object
    """
    try:
        consumer_key = os.getenv('TWITTER_CONSUMER_KEY')
        consumer_secret = os.getenv('TWITTER_CONSUMER_SECRET')
        access_token = os.getenv('TWITTER_ACCESS_TOKEN')
        access_secret = os.getenv('TWITTER_ACCESS_SECRET')
        assert all([consumer_key, access_secret, access_token, consumer_secret])
    except KeyError:
        sys.stderr.write("TWITTER_*  not foundn")
        sys.exit(1)
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_secret)
    return auth.apply_auth()


protected_url = "https://ads-api.twitter.com/9/insights/keywords/search?granularity=HOUR&keywords=developers&start_time=2021-07-02T10:00:00Z"
oauth = get_twitter_auth()
response = requests.get(url=protected_url, auth=oauth)

print(response.content, 10 * "**=|")

Thanks

4

Answers


  1. Bearer Tokens are the predominant type of access token used with OAuth 2.0. A Bearer Token is an opaque string, not intended to have any meaning to clients using it. Instead of using a bearer token try with the access_token and access_token_secret. For more info refer this

    Login or Signup to reply.
  2. Add your bearer token(received from twitter developer account) in the Authorization tab of postman[see attached image] and then request. I was able to get response for endpoint you mention.
    enter image description here

    Login or Signup to reply.
  3. Goto :

    https://developer.twitter.com/en/portal/projects/new

    Create a new app , and copy the bearer token that will be generated

    enter image description here

    and in postman use :

    enter image description here

    output:

    enter image description here

    Login or Signup to reply.
  4. First make sure you are using GET request instead of the other request type for this specific request (as shown in their docs here with a Postman example. I just tried to use POST and I got the same error, but works fine on GET request. This is the result I get with the URL in the question copied and pasted without any edits; and using GET request with Bearer Token as my authentication:

    {
        "data": [
            {
                "id": "1261326399320715264",
                "text": "Tune in to the @MongoDB @Twitch stream featuring our very own @suhemparack to learn about Twitter Developer Labs - starting now! https://twitter.com/MongoDB/status/1261091720801980419"
            },
            {
                "id": "1278347468690915330",
                "text": "Good news and bad news: nn2020 is half over"
            }
        ]
    }
    

    url in the above snippet was edited and replaced with the full URL as StackOverflow doesn’t accept shortened URLs.

    To change the request type do the following:

    1. Open Postman
    2. Click on the select input (also called combo box) on the left side of the URL input textbox (where you wrote the URL https://api.twitter.com/2/tweets?ids=1261326399320715264,1278347468690915330). Shouldn’t be hard to see.
    3. Select GET on the options. If that doesn’t work then it’s time to reset your keys.

    To reset your keys (called regenerating according to Twitter) do the following (you may skip this whole process if the above solved your issue):

    1. go to your project in your Twitter developer account.
    2. In the main view for your project you should see your apps with two icons; a gear and key icon. Look for the app you want to edit, click on the key icon next to it
    3. On the next page you can regenerate any of the keys you might have lost access to. If you choose to regenerate the Bearer Token, click on regenerate on the same line with the Bearer Token text.
    4. You can now copy the Bearer Token to your clipboard, I recommend copying it to somewhere safe so you don’t have to keep resetting.
    5. After copying the Bearer Token, open postman
    6. Duplicate the tab with the GET request
    7. Under the URL textbox there should be a tab written Authorisation. Click on it.
    8. Under that tab there should be a select input (combobox) with the label type, click on it and select Bearer Token.
    9. On the right there will appear an input with the label token on its left side. Go to that input and paste your URL, use the same exact one you used in the question as it works as is.
    10. For the final step, press Enter or go to the button written Send on the right side of the URL textbox. If everything was done correctly you should have your results.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search