Search code examples
pythontwittertwitter-oauth

How do I form a search query in python for Twitter's search API?


I got past the authentication part, but I have no idea how to form a query for the search part.

Authentication: https://developer.twitter.com/en/docs/basics/authentication/oauth-2-0/bearer-tokens

import base64
import os
import requests
import urllib.parse

CONSUMER_KEY = os.environ.get("CONSUMER_KEY")
CONSUMER_SECRET = os.environ.get("CONSUMER_SECRET")
OAUTH2_ENDPOINT = "https://api.twitter.com/oauth2/token"

def get_bearer_token(consumer_key, consumer_secret):
    consumer_key = urllib.parse.quote(consumer_key)
    consumer_secret = urllib.parse.quote(consumer_secret)
    bearer_token = consumer_key + ":" + consumer_secret
    base64_encoded_bearer_token = base64.b64encode(bearer_token.encode('utf-8'))
    headers = {
        "Authorization": "Basic " + base64_encoded_bearer_token.decode('utf-8') + "",
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        "Content-Length": "29"
    }
    data = {
        "grant_type": "client_credentials"
    }
    response = requests.post(OAUTH2_ENDPOINT, headers=headers, data=data)
    to_json = response.json()
    access_token = to_json["access_token"]

if __name__ == "__main__":
    get_bearer_token(CONSUMER_KEY, CONSUMER_SECRET)

Search API: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets

I'm not really sure how to turn that "example requests" into a response query in python


Solution

  • You need to use the consumer key that is returned to you for a further request. In the documentation you can see that there is a curl request where you add, in the header, the token. This is what I would do:

    With requests do a GET request with headers, where in the header you have the authorization key filled with this sort of value.

    'authorization: OAuth oauth_consumer_key="consumer-key-for-app"

    And as payload to pass in params s a dictionary with your search term q and other stuff that twitter gives as parameter options.

    {'q': 'my search term', 'lang':'language'}

    r = requests.get(url, headers=headers, params=payload)
    

    r will be the response, which you can then turn into json for further manipulation with

    r.json()