You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Postman调用Twitter API遇认证失败问题求助(Bearer Token/OAuth 1.0均报错)

Troubleshooting Twitter API Authentication Failures

Let’s work through your authentication issues step by step, since both Bearer Token and OAuth 1.0 methods are failing—and there’s a clear issue in your Tweepy code that’s contributing to the problem.

1. Bearer Token Error: "Must use keys from an App attached to a Project"

Even though you mentioned creating a Project and linking an App, double-check these critical details:

  • Verify App-Project association: Go to your Twitter Developer Portal → Projects & Apps → Confirm your App is listed under the correct Project. Sometimes Apps get created outside a Project accidentally, or are moved later.
  • Regenerate your Bearer Token: Old tokens might be tied to an unlinked App. Navigate to your App’s Keys and Tokens tab, scroll to Bearer Token, click Regenerate, and use this new token immediately.
  • Check App permissions: Ensure your App has the required access for the endpoint. For the tweets endpoint, you need at least Read-only access. Go to User authentication settings → Under App permissions, select Read and save changes.

2. OAuth 1.0 401 Unauthorized Error

For OAuth 1.0 issues, focus on these checks:

  • Match credentials to the same App: Confirm your Consumer Key/Secret and Access Token/Secret all belong to the same App linked to your Project. Mixing credentials from different Apps will trigger 401s.
  • Validate Access Token authorization: If you generated the Access Token manually, make sure you completed the full OAuth authorization flow (logging into your Twitter account to grant App access). Tokens created without this flow won’t work.
  • Check endpoint permissions: Just like with Bearer Token, ensure your App has the right permissions (Read-only is enough for fetching tweets).

3. Critical Issue in Your Tweepy Code

Your code has two major problems causing failures:

a. Wrong API Endpoint

You’re trying to call the Twitter Ads API (https://ads-api.twitter.com/9/insights/keywords/search), which requires separate Ads access and permissions—this is not the endpoint for fetching public tweets. Swap it for the correct v2 endpoint you tested earlier.

b. Authentication Method Misuse

Tweepy’s apply_auth() returns a tuple that isn’t compatible with requests’ auth parameter. Instead, pass the OAuthHandler object directly. Also, your assertion had a duplicate consumer_secret (typo).

Here’s the corrected code:

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

load_dotenv()

def get_twitter_auth():
    """Setup Twitter authentication. Returns 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')
        # Fix duplicate parameter in assertion
        assert all([consumer_key, consumer_secret, access_token, access_secret]), "Missing Twitter credentials"
    except AssertionError as e:
        sys.stderr.write(f"Error: {e}\n")
        sys.exit(1)
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_secret)
    return auth

# Use the correct v2 tweets endpoint
protected_url = "https://api.twitter.com/2/tweets?ids=1261326399320715264,1278347468690915330"
oauth = get_twitter_auth()
response = requests.get(url=protected_url, auth=oauth)

# Print status code and response for debugging
print(f"Status Code: {response.status_code}")
print(f"Response: {response.json()}")

Final Checklist to Ensure Success

  1. All credentials (Keys, Tokens, Secrets) belong to the same App linked to your Project.
  2. Your App has the correct permissions (Read-only for tweet fetching).
  3. You’re using the right API endpoint (avoid Ads API unless you have access).
  4. Regenerate tokens if you made any changes to App settings or Project links.

内容的提问来源于stack exchange,提问作者sac

火山引擎 最新活动