Skip to content

Instantly share code, notes, and snippets.

@ryumei
Created May 10, 2018 09:32
Show Gist options
  • Save ryumei/38134bb42f0dc531a6dae0b350b00c8a to your computer and use it in GitHub Desktop.
Save ryumei/38134bb42f0dc531a6dae0b350b00c8a to your computer and use it in GitHub Desktop.
Sample of Twitter Standard Search API Python Requests
import requests
import os
apikey = os.environ['TWITTER_TOKEN']
BASE_URL = 'https://api.twitter.com/1.1/search/tweets.json'
def get_tweets(query, apikey, base_url=BASE_URL, next_results=None):
headers = {"Authorization": "Bearer {key}".format(key=apikey)}
if next_results is None:
url = base_url
params = {'q': query}
else:
url = '{}{}'.format(base_url, next_results)
params = None
res = requests.get(url, headers=headers, params=params)
res.raise_for_status()
data = res.json()
for tweet in data['statuses']:
yield tweet
metadata = data['search_metadata']
if 'next_results' in metadata:
get_tweets(query, apikey, next_results=metadata['next_results'])
data = get_tweets('from:lyumei', apikey=apikey)
for t in data:
print(t['id'], t['text'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment