I wrote this python code to find a particular user in twitter based on some text. Should be pretty straightforward based on the docs plus it is part of the standard API but I am having trouble with the authentication. I found this similar post in c# but I do not know how to adapt it to python. I would prefer to query the API directly and to not use python twitter libraries.

Help would be heartily appreciated :smiling_face_with_three_hearts:


import requests
import os
import json

def auth():
    return os.environ.get("BEARER_TOKEN")


# https://en.wikipedia.org/wiki/Percent-encoding
def create_url(query):
    url = f"https://api.twitter.com/1.1/users/search.json?q={query}"
    return url

def create_headers(bearer_token):
    headers = {"Authorization": "Bearer {}".format(bearer_token)}
    return headers


def connect_to_endpoint(url, headers):
    response = requests.request("GET", url, headers=headers)
    print(response.status_code)
    if response.status_code != 200:
        raise Exception(
            "Request returned an error: {} {}".format(
                response.status_code, response.text
            )
        )
    return response.json()



bearer_token = auth()
url = create_url("soccer")
headers = create_headers(bearer_token)
json_response = connect_to_endpoint(url, headers)
print(json.dumps(json_response, indent=4, sort_keys=True))

According to GET users/search | Docs | Twitter Developer Platform

Requires authentication? Yes (user context only)

This endpoint cannot use Bearer authentication (Bearer Auth is Application Only) so you would have to use a Consumer Key & Secret and an access token & secret belonging to a user.

I would prefer to query the API directly and to not use python twitter libraries.

Why this constraint? You are already using requests which is a 3rd party library, so using something like TwitterAPI would make your life a lot easier (underneath TwitterAPI is also using requests to make the calls): TwitterAPI/search_tweets.py at master · geduldig/TwitterAPI · GitHub (this example uses tweet search, but you can change the endpoint to use user search)

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.