Search code examples
pythonapitwittertweepyrate-limiting

Twitter API V2, return the x-rate-limit-limit, x-rate-limit-remaining, x-rate-limit-reset


Hello fellow overflowers.

I'm new to Twitter API. I'm using python. I'm using Tweepy library. I have the elevated access of twitter API, and I'm trying to get the rate limit information of the 15 min window.

  1. I want the amount of time left in the 15 min window.
  2. I want to know how much requests I have left in the 15 min window
  3. and the rate limit ceiling for the endpoint.

Reference of what I want in twitter docs :

  • x-rate-limit-limit: the rate limit ceiling for that given endpoint.
  • x-rate-limit-remaining: the number of requests left for the 15-minute window.
  • x-rate-limit-reset: the remaining window before the rate limit resets, in UTC epoch seconds.

Twitter Docs : https://developer.twitter.com/en/docs/twitter-api/rate-limits#headers-and-codes

I did a bit of search but cannot find anything on how to do it. I found this Github sample code from twitter but still nothing: https://github.com/twitterdev/Twitter-API-v2-sample-code

And also on Tweepy I couldn't find anything: https://docs.tweepy.org/en/stable/client.html

But I can see the amount of requests when I use the request live from twitter self, but it's only 180 requests per 15 min, so its using the User-rate-limit and not the application-rate-limit :

https://oauth-playground.glitch.me/?id=tweetsRecentSearch&params=%28%27query%21%27from%3ATwitterDev%27%7Ebody%21%27%27%7Epath%21%28%29%29_

Does anyone know how to do this ? Thnx in advance👌.


Solution

  • The function search_recent_tweets from tweepy.Client returns an object with type tweepy.client.Response, which does not contain information regarding rate limits. Unfortunately, this means you won't be able to get it using tweepy.

    An alternative could be to make the request yourself with a code like this:

    import requests
    
    def bearer_oauth(r):
        r.headers["Authorization"] = f"Bearer {bearer}"
        return r
    
    bearer = "your bearer token"
    
    params = {"query": "your search"}
        
    response = requests.get("https://api.twitter.com/2/tweets/search/recent", params=params, auth=bearer_oauth)
    

    After running that code, you will find rate limit information on response.headers.